Completed
Branch gutenberg/main (ad8606)
by
unknown
11:08 queued 09:12
created
core/domain/services/event/EventSpacesCalculator.php 2 patches
Indentation   +698 added lines, -698 removed lines patch added patch discarded remove patch
@@ -26,702 +26,702 @@
 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
-        $this->event = $event;
117
-        $this->datetime_query_params = $datetime_query_params + array('order_by' => array('DTT_reg_limit' => 'ASC'));
118
-        $this->setHooks();
119
-    }
120
-
121
-
122
-    /**
123
-     * @return void
124
-     */
125
-    private function setHooks()
126
-    {
127
-        add_action('AHEE__EE_Ticket__increase_sold', array($this, 'clearResults'));
128
-        add_action('AHEE__EE_Ticket__decrease_sold', array($this, 'clearResults'));
129
-        add_action('AHEE__EE_Datetime__increase_sold', array($this, 'clearResults'));
130
-        add_action('AHEE__EE_Datetime__decrease_sold', array($this, 'clearResults'));
131
-        add_action('AHEE__EE_Ticket__increase_reserved', array($this, 'clearResults'));
132
-        add_action('AHEE__EE_Ticket__decrease_reserved', array($this, 'clearResults'));
133
-        add_action('AHEE__EE_Datetime__increase_reserved', array($this, 'clearResults'));
134
-        add_action('AHEE__EE_Datetime__decrease_reserved', array($this, 'clearResults'));
135
-    }
136
-
137
-
138
-    /**
139
-     * @return void
140
-     */
141
-    public function clearResults()
142
-    {
143
-        $this->spaces_remaining = null;
144
-        $this->total_spaces_available = null;
145
-    }
146
-
147
-
148
-    /**
149
-     * @return EE_Ticket[]
150
-     * @throws EE_Error
151
-     * @throws InvalidDataTypeException
152
-     * @throws InvalidInterfaceException
153
-     * @throws InvalidArgumentException
154
-     */
155
-    public function getActiveTickets()
156
-    {
157
-        if (empty($this->active_tickets)) {
158
-            $this->active_tickets = $this->event->tickets(
159
-                array(
160
-                    array('TKT_deleted' => false),
161
-                    'order_by' => array('TKT_qty' => 'ASC'),
162
-                )
163
-            );
164
-        }
165
-        return $this->active_tickets;
166
-    }
167
-
168
-
169
-    /**
170
-     * @param EE_Ticket[] $active_tickets
171
-     * @throws EE_Error
172
-     * @throws DomainException
173
-     * @throws UnexpectedEntityException
174
-     */
175
-    public function setActiveTickets(array $active_tickets = array())
176
-    {
177
-        if (! empty($active_tickets)) {
178
-            foreach ($active_tickets as $active_ticket) {
179
-                $this->validateTicket($active_ticket);
180
-            }
181
-            // sort incoming array by ticket quantity (asc)
182
-            usort(
183
-                $active_tickets,
184
-                function (EE_Ticket $a, EE_Ticket $b) {
185
-                    if ($a->qty() === $b->qty()) {
186
-                        return 0;
187
-                    }
188
-                    return ($a->qty() < $b->qty())
189
-                        ? -1
190
-                        : 1;
191
-                }
192
-            );
193
-        }
194
-        $this->active_tickets = $active_tickets;
195
-    }
196
-
197
-
198
-    /**
199
-     * @param $ticket
200
-     * @throws DomainException
201
-     * @throws EE_Error
202
-     * @throws UnexpectedEntityException
203
-     */
204
-    private function validateTicket($ticket)
205
-    {
206
-        if (! $ticket instanceof EE_Ticket) {
207
-            throw new DomainException(
208
-                esc_html__(
209
-                    'Invalid Ticket. Only EE_Ticket objects can be used to calculate event space availability.',
210
-                    'event_espresso'
211
-                )
212
-            );
213
-        }
214
-        if ($ticket->get_event_ID() !== $this->event->ID()) {
215
-            throw new DomainException(
216
-                sprintf(
217
-                    esc_html__(
218
-                        'An EE_Ticket for Event %1$d was supplied while calculating event space availability for Event %2$d.',
219
-                        'event_espresso'
220
-                    ),
221
-                    $ticket->get_event_ID(),
222
-                    $this->event->ID()
223
-                )
224
-            );
225
-        }
226
-    }
227
-
228
-
229
-    /**
230
-     * @return EE_Datetime[]
231
-     */
232
-    public function getDatetimes()
233
-    {
234
-        return $this->datetimes;
235
-    }
236
-
237
-
238
-    /**
239
-     * @param EE_Datetime $datetime
240
-     * @throws EE_Error
241
-     * @throws DomainException
242
-     */
243
-    public function setDatetime(EE_Datetime $datetime)
244
-    {
245
-        if ($datetime->event()->ID() !== $this->event->ID()) {
246
-            throw new DomainException(
247
-                sprintf(
248
-                    esc_html__(
249
-                        'An EE_Datetime for Event %1$d was supplied while calculating event space availability for Event %2$d.',
250
-                        'event_espresso'
251
-                    ),
252
-                    $datetime->event()->ID(),
253
-                    $this->event->ID()
254
-                )
255
-            );
256
-        }
257
-        $this->datetimes[ $datetime->ID() ] = $datetime;
258
-    }
259
-
260
-
261
-    /**
262
-     * calculate spaces remaining based on "saleable" tickets
263
-     *
264
-     * @return float|int
265
-     * @throws EE_Error
266
-     * @throws DomainException
267
-     * @throws UnexpectedEntityException
268
-     * @throws InvalidDataTypeException
269
-     * @throws InvalidInterfaceException
270
-     * @throws InvalidArgumentException
271
-     */
272
-    public function spacesRemaining()
273
-    {
274
-        if ($this->spaces_remaining === null) {
275
-            $this->initialize();
276
-            $this->spaces_remaining = $this->calculate();
277
-        }
278
-        return $this->spaces_remaining;
279
-    }
280
-
281
-
282
-    /**
283
-     * calculates total available spaces for an event with no regard for sold tickets
284
-     *
285
-     * @return int|float
286
-     * @throws EE_Error
287
-     * @throws DomainException
288
-     * @throws UnexpectedEntityException
289
-     * @throws InvalidDataTypeException
290
-     * @throws InvalidInterfaceException
291
-     * @throws InvalidArgumentException
292
-     */
293
-    public function totalSpacesAvailable()
294
-    {
295
-        if ($this->total_spaces_available === null) {
296
-            $this->initialize();
297
-            $this->total_spaces_available = $this->calculate(false);
298
-        }
299
-        return $this->total_spaces_available;
300
-    }
301
-
302
-
303
-    /**
304
-     * Loops through the active tickets for the event
305
-     * and builds a series of data arrays that will be used for calculating
306
-     * the total maximum available spaces, as well as the spaces remaining.
307
-     * Because ticket quantities affect datetime spaces and vice versa,
308
-     * we need to be constantly updating these data arrays as things change,
309
-     * which is the entire reason for their existence.
310
-     *
311
-     * @throws EE_Error
312
-     * @throws DomainException
313
-     * @throws UnexpectedEntityException
314
-     * @throws InvalidDataTypeException
315
-     * @throws InvalidInterfaceException
316
-     * @throws InvalidArgumentException
317
-     */
318
-    private function initialize()
319
-    {
320
-        if ($this->debug) {
321
-            \EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
322
-        }
323
-        $this->datetime_tickets = array();
324
-        $this->datetime_spaces = array();
325
-        $this->ticket_datetimes = array();
326
-        $this->ticket_quantities = array();
327
-        $this->tickets_sold = array();
328
-        $this->total_spaces = array();
329
-        $active_tickets = $this->getActiveTickets();
330
-        if (! empty($active_tickets)) {
331
-            foreach ($active_tickets as $ticket) {
332
-                $this->validateTicket($ticket);
333
-                // we need to index our data arrays using strings for the purpose of sorting,
334
-                // but we also need them to be unique, so  we'll just prepend a letter T to the ID
335
-                $ticket_identifier = "T{$ticket->ID()}";
336
-                // to start, we'll just consider the raw qty to be the maximum availability for this ticket,
337
-                // unless the ticket is past its "sell until" date, in which case the qty will be 0
338
-                $max_tickets = $ticket->is_expired() ? 0 : $ticket->qty();
339
-                // but we'll adjust that after looping over each datetime for the ticket and checking reg limits
340
-                $ticket_datetimes = $ticket->datetimes($this->datetime_query_params);
341
-                foreach ($ticket_datetimes as $datetime) {
342
-                    // save all datetimes
343
-                    $this->setDatetime($datetime);
344
-                    $datetime_identifier = "D{$datetime->ID()}";
345
-                    $reg_limit = $datetime->reg_limit();
346
-                    // ticket quantity can not exceed datetime reg limit
347
-                    $max_tickets = min($max_tickets, $reg_limit);
348
-                    // as described earlier, because we need to be able to constantly adjust numbers for things,
349
-                    // we are going to move all of our data into the following arrays:
350
-                    // datetime spaces initially represents the reg limit for each datetime,
351
-                    // but this will get adjusted as tickets are accounted for
352
-                    $this->datetime_spaces[ $datetime_identifier ] = $reg_limit;
353
-                    // just an array of ticket IDs grouped by datetime
354
-                    $this->datetime_tickets[ $datetime_identifier ][] = $ticket_identifier;
355
-                    // and an array of datetime IDs grouped by ticket
356
-                    $this->ticket_datetimes[ $ticket_identifier ][] = $datetime_identifier;
357
-                }
358
-                // total quantity of sold and reserved for each ticket
359
-                $this->tickets_sold[ $ticket_identifier ] = $ticket->sold() + $ticket->reserved();
360
-                // and the maximum ticket quantities for each ticket (adjusted for reg limit)
361
-                $this->ticket_quantities[ $ticket_identifier ] = $max_tickets;
362
-            }
363
-        }
364
-        // sort datetime spaces by reg limit, but maintain our string indexes
365
-        asort($this->datetime_spaces, SORT_NUMERIC);
366
-        // datetime tickets need to be sorted in the SAME order as the above array...
367
-        // so we'll just use array_merge() to take the structure of datetime_spaces
368
-        // but overwrite all of the data with that from datetime_tickets
369
-        $this->datetime_tickets = array_merge(
370
-            $this->datetime_spaces,
371
-            $this->datetime_tickets
372
-        );
373
-        if ($this->debug) {
374
-            \EEH_Debug_Tools::printr($this->datetime_spaces, 'datetime_spaces', __FILE__, __LINE__);
375
-            \EEH_Debug_Tools::printr($this->datetime_tickets, 'datetime_tickets', __FILE__, __LINE__);
376
-            \EEH_Debug_Tools::printr($this->ticket_quantities, 'ticket_quantities', __FILE__, __LINE__);
377
-        }
378
-    }
379
-
380
-
381
-    /**
382
-     * performs calculations on initialized data
383
-     *
384
-     * @param bool $consider_sold
385
-     * @return int|float
386
-     */
387
-    private function calculate($consider_sold = true)
388
-    {
389
-        if ($this->debug) {
390
-            \EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
391
-            \EEH_Debug_Tools::printr($consider_sold, '$consider_sold', __FILE__, __LINE__);
392
-        }
393
-        if ($consider_sold) {
394
-            // subtract amounts sold from all ticket quantities and datetime spaces
395
-            $this->adjustTicketQuantitiesDueToSales();
396
-        }
397
-        foreach ($this->datetime_tickets as $datetime_identifier => $tickets) {
398
-            $this->trackAvailableSpacesForDatetimes($datetime_identifier, $tickets);
399
-        }
400
-        // total spaces available is just the sum of the spaces available for each datetime
401
-        $spaces_remaining = array_sum($this->total_spaces);
402
-        if ($this->debug) {
403
-            \EEH_Debug_Tools::printr($this->total_spaces, '$this->total_spaces', __FILE__, __LINE__);
404
-            \EEH_Debug_Tools::printr($this->tickets_sold, '$this->tickets_sold', __FILE__, __LINE__);
405
-            \EEH_Debug_Tools::printr($spaces_remaining, '$spaces_remaining', __FILE__, __LINE__);
406
-        }
407
-        return $spaces_remaining;
408
-    }
409
-
410
-
411
-    /**
412
-     * subtracts amount of  tickets sold from ticket quantities and datetime spaces
413
-     */
414
-    private function adjustTicketQuantitiesDueToSales()
415
-    {
416
-        if ($this->debug) {
417
-            \EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
418
-        }
419
-        foreach ($this->tickets_sold as $ticket_identifier => $tickets_sold) {
420
-            if (isset($this->ticket_quantities[ $ticket_identifier ])) {
421
-                $this->ticket_quantities[ $ticket_identifier ] -= $tickets_sold;
422
-                // don't let values go below zero
423
-                $this->ticket_quantities[ $ticket_identifier ] = max(
424
-                    $this->ticket_quantities[ $ticket_identifier ],
425
-                    0
426
-                );
427
-                if ($this->debug) {
428
-                    \EEH_Debug_Tools::printr(
429
-                        "{$tickets_sold} sales for ticket {$ticket_identifier} ",
430
-                        'subtracting',
431
-                        __FILE__,
432
-                        __LINE__
433
-                    );
434
-                }
435
-            }
436
-            if (isset($this->ticket_datetimes[ $ticket_identifier ])
437
-                && is_array($this->ticket_datetimes[ $ticket_identifier ])
438
-            ) {
439
-                foreach ($this->ticket_datetimes[ $ticket_identifier ] as $ticket_datetime) {
440
-                    if (isset($this->ticket_quantities[ $ticket_identifier ])) {
441
-                        $this->datetime_spaces[ $ticket_datetime ] -= $tickets_sold;
442
-                        // don't let values go below zero
443
-                        $this->datetime_spaces[ $ticket_datetime ] = max(
444
-                            $this->datetime_spaces[ $ticket_datetime ],
445
-                            0
446
-                        );
447
-                        if ($this->debug) {
448
-                            \EEH_Debug_Tools::printr(
449
-                                "{$tickets_sold} sales for datetime {$ticket_datetime} ",
450
-                                'subtracting',
451
-                                __FILE__,
452
-                                __LINE__
453
-                            );
454
-                        }
455
-                    }
456
-                }
457
-            }
458
-        }
459
-    }
460
-
461
-
462
-    /**
463
-     * @param string $datetime_identifier
464
-     * @param array  $tickets
465
-     */
466
-    private function trackAvailableSpacesForDatetimes($datetime_identifier, array $tickets)
467
-    {
468
-        // make sure a reg limit is set for the datetime
469
-        $reg_limit = isset($this->datetime_spaces[ $datetime_identifier ])
470
-            ? $this->datetime_spaces[ $datetime_identifier ]
471
-            : 0;
472
-        // and bail if it is not
473
-        if (! $reg_limit) {
474
-            if ($this->debug) {
475
-                \EEH_Debug_Tools::printr('AT CAPACITY', " . {$datetime_identifier}", __FILE__, __LINE__);
476
-            }
477
-            return;
478
-        }
479
-        if ($this->debug) {
480
-            \EEH_Debug_Tools::printr($datetime_identifier, '* $datetime_identifier', __FILE__, __LINE__, 1);
481
-            \EEH_Debug_Tools::printr(
482
-                "{$reg_limit}",
483
-                'REG LIMIT',
484
-                __FILE__,
485
-                __LINE__
486
-            );
487
-        }
488
-        // number of allocated spaces always starts at zero
489
-        $spaces_allocated = 0;
490
-        $this->total_spaces[ $datetime_identifier ] = 0;
491
-        foreach ($tickets as $ticket_identifier) {
492
-            $spaces_allocated = $this->calculateAvailableSpacesForTicket(
493
-                $datetime_identifier,
494
-                $reg_limit,
495
-                $ticket_identifier,
496
-                $spaces_allocated
497
-            );
498
-        }
499
-        // spaces can't be negative
500
-        $spaces_allocated = max($spaces_allocated, 0);
501
-        if ($spaces_allocated) {
502
-            // track any non-zero values
503
-            $this->total_spaces[ $datetime_identifier ] += $spaces_allocated;
504
-            if ($this->debug) {
505
-                \EEH_Debug_Tools::printr((string) $spaces_allocated, ' . $spaces_allocated: ', __FILE__, __LINE__);
506
-            }
507
-        } else {
508
-            if ($this->debug) {
509
-                \EEH_Debug_Tools::printr(' ', ' . NO TICKETS AVAILABLE FOR DATETIME', __FILE__, __LINE__);
510
-            }
511
-        }
512
-        if ($this->debug) {
513
-            \EEH_Debug_Tools::printr(
514
-                $this->total_spaces[ $datetime_identifier ],
515
-                '$total_spaces',
516
-                __FILE__,
517
-                __LINE__
518
-            );
519
-            \EEH_Debug_Tools::printr($this->ticket_quantities, '$ticket_quantities', __FILE__, __LINE__);
520
-            \EEH_Debug_Tools::printr($this->datetime_spaces, 'datetime_spaces', __FILE__, __LINE__);
521
-        }
522
-    }
523
-
524
-
525
-    /**
526
-     * @param string $datetime_identifier
527
-     * @param int    $reg_limit
528
-     * @param string $ticket_identifier
529
-     * @param int    $spaces_allocated
530
-     * @return int
531
-     */
532
-    private function calculateAvailableSpacesForTicket(
533
-        $datetime_identifier,
534
-        $reg_limit,
535
-        $ticket_identifier,
536
-        $spaces_allocated
537
-    ) {
538
-        // make sure ticket quantity is set
539
-        $ticket_quantity = isset($this->ticket_quantities[ $ticket_identifier ])
540
-            ? $this->ticket_quantities[ $ticket_identifier ]
541
-            : 0;
542
-        if ($this->debug) {
543
-            \EEH_Debug_Tools::printr("{$spaces_allocated}", '$spaces_allocated', __FILE__, __LINE__);
544
-            \EEH_Debug_Tools::printr(
545
-                "{$ticket_quantity}",
546
-                "ticket $ticket_identifier quantity: ",
547
-                __FILE__,
548
-                __LINE__,
549
-                2
550
-            );
551
-        }
552
-        if ($ticket_quantity) {
553
-            if ($this->debug) {
554
-                \EEH_Debug_Tools::printr(
555
-                    ($spaces_allocated <= $reg_limit)
556
-                        ? 'true'
557
-                        : 'false',
558
-                    ' . spaces_allocated <= reg_limit = ',
559
-                    __FILE__,
560
-                    __LINE__
561
-                );
562
-            }
563
-            // if the datetime is NOT at full capacity yet
564
-            if ($spaces_allocated <= $reg_limit) {
565
-                // then the maximum ticket quantity we can allocate is the lowest value of either:
566
-                //  the number of remaining spaces for the datetime, which is the limit - spaces already taken
567
-                //  or the maximum ticket quantity
568
-                $ticket_quantity = min($reg_limit - $spaces_allocated, $ticket_quantity);
569
-                // adjust the available quantity in our tracking array
570
-                $this->ticket_quantities[ $ticket_identifier ] -= $ticket_quantity;
571
-                // and increment spaces allocated for this datetime
572
-                $spaces_allocated += $ticket_quantity;
573
-                $at_capacity = $spaces_allocated >= $reg_limit;
574
-                if ($this->debug) {
575
-                    \EEH_Debug_Tools::printr(
576
-                        "{$ticket_quantity} {$ticket_identifier} tickets",
577
-                        ' > > allocate ',
578
-                        __FILE__,
579
-                        __LINE__,
580
-                        3
581
-                    );
582
-                    if ($at_capacity) {
583
-                        \EEH_Debug_Tools::printr('AT CAPACITY', " . {$datetime_identifier}", __FILE__, __LINE__, 3);
584
-                    }
585
-                }
586
-                // now adjust all other datetimes that allow access to this ticket
587
-                $this->adjustDatetimes(
588
-                    $datetime_identifier,
589
-                    $ticket_identifier,
590
-                    $ticket_quantity,
591
-                    $at_capacity
592
-                );
593
-            }
594
-        }
595
-        return $spaces_allocated;
596
-    }
597
-
598
-
599
-    /**
600
-     * subtracts ticket amounts from all datetime reg limits
601
-     * that allow access to the ticket specified,
602
-     * because that ticket could be used
603
-     * to attend any of the datetimes it has access to
604
-     *
605
-     * @param string $datetime_identifier
606
-     * @param string $ticket_identifier
607
-     * @param bool   $at_capacity
608
-     * @param int    $ticket_quantity
609
-     */
610
-    private function adjustDatetimes(
611
-        $datetime_identifier,
612
-        $ticket_identifier,
613
-        $ticket_quantity,
614
-        $at_capacity
615
-    ) {
616
-        /** @var array $datetime_tickets */
617
-        foreach ($this->datetime_tickets as $datetime_ID => $datetime_tickets) {
618
-            if ($datetime_ID !== $datetime_identifier || ! is_array($datetime_tickets)) {
619
-                continue;
620
-            }
621
-            $adjusted = $this->adjustDatetimeSpaces(
622
-                $datetime_ID,
623
-                $ticket_identifier,
624
-                $ticket_quantity
625
-            );
626
-            // skip to next ticket if nothing changed
627
-            if (! ($adjusted || $at_capacity)) {
628
-                continue;
629
-            }
630
-            // then all of it's tickets are now unavailable
631
-            foreach ($datetime_tickets as $datetime_ticket) {
632
-                if (($ticket_identifier === $datetime_ticket || $at_capacity)
633
-                    && isset($this->ticket_quantities[ $datetime_ticket ])
634
-                    && $this->ticket_quantities[ $datetime_ticket ] > 0
635
-                ) {
636
-                    if ($this->debug) {
637
-                        \EEH_Debug_Tools::printr(
638
-                            $datetime_ticket,
639
-                            ' . . . adjust ticket quantities for',
640
-                            __FILE__,
641
-                            __LINE__
642
-                        );
643
-                    }
644
-                    // if this datetime is at full capacity, set any tracked available quantities to zero
645
-                    // otherwise just subtract the ticket quantity
646
-                    $new_quantity = $at_capacity
647
-                        ? 0
648
-                        : $this->ticket_quantities[ $datetime_ticket ] - $ticket_quantity;
649
-                    // don't let ticket quantity go below zero
650
-                    $this->ticket_quantities[ $datetime_ticket ] = max($new_quantity, 0);
651
-                    if ($this->debug) {
652
-                        \EEH_Debug_Tools::printr(
653
-                            $at_capacity
654
-                                ? "0 because Datetime {$datetime_identifier} is at capacity"
655
-                                : "{$this->ticket_quantities[ $datetime_ticket ]}",
656
-                            " . . . . {$datetime_ticket} quantity set to ",
657
-                            __FILE__,
658
-                            __LINE__
659
-                        );
660
-                    }
661
-                }
662
-                // but we also need to adjust spaces for any other datetimes this ticket has access to
663
-                if ($datetime_ticket === $ticket_identifier) {
664
-                    if (isset($this->ticket_datetimes[ $datetime_ticket ])
665
-                        && is_array($this->ticket_datetimes[ $datetime_ticket ])
666
-                    ) {
667
-                        if ($this->debug) {
668
-                            \EEH_Debug_Tools::printr(
669
-                                $datetime_ticket,
670
-                                ' . . adjust other Datetimes for',
671
-                                __FILE__,
672
-                                __LINE__
673
-                            );
674
-                        }
675
-                        foreach ($this->ticket_datetimes[ $datetime_ticket ] as $datetime) {
676
-                            // don't adjust the current datetime twice
677
-                            if ($datetime !== $datetime_identifier) {
678
-                                $this->adjustDatetimeSpaces(
679
-                                    $datetime,
680
-                                    $datetime_ticket,
681
-                                    $ticket_quantity
682
-                                );
683
-                            }
684
-                        }
685
-                    }
686
-                }
687
-            }
688
-        }
689
-    }
690
-
691
-    private function adjustDatetimeSpaces($datetime_identifier, $ticket_identifier, $ticket_quantity = 0)
692
-    {
693
-        // does datetime have spaces available?
694
-        // and does the supplied ticket have access to this datetime ?
695
-        if ($this->datetime_spaces[ $datetime_identifier ] > 0
696
-            && isset($this->datetime_spaces[ $datetime_identifier ], $this->datetime_tickets[ $datetime_identifier ])
697
-            && in_array($ticket_identifier, $this->datetime_tickets[ $datetime_identifier ], true)
698
-        ) {
699
-            if ($this->debug) {
700
-                \EEH_Debug_Tools::printr($datetime_identifier, ' . . adjust Datetime Spaces for', __FILE__, __LINE__);
701
-                \EEH_Debug_Tools::printr(
702
-                    "{$this->datetime_spaces[ $datetime_identifier ]}",
703
-                    " . . current  {$datetime_identifier} spaces available",
704
-                    __FILE__,
705
-                    __LINE__
706
-                );
707
-            }
708
-            // then decrement the available spaces for the datetime
709
-            $this->datetime_spaces[ $datetime_identifier ] -= $ticket_quantity;
710
-            // but don't let quantities go below zero
711
-            $this->datetime_spaces[ $datetime_identifier ] = max(
712
-                $this->datetime_spaces[ $datetime_identifier ],
713
-                0
714
-            );
715
-            if ($this->debug) {
716
-                \EEH_Debug_Tools::printr(
717
-                    "{$ticket_quantity}",
718
-                    " . . . {$datetime_identifier} capacity reduced by",
719
-                    __FILE__,
720
-                    __LINE__
721
-                );
722
-            }
723
-            return true;
724
-        }
725
-        return false;
726
-    }
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
+		$this->event = $event;
117
+		$this->datetime_query_params = $datetime_query_params + array('order_by' => array('DTT_reg_limit' => 'ASC'));
118
+		$this->setHooks();
119
+	}
120
+
121
+
122
+	/**
123
+	 * @return void
124
+	 */
125
+	private function setHooks()
126
+	{
127
+		add_action('AHEE__EE_Ticket__increase_sold', array($this, 'clearResults'));
128
+		add_action('AHEE__EE_Ticket__decrease_sold', array($this, 'clearResults'));
129
+		add_action('AHEE__EE_Datetime__increase_sold', array($this, 'clearResults'));
130
+		add_action('AHEE__EE_Datetime__decrease_sold', array($this, 'clearResults'));
131
+		add_action('AHEE__EE_Ticket__increase_reserved', array($this, 'clearResults'));
132
+		add_action('AHEE__EE_Ticket__decrease_reserved', array($this, 'clearResults'));
133
+		add_action('AHEE__EE_Datetime__increase_reserved', array($this, 'clearResults'));
134
+		add_action('AHEE__EE_Datetime__decrease_reserved', array($this, 'clearResults'));
135
+	}
136
+
137
+
138
+	/**
139
+	 * @return void
140
+	 */
141
+	public function clearResults()
142
+	{
143
+		$this->spaces_remaining = null;
144
+		$this->total_spaces_available = null;
145
+	}
146
+
147
+
148
+	/**
149
+	 * @return EE_Ticket[]
150
+	 * @throws EE_Error
151
+	 * @throws InvalidDataTypeException
152
+	 * @throws InvalidInterfaceException
153
+	 * @throws InvalidArgumentException
154
+	 */
155
+	public function getActiveTickets()
156
+	{
157
+		if (empty($this->active_tickets)) {
158
+			$this->active_tickets = $this->event->tickets(
159
+				array(
160
+					array('TKT_deleted' => false),
161
+					'order_by' => array('TKT_qty' => 'ASC'),
162
+				)
163
+			);
164
+		}
165
+		return $this->active_tickets;
166
+	}
167
+
168
+
169
+	/**
170
+	 * @param EE_Ticket[] $active_tickets
171
+	 * @throws EE_Error
172
+	 * @throws DomainException
173
+	 * @throws UnexpectedEntityException
174
+	 */
175
+	public function setActiveTickets(array $active_tickets = array())
176
+	{
177
+		if (! empty($active_tickets)) {
178
+			foreach ($active_tickets as $active_ticket) {
179
+				$this->validateTicket($active_ticket);
180
+			}
181
+			// sort incoming array by ticket quantity (asc)
182
+			usort(
183
+				$active_tickets,
184
+				function (EE_Ticket $a, EE_Ticket $b) {
185
+					if ($a->qty() === $b->qty()) {
186
+						return 0;
187
+					}
188
+					return ($a->qty() < $b->qty())
189
+						? -1
190
+						: 1;
191
+				}
192
+			);
193
+		}
194
+		$this->active_tickets = $active_tickets;
195
+	}
196
+
197
+
198
+	/**
199
+	 * @param $ticket
200
+	 * @throws DomainException
201
+	 * @throws EE_Error
202
+	 * @throws UnexpectedEntityException
203
+	 */
204
+	private function validateTicket($ticket)
205
+	{
206
+		if (! $ticket instanceof EE_Ticket) {
207
+			throw new DomainException(
208
+				esc_html__(
209
+					'Invalid Ticket. Only EE_Ticket objects can be used to calculate event space availability.',
210
+					'event_espresso'
211
+				)
212
+			);
213
+		}
214
+		if ($ticket->get_event_ID() !== $this->event->ID()) {
215
+			throw new DomainException(
216
+				sprintf(
217
+					esc_html__(
218
+						'An EE_Ticket for Event %1$d was supplied while calculating event space availability for Event %2$d.',
219
+						'event_espresso'
220
+					),
221
+					$ticket->get_event_ID(),
222
+					$this->event->ID()
223
+				)
224
+			);
225
+		}
226
+	}
227
+
228
+
229
+	/**
230
+	 * @return EE_Datetime[]
231
+	 */
232
+	public function getDatetimes()
233
+	{
234
+		return $this->datetimes;
235
+	}
236
+
237
+
238
+	/**
239
+	 * @param EE_Datetime $datetime
240
+	 * @throws EE_Error
241
+	 * @throws DomainException
242
+	 */
243
+	public function setDatetime(EE_Datetime $datetime)
244
+	{
245
+		if ($datetime->event()->ID() !== $this->event->ID()) {
246
+			throw new DomainException(
247
+				sprintf(
248
+					esc_html__(
249
+						'An EE_Datetime for Event %1$d was supplied while calculating event space availability for Event %2$d.',
250
+						'event_espresso'
251
+					),
252
+					$datetime->event()->ID(),
253
+					$this->event->ID()
254
+				)
255
+			);
256
+		}
257
+		$this->datetimes[ $datetime->ID() ] = $datetime;
258
+	}
259
+
260
+
261
+	/**
262
+	 * calculate spaces remaining based on "saleable" tickets
263
+	 *
264
+	 * @return float|int
265
+	 * @throws EE_Error
266
+	 * @throws DomainException
267
+	 * @throws UnexpectedEntityException
268
+	 * @throws InvalidDataTypeException
269
+	 * @throws InvalidInterfaceException
270
+	 * @throws InvalidArgumentException
271
+	 */
272
+	public function spacesRemaining()
273
+	{
274
+		if ($this->spaces_remaining === null) {
275
+			$this->initialize();
276
+			$this->spaces_remaining = $this->calculate();
277
+		}
278
+		return $this->spaces_remaining;
279
+	}
280
+
281
+
282
+	/**
283
+	 * calculates total available spaces for an event with no regard for sold tickets
284
+	 *
285
+	 * @return int|float
286
+	 * @throws EE_Error
287
+	 * @throws DomainException
288
+	 * @throws UnexpectedEntityException
289
+	 * @throws InvalidDataTypeException
290
+	 * @throws InvalidInterfaceException
291
+	 * @throws InvalidArgumentException
292
+	 */
293
+	public function totalSpacesAvailable()
294
+	{
295
+		if ($this->total_spaces_available === null) {
296
+			$this->initialize();
297
+			$this->total_spaces_available = $this->calculate(false);
298
+		}
299
+		return $this->total_spaces_available;
300
+	}
301
+
302
+
303
+	/**
304
+	 * Loops through the active tickets for the event
305
+	 * and builds a series of data arrays that will be used for calculating
306
+	 * the total maximum available spaces, as well as the spaces remaining.
307
+	 * Because ticket quantities affect datetime spaces and vice versa,
308
+	 * we need to be constantly updating these data arrays as things change,
309
+	 * which is the entire reason for their existence.
310
+	 *
311
+	 * @throws EE_Error
312
+	 * @throws DomainException
313
+	 * @throws UnexpectedEntityException
314
+	 * @throws InvalidDataTypeException
315
+	 * @throws InvalidInterfaceException
316
+	 * @throws InvalidArgumentException
317
+	 */
318
+	private function initialize()
319
+	{
320
+		if ($this->debug) {
321
+			\EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
322
+		}
323
+		$this->datetime_tickets = array();
324
+		$this->datetime_spaces = array();
325
+		$this->ticket_datetimes = array();
326
+		$this->ticket_quantities = array();
327
+		$this->tickets_sold = array();
328
+		$this->total_spaces = array();
329
+		$active_tickets = $this->getActiveTickets();
330
+		if (! empty($active_tickets)) {
331
+			foreach ($active_tickets as $ticket) {
332
+				$this->validateTicket($ticket);
333
+				// we need to index our data arrays using strings for the purpose of sorting,
334
+				// but we also need them to be unique, so  we'll just prepend a letter T to the ID
335
+				$ticket_identifier = "T{$ticket->ID()}";
336
+				// to start, we'll just consider the raw qty to be the maximum availability for this ticket,
337
+				// unless the ticket is past its "sell until" date, in which case the qty will be 0
338
+				$max_tickets = $ticket->is_expired() ? 0 : $ticket->qty();
339
+				// but we'll adjust that after looping over each datetime for the ticket and checking reg limits
340
+				$ticket_datetimes = $ticket->datetimes($this->datetime_query_params);
341
+				foreach ($ticket_datetimes as $datetime) {
342
+					// save all datetimes
343
+					$this->setDatetime($datetime);
344
+					$datetime_identifier = "D{$datetime->ID()}";
345
+					$reg_limit = $datetime->reg_limit();
346
+					// ticket quantity can not exceed datetime reg limit
347
+					$max_tickets = min($max_tickets, $reg_limit);
348
+					// as described earlier, because we need to be able to constantly adjust numbers for things,
349
+					// we are going to move all of our data into the following arrays:
350
+					// datetime spaces initially represents the reg limit for each datetime,
351
+					// but this will get adjusted as tickets are accounted for
352
+					$this->datetime_spaces[ $datetime_identifier ] = $reg_limit;
353
+					// just an array of ticket IDs grouped by datetime
354
+					$this->datetime_tickets[ $datetime_identifier ][] = $ticket_identifier;
355
+					// and an array of datetime IDs grouped by ticket
356
+					$this->ticket_datetimes[ $ticket_identifier ][] = $datetime_identifier;
357
+				}
358
+				// total quantity of sold and reserved for each ticket
359
+				$this->tickets_sold[ $ticket_identifier ] = $ticket->sold() + $ticket->reserved();
360
+				// and the maximum ticket quantities for each ticket (adjusted for reg limit)
361
+				$this->ticket_quantities[ $ticket_identifier ] = $max_tickets;
362
+			}
363
+		}
364
+		// sort datetime spaces by reg limit, but maintain our string indexes
365
+		asort($this->datetime_spaces, SORT_NUMERIC);
366
+		// datetime tickets need to be sorted in the SAME order as the above array...
367
+		// so we'll just use array_merge() to take the structure of datetime_spaces
368
+		// but overwrite all of the data with that from datetime_tickets
369
+		$this->datetime_tickets = array_merge(
370
+			$this->datetime_spaces,
371
+			$this->datetime_tickets
372
+		);
373
+		if ($this->debug) {
374
+			\EEH_Debug_Tools::printr($this->datetime_spaces, 'datetime_spaces', __FILE__, __LINE__);
375
+			\EEH_Debug_Tools::printr($this->datetime_tickets, 'datetime_tickets', __FILE__, __LINE__);
376
+			\EEH_Debug_Tools::printr($this->ticket_quantities, 'ticket_quantities', __FILE__, __LINE__);
377
+		}
378
+	}
379
+
380
+
381
+	/**
382
+	 * performs calculations on initialized data
383
+	 *
384
+	 * @param bool $consider_sold
385
+	 * @return int|float
386
+	 */
387
+	private function calculate($consider_sold = true)
388
+	{
389
+		if ($this->debug) {
390
+			\EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
391
+			\EEH_Debug_Tools::printr($consider_sold, '$consider_sold', __FILE__, __LINE__);
392
+		}
393
+		if ($consider_sold) {
394
+			// subtract amounts sold from all ticket quantities and datetime spaces
395
+			$this->adjustTicketQuantitiesDueToSales();
396
+		}
397
+		foreach ($this->datetime_tickets as $datetime_identifier => $tickets) {
398
+			$this->trackAvailableSpacesForDatetimes($datetime_identifier, $tickets);
399
+		}
400
+		// total spaces available is just the sum of the spaces available for each datetime
401
+		$spaces_remaining = array_sum($this->total_spaces);
402
+		if ($this->debug) {
403
+			\EEH_Debug_Tools::printr($this->total_spaces, '$this->total_spaces', __FILE__, __LINE__);
404
+			\EEH_Debug_Tools::printr($this->tickets_sold, '$this->tickets_sold', __FILE__, __LINE__);
405
+			\EEH_Debug_Tools::printr($spaces_remaining, '$spaces_remaining', __FILE__, __LINE__);
406
+		}
407
+		return $spaces_remaining;
408
+	}
409
+
410
+
411
+	/**
412
+	 * subtracts amount of  tickets sold from ticket quantities and datetime spaces
413
+	 */
414
+	private function adjustTicketQuantitiesDueToSales()
415
+	{
416
+		if ($this->debug) {
417
+			\EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
418
+		}
419
+		foreach ($this->tickets_sold as $ticket_identifier => $tickets_sold) {
420
+			if (isset($this->ticket_quantities[ $ticket_identifier ])) {
421
+				$this->ticket_quantities[ $ticket_identifier ] -= $tickets_sold;
422
+				// don't let values go below zero
423
+				$this->ticket_quantities[ $ticket_identifier ] = max(
424
+					$this->ticket_quantities[ $ticket_identifier ],
425
+					0
426
+				);
427
+				if ($this->debug) {
428
+					\EEH_Debug_Tools::printr(
429
+						"{$tickets_sold} sales for ticket {$ticket_identifier} ",
430
+						'subtracting',
431
+						__FILE__,
432
+						__LINE__
433
+					);
434
+				}
435
+			}
436
+			if (isset($this->ticket_datetimes[ $ticket_identifier ])
437
+				&& is_array($this->ticket_datetimes[ $ticket_identifier ])
438
+			) {
439
+				foreach ($this->ticket_datetimes[ $ticket_identifier ] as $ticket_datetime) {
440
+					if (isset($this->ticket_quantities[ $ticket_identifier ])) {
441
+						$this->datetime_spaces[ $ticket_datetime ] -= $tickets_sold;
442
+						// don't let values go below zero
443
+						$this->datetime_spaces[ $ticket_datetime ] = max(
444
+							$this->datetime_spaces[ $ticket_datetime ],
445
+							0
446
+						);
447
+						if ($this->debug) {
448
+							\EEH_Debug_Tools::printr(
449
+								"{$tickets_sold} sales for datetime {$ticket_datetime} ",
450
+								'subtracting',
451
+								__FILE__,
452
+								__LINE__
453
+							);
454
+						}
455
+					}
456
+				}
457
+			}
458
+		}
459
+	}
460
+
461
+
462
+	/**
463
+	 * @param string $datetime_identifier
464
+	 * @param array  $tickets
465
+	 */
466
+	private function trackAvailableSpacesForDatetimes($datetime_identifier, array $tickets)
467
+	{
468
+		// make sure a reg limit is set for the datetime
469
+		$reg_limit = isset($this->datetime_spaces[ $datetime_identifier ])
470
+			? $this->datetime_spaces[ $datetime_identifier ]
471
+			: 0;
472
+		// and bail if it is not
473
+		if (! $reg_limit) {
474
+			if ($this->debug) {
475
+				\EEH_Debug_Tools::printr('AT CAPACITY', " . {$datetime_identifier}", __FILE__, __LINE__);
476
+			}
477
+			return;
478
+		}
479
+		if ($this->debug) {
480
+			\EEH_Debug_Tools::printr($datetime_identifier, '* $datetime_identifier', __FILE__, __LINE__, 1);
481
+			\EEH_Debug_Tools::printr(
482
+				"{$reg_limit}",
483
+				'REG LIMIT',
484
+				__FILE__,
485
+				__LINE__
486
+			);
487
+		}
488
+		// number of allocated spaces always starts at zero
489
+		$spaces_allocated = 0;
490
+		$this->total_spaces[ $datetime_identifier ] = 0;
491
+		foreach ($tickets as $ticket_identifier) {
492
+			$spaces_allocated = $this->calculateAvailableSpacesForTicket(
493
+				$datetime_identifier,
494
+				$reg_limit,
495
+				$ticket_identifier,
496
+				$spaces_allocated
497
+			);
498
+		}
499
+		// spaces can't be negative
500
+		$spaces_allocated = max($spaces_allocated, 0);
501
+		if ($spaces_allocated) {
502
+			// track any non-zero values
503
+			$this->total_spaces[ $datetime_identifier ] += $spaces_allocated;
504
+			if ($this->debug) {
505
+				\EEH_Debug_Tools::printr((string) $spaces_allocated, ' . $spaces_allocated: ', __FILE__, __LINE__);
506
+			}
507
+		} else {
508
+			if ($this->debug) {
509
+				\EEH_Debug_Tools::printr(' ', ' . NO TICKETS AVAILABLE FOR DATETIME', __FILE__, __LINE__);
510
+			}
511
+		}
512
+		if ($this->debug) {
513
+			\EEH_Debug_Tools::printr(
514
+				$this->total_spaces[ $datetime_identifier ],
515
+				'$total_spaces',
516
+				__FILE__,
517
+				__LINE__
518
+			);
519
+			\EEH_Debug_Tools::printr($this->ticket_quantities, '$ticket_quantities', __FILE__, __LINE__);
520
+			\EEH_Debug_Tools::printr($this->datetime_spaces, 'datetime_spaces', __FILE__, __LINE__);
521
+		}
522
+	}
523
+
524
+
525
+	/**
526
+	 * @param string $datetime_identifier
527
+	 * @param int    $reg_limit
528
+	 * @param string $ticket_identifier
529
+	 * @param int    $spaces_allocated
530
+	 * @return int
531
+	 */
532
+	private function calculateAvailableSpacesForTicket(
533
+		$datetime_identifier,
534
+		$reg_limit,
535
+		$ticket_identifier,
536
+		$spaces_allocated
537
+	) {
538
+		// make sure ticket quantity is set
539
+		$ticket_quantity = isset($this->ticket_quantities[ $ticket_identifier ])
540
+			? $this->ticket_quantities[ $ticket_identifier ]
541
+			: 0;
542
+		if ($this->debug) {
543
+			\EEH_Debug_Tools::printr("{$spaces_allocated}", '$spaces_allocated', __FILE__, __LINE__);
544
+			\EEH_Debug_Tools::printr(
545
+				"{$ticket_quantity}",
546
+				"ticket $ticket_identifier quantity: ",
547
+				__FILE__,
548
+				__LINE__,
549
+				2
550
+			);
551
+		}
552
+		if ($ticket_quantity) {
553
+			if ($this->debug) {
554
+				\EEH_Debug_Tools::printr(
555
+					($spaces_allocated <= $reg_limit)
556
+						? 'true'
557
+						: 'false',
558
+					' . spaces_allocated <= reg_limit = ',
559
+					__FILE__,
560
+					__LINE__
561
+				);
562
+			}
563
+			// if the datetime is NOT at full capacity yet
564
+			if ($spaces_allocated <= $reg_limit) {
565
+				// then the maximum ticket quantity we can allocate is the lowest value of either:
566
+				//  the number of remaining spaces for the datetime, which is the limit - spaces already taken
567
+				//  or the maximum ticket quantity
568
+				$ticket_quantity = min($reg_limit - $spaces_allocated, $ticket_quantity);
569
+				// adjust the available quantity in our tracking array
570
+				$this->ticket_quantities[ $ticket_identifier ] -= $ticket_quantity;
571
+				// and increment spaces allocated for this datetime
572
+				$spaces_allocated += $ticket_quantity;
573
+				$at_capacity = $spaces_allocated >= $reg_limit;
574
+				if ($this->debug) {
575
+					\EEH_Debug_Tools::printr(
576
+						"{$ticket_quantity} {$ticket_identifier} tickets",
577
+						' > > allocate ',
578
+						__FILE__,
579
+						__LINE__,
580
+						3
581
+					);
582
+					if ($at_capacity) {
583
+						\EEH_Debug_Tools::printr('AT CAPACITY', " . {$datetime_identifier}", __FILE__, __LINE__, 3);
584
+					}
585
+				}
586
+				// now adjust all other datetimes that allow access to this ticket
587
+				$this->adjustDatetimes(
588
+					$datetime_identifier,
589
+					$ticket_identifier,
590
+					$ticket_quantity,
591
+					$at_capacity
592
+				);
593
+			}
594
+		}
595
+		return $spaces_allocated;
596
+	}
597
+
598
+
599
+	/**
600
+	 * subtracts ticket amounts from all datetime reg limits
601
+	 * that allow access to the ticket specified,
602
+	 * because that ticket could be used
603
+	 * to attend any of the datetimes it has access to
604
+	 *
605
+	 * @param string $datetime_identifier
606
+	 * @param string $ticket_identifier
607
+	 * @param bool   $at_capacity
608
+	 * @param int    $ticket_quantity
609
+	 */
610
+	private function adjustDatetimes(
611
+		$datetime_identifier,
612
+		$ticket_identifier,
613
+		$ticket_quantity,
614
+		$at_capacity
615
+	) {
616
+		/** @var array $datetime_tickets */
617
+		foreach ($this->datetime_tickets as $datetime_ID => $datetime_tickets) {
618
+			if ($datetime_ID !== $datetime_identifier || ! is_array($datetime_tickets)) {
619
+				continue;
620
+			}
621
+			$adjusted = $this->adjustDatetimeSpaces(
622
+				$datetime_ID,
623
+				$ticket_identifier,
624
+				$ticket_quantity
625
+			);
626
+			// skip to next ticket if nothing changed
627
+			if (! ($adjusted || $at_capacity)) {
628
+				continue;
629
+			}
630
+			// then all of it's tickets are now unavailable
631
+			foreach ($datetime_tickets as $datetime_ticket) {
632
+				if (($ticket_identifier === $datetime_ticket || $at_capacity)
633
+					&& isset($this->ticket_quantities[ $datetime_ticket ])
634
+					&& $this->ticket_quantities[ $datetime_ticket ] > 0
635
+				) {
636
+					if ($this->debug) {
637
+						\EEH_Debug_Tools::printr(
638
+							$datetime_ticket,
639
+							' . . . adjust ticket quantities for',
640
+							__FILE__,
641
+							__LINE__
642
+						);
643
+					}
644
+					// if this datetime is at full capacity, set any tracked available quantities to zero
645
+					// otherwise just subtract the ticket quantity
646
+					$new_quantity = $at_capacity
647
+						? 0
648
+						: $this->ticket_quantities[ $datetime_ticket ] - $ticket_quantity;
649
+					// don't let ticket quantity go below zero
650
+					$this->ticket_quantities[ $datetime_ticket ] = max($new_quantity, 0);
651
+					if ($this->debug) {
652
+						\EEH_Debug_Tools::printr(
653
+							$at_capacity
654
+								? "0 because Datetime {$datetime_identifier} is at capacity"
655
+								: "{$this->ticket_quantities[ $datetime_ticket ]}",
656
+							" . . . . {$datetime_ticket} quantity set to ",
657
+							__FILE__,
658
+							__LINE__
659
+						);
660
+					}
661
+				}
662
+				// but we also need to adjust spaces for any other datetimes this ticket has access to
663
+				if ($datetime_ticket === $ticket_identifier) {
664
+					if (isset($this->ticket_datetimes[ $datetime_ticket ])
665
+						&& is_array($this->ticket_datetimes[ $datetime_ticket ])
666
+					) {
667
+						if ($this->debug) {
668
+							\EEH_Debug_Tools::printr(
669
+								$datetime_ticket,
670
+								' . . adjust other Datetimes for',
671
+								__FILE__,
672
+								__LINE__
673
+							);
674
+						}
675
+						foreach ($this->ticket_datetimes[ $datetime_ticket ] as $datetime) {
676
+							// don't adjust the current datetime twice
677
+							if ($datetime !== $datetime_identifier) {
678
+								$this->adjustDatetimeSpaces(
679
+									$datetime,
680
+									$datetime_ticket,
681
+									$ticket_quantity
682
+								);
683
+							}
684
+						}
685
+					}
686
+				}
687
+			}
688
+		}
689
+	}
690
+
691
+	private function adjustDatetimeSpaces($datetime_identifier, $ticket_identifier, $ticket_quantity = 0)
692
+	{
693
+		// does datetime have spaces available?
694
+		// and does the supplied ticket have access to this datetime ?
695
+		if ($this->datetime_spaces[ $datetime_identifier ] > 0
696
+			&& isset($this->datetime_spaces[ $datetime_identifier ], $this->datetime_tickets[ $datetime_identifier ])
697
+			&& in_array($ticket_identifier, $this->datetime_tickets[ $datetime_identifier ], true)
698
+		) {
699
+			if ($this->debug) {
700
+				\EEH_Debug_Tools::printr($datetime_identifier, ' . . adjust Datetime Spaces for', __FILE__, __LINE__);
701
+				\EEH_Debug_Tools::printr(
702
+					"{$this->datetime_spaces[ $datetime_identifier ]}",
703
+					" . . current  {$datetime_identifier} spaces available",
704
+					__FILE__,
705
+					__LINE__
706
+				);
707
+			}
708
+			// then decrement the available spaces for the datetime
709
+			$this->datetime_spaces[ $datetime_identifier ] -= $ticket_quantity;
710
+			// but don't let quantities go below zero
711
+			$this->datetime_spaces[ $datetime_identifier ] = max(
712
+				$this->datetime_spaces[ $datetime_identifier ],
713
+				0
714
+			);
715
+			if ($this->debug) {
716
+				\EEH_Debug_Tools::printr(
717
+					"{$ticket_quantity}",
718
+					" . . . {$datetime_identifier} capacity reduced by",
719
+					__FILE__,
720
+					__LINE__
721
+				);
722
+			}
723
+			return true;
724
+		}
725
+		return false;
726
+	}
727 727
 }
Please login to merge, or discard this patch.
Spacing   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -174,14 +174,14 @@  discard block
 block discarded – undo
174 174
      */
175 175
     public function setActiveTickets(array $active_tickets = array())
176 176
     {
177
-        if (! empty($active_tickets)) {
177
+        if ( ! empty($active_tickets)) {
178 178
             foreach ($active_tickets as $active_ticket) {
179 179
                 $this->validateTicket($active_ticket);
180 180
             }
181 181
             // sort incoming array by ticket quantity (asc)
182 182
             usort(
183 183
                 $active_tickets,
184
-                function (EE_Ticket $a, EE_Ticket $b) {
184
+                function(EE_Ticket $a, EE_Ticket $b) {
185 185
                     if ($a->qty() === $b->qty()) {
186 186
                         return 0;
187 187
                     }
@@ -203,7 +203,7 @@  discard block
 block discarded – undo
203 203
      */
204 204
     private function validateTicket($ticket)
205 205
     {
206
-        if (! $ticket instanceof EE_Ticket) {
206
+        if ( ! $ticket instanceof EE_Ticket) {
207 207
             throw new DomainException(
208 208
                 esc_html__(
209 209
                     'Invalid Ticket. Only EE_Ticket objects can be used to calculate event space availability.',
@@ -254,7 +254,7 @@  discard block
 block discarded – undo
254 254
                 )
255 255
             );
256 256
         }
257
-        $this->datetimes[ $datetime->ID() ] = $datetime;
257
+        $this->datetimes[$datetime->ID()] = $datetime;
258 258
     }
259 259
 
260 260
 
@@ -327,7 +327,7 @@  discard block
 block discarded – undo
327 327
         $this->tickets_sold = array();
328 328
         $this->total_spaces = array();
329 329
         $active_tickets = $this->getActiveTickets();
330
-        if (! empty($active_tickets)) {
330
+        if ( ! empty($active_tickets)) {
331 331
             foreach ($active_tickets as $ticket) {
332 332
                 $this->validateTicket($ticket);
333 333
                 // we need to index our data arrays using strings for the purpose of sorting,
@@ -349,16 +349,16 @@  discard block
 block discarded – undo
349 349
                     // we are going to move all of our data into the following arrays:
350 350
                     // datetime spaces initially represents the reg limit for each datetime,
351 351
                     // but this will get adjusted as tickets are accounted for
352
-                    $this->datetime_spaces[ $datetime_identifier ] = $reg_limit;
352
+                    $this->datetime_spaces[$datetime_identifier] = $reg_limit;
353 353
                     // just an array of ticket IDs grouped by datetime
354
-                    $this->datetime_tickets[ $datetime_identifier ][] = $ticket_identifier;
354
+                    $this->datetime_tickets[$datetime_identifier][] = $ticket_identifier;
355 355
                     // and an array of datetime IDs grouped by ticket
356
-                    $this->ticket_datetimes[ $ticket_identifier ][] = $datetime_identifier;
356
+                    $this->ticket_datetimes[$ticket_identifier][] = $datetime_identifier;
357 357
                 }
358 358
                 // total quantity of sold and reserved for each ticket
359
-                $this->tickets_sold[ $ticket_identifier ] = $ticket->sold() + $ticket->reserved();
359
+                $this->tickets_sold[$ticket_identifier] = $ticket->sold() + $ticket->reserved();
360 360
                 // and the maximum ticket quantities for each ticket (adjusted for reg limit)
361
-                $this->ticket_quantities[ $ticket_identifier ] = $max_tickets;
361
+                $this->ticket_quantities[$ticket_identifier] = $max_tickets;
362 362
             }
363 363
         }
364 364
         // sort datetime spaces by reg limit, but maintain our string indexes
@@ -417,11 +417,11 @@  discard block
 block discarded – undo
417 417
             \EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
418 418
         }
419 419
         foreach ($this->tickets_sold as $ticket_identifier => $tickets_sold) {
420
-            if (isset($this->ticket_quantities[ $ticket_identifier ])) {
421
-                $this->ticket_quantities[ $ticket_identifier ] -= $tickets_sold;
420
+            if (isset($this->ticket_quantities[$ticket_identifier])) {
421
+                $this->ticket_quantities[$ticket_identifier] -= $tickets_sold;
422 422
                 // don't let values go below zero
423
-                $this->ticket_quantities[ $ticket_identifier ] = max(
424
-                    $this->ticket_quantities[ $ticket_identifier ],
423
+                $this->ticket_quantities[$ticket_identifier] = max(
424
+                    $this->ticket_quantities[$ticket_identifier],
425 425
                     0
426 426
                 );
427 427
                 if ($this->debug) {
@@ -433,15 +433,15 @@  discard block
 block discarded – undo
433 433
                     );
434 434
                 }
435 435
             }
436
-            if (isset($this->ticket_datetimes[ $ticket_identifier ])
437
-                && is_array($this->ticket_datetimes[ $ticket_identifier ])
436
+            if (isset($this->ticket_datetimes[$ticket_identifier])
437
+                && is_array($this->ticket_datetimes[$ticket_identifier])
438 438
             ) {
439
-                foreach ($this->ticket_datetimes[ $ticket_identifier ] as $ticket_datetime) {
440
-                    if (isset($this->ticket_quantities[ $ticket_identifier ])) {
441
-                        $this->datetime_spaces[ $ticket_datetime ] -= $tickets_sold;
439
+                foreach ($this->ticket_datetimes[$ticket_identifier] as $ticket_datetime) {
440
+                    if (isset($this->ticket_quantities[$ticket_identifier])) {
441
+                        $this->datetime_spaces[$ticket_datetime] -= $tickets_sold;
442 442
                         // don't let values go below zero
443
-                        $this->datetime_spaces[ $ticket_datetime ] = max(
444
-                            $this->datetime_spaces[ $ticket_datetime ],
443
+                        $this->datetime_spaces[$ticket_datetime] = max(
444
+                            $this->datetime_spaces[$ticket_datetime],
445 445
                             0
446 446
                         );
447 447
                         if ($this->debug) {
@@ -466,11 +466,11 @@  discard block
 block discarded – undo
466 466
     private function trackAvailableSpacesForDatetimes($datetime_identifier, array $tickets)
467 467
     {
468 468
         // make sure a reg limit is set for the datetime
469
-        $reg_limit = isset($this->datetime_spaces[ $datetime_identifier ])
470
-            ? $this->datetime_spaces[ $datetime_identifier ]
469
+        $reg_limit = isset($this->datetime_spaces[$datetime_identifier])
470
+            ? $this->datetime_spaces[$datetime_identifier]
471 471
             : 0;
472 472
         // and bail if it is not
473
-        if (! $reg_limit) {
473
+        if ( ! $reg_limit) {
474 474
             if ($this->debug) {
475 475
                 \EEH_Debug_Tools::printr('AT CAPACITY', " . {$datetime_identifier}", __FILE__, __LINE__);
476 476
             }
@@ -487,7 +487,7 @@  discard block
 block discarded – undo
487 487
         }
488 488
         // number of allocated spaces always starts at zero
489 489
         $spaces_allocated = 0;
490
-        $this->total_spaces[ $datetime_identifier ] = 0;
490
+        $this->total_spaces[$datetime_identifier] = 0;
491 491
         foreach ($tickets as $ticket_identifier) {
492 492
             $spaces_allocated = $this->calculateAvailableSpacesForTicket(
493 493
                 $datetime_identifier,
@@ -500,7 +500,7 @@  discard block
 block discarded – undo
500 500
         $spaces_allocated = max($spaces_allocated, 0);
501 501
         if ($spaces_allocated) {
502 502
             // track any non-zero values
503
-            $this->total_spaces[ $datetime_identifier ] += $spaces_allocated;
503
+            $this->total_spaces[$datetime_identifier] += $spaces_allocated;
504 504
             if ($this->debug) {
505 505
                 \EEH_Debug_Tools::printr((string) $spaces_allocated, ' . $spaces_allocated: ', __FILE__, __LINE__);
506 506
             }
@@ -511,7 +511,7 @@  discard block
 block discarded – undo
511 511
         }
512 512
         if ($this->debug) {
513 513
             \EEH_Debug_Tools::printr(
514
-                $this->total_spaces[ $datetime_identifier ],
514
+                $this->total_spaces[$datetime_identifier],
515 515
                 '$total_spaces',
516 516
                 __FILE__,
517 517
                 __LINE__
@@ -536,8 +536,8 @@  discard block
 block discarded – undo
536 536
         $spaces_allocated
537 537
     ) {
538 538
         // make sure ticket quantity is set
539
-        $ticket_quantity = isset($this->ticket_quantities[ $ticket_identifier ])
540
-            ? $this->ticket_quantities[ $ticket_identifier ]
539
+        $ticket_quantity = isset($this->ticket_quantities[$ticket_identifier])
540
+            ? $this->ticket_quantities[$ticket_identifier]
541 541
             : 0;
542 542
         if ($this->debug) {
543 543
             \EEH_Debug_Tools::printr("{$spaces_allocated}", '$spaces_allocated', __FILE__, __LINE__);
@@ -567,7 +567,7 @@  discard block
 block discarded – undo
567 567
                 //  or the maximum ticket quantity
568 568
                 $ticket_quantity = min($reg_limit - $spaces_allocated, $ticket_quantity);
569 569
                 // adjust the available quantity in our tracking array
570
-                $this->ticket_quantities[ $ticket_identifier ] -= $ticket_quantity;
570
+                $this->ticket_quantities[$ticket_identifier] -= $ticket_quantity;
571 571
                 // and increment spaces allocated for this datetime
572 572
                 $spaces_allocated += $ticket_quantity;
573 573
                 $at_capacity = $spaces_allocated >= $reg_limit;
@@ -624,14 +624,14 @@  discard block
 block discarded – undo
624 624
                 $ticket_quantity
625 625
             );
626 626
             // skip to next ticket if nothing changed
627
-            if (! ($adjusted || $at_capacity)) {
627
+            if ( ! ($adjusted || $at_capacity)) {
628 628
                 continue;
629 629
             }
630 630
             // then all of it's tickets are now unavailable
631 631
             foreach ($datetime_tickets as $datetime_ticket) {
632 632
                 if (($ticket_identifier === $datetime_ticket || $at_capacity)
633
-                    && isset($this->ticket_quantities[ $datetime_ticket ])
634
-                    && $this->ticket_quantities[ $datetime_ticket ] > 0
633
+                    && isset($this->ticket_quantities[$datetime_ticket])
634
+                    && $this->ticket_quantities[$datetime_ticket] > 0
635 635
                 ) {
636 636
                     if ($this->debug) {
637 637
                         \EEH_Debug_Tools::printr(
@@ -645,14 +645,14 @@  discard block
 block discarded – undo
645 645
                     // otherwise just subtract the ticket quantity
646 646
                     $new_quantity = $at_capacity
647 647
                         ? 0
648
-                        : $this->ticket_quantities[ $datetime_ticket ] - $ticket_quantity;
648
+                        : $this->ticket_quantities[$datetime_ticket] - $ticket_quantity;
649 649
                     // don't let ticket quantity go below zero
650
-                    $this->ticket_quantities[ $datetime_ticket ] = max($new_quantity, 0);
650
+                    $this->ticket_quantities[$datetime_ticket] = max($new_quantity, 0);
651 651
                     if ($this->debug) {
652 652
                         \EEH_Debug_Tools::printr(
653 653
                             $at_capacity
654 654
                                 ? "0 because Datetime {$datetime_identifier} is at capacity"
655
-                                : "{$this->ticket_quantities[ $datetime_ticket ]}",
655
+                                : "{$this->ticket_quantities[$datetime_ticket]}",
656 656
                             " . . . . {$datetime_ticket} quantity set to ",
657 657
                             __FILE__,
658 658
                             __LINE__
@@ -661,8 +661,8 @@  discard block
 block discarded – undo
661 661
                 }
662 662
                 // but we also need to adjust spaces for any other datetimes this ticket has access to
663 663
                 if ($datetime_ticket === $ticket_identifier) {
664
-                    if (isset($this->ticket_datetimes[ $datetime_ticket ])
665
-                        && is_array($this->ticket_datetimes[ $datetime_ticket ])
664
+                    if (isset($this->ticket_datetimes[$datetime_ticket])
665
+                        && is_array($this->ticket_datetimes[$datetime_ticket])
666 666
                     ) {
667 667
                         if ($this->debug) {
668 668
                             \EEH_Debug_Tools::printr(
@@ -672,7 +672,7 @@  discard block
 block discarded – undo
672 672
                                 __LINE__
673 673
                             );
674 674
                         }
675
-                        foreach ($this->ticket_datetimes[ $datetime_ticket ] as $datetime) {
675
+                        foreach ($this->ticket_datetimes[$datetime_ticket] as $datetime) {
676 676
                             // don't adjust the current datetime twice
677 677
                             if ($datetime !== $datetime_identifier) {
678 678
                                 $this->adjustDatetimeSpaces(
@@ -692,24 +692,24 @@  discard block
 block discarded – undo
692 692
     {
693 693
         // does datetime have spaces available?
694 694
         // and does the supplied ticket have access to this datetime ?
695
-        if ($this->datetime_spaces[ $datetime_identifier ] > 0
696
-            && isset($this->datetime_spaces[ $datetime_identifier ], $this->datetime_tickets[ $datetime_identifier ])
697
-            && in_array($ticket_identifier, $this->datetime_tickets[ $datetime_identifier ], true)
695
+        if ($this->datetime_spaces[$datetime_identifier] > 0
696
+            && isset($this->datetime_spaces[$datetime_identifier], $this->datetime_tickets[$datetime_identifier])
697
+            && in_array($ticket_identifier, $this->datetime_tickets[$datetime_identifier], true)
698 698
         ) {
699 699
             if ($this->debug) {
700 700
                 \EEH_Debug_Tools::printr($datetime_identifier, ' . . adjust Datetime Spaces for', __FILE__, __LINE__);
701 701
                 \EEH_Debug_Tools::printr(
702
-                    "{$this->datetime_spaces[ $datetime_identifier ]}",
702
+                    "{$this->datetime_spaces[$datetime_identifier]}",
703 703
                     " . . current  {$datetime_identifier} spaces available",
704 704
                     __FILE__,
705 705
                     __LINE__
706 706
                 );
707 707
             }
708 708
             // then decrement the available spaces for the datetime
709
-            $this->datetime_spaces[ $datetime_identifier ] -= $ticket_quantity;
709
+            $this->datetime_spaces[$datetime_identifier] -= $ticket_quantity;
710 710
             // but don't let quantities go below zero
711
-            $this->datetime_spaces[ $datetime_identifier ] = max(
712
-                $this->datetime_spaces[ $datetime_identifier ],
711
+            $this->datetime_spaces[$datetime_identifier] = max(
712
+                $this->datetime_spaces[$datetime_identifier],
713 713
                 0
714 714
             );
715 715
             if ($this->debug) {
Please login to merge, or discard this patch.
core/domain/services/pue/StatsGatherer.php 2 patches
Indentation   +269 added lines, -269 removed lines patch added patch discarded remove patch
@@ -15,293 +15,293 @@
 block discarded – undo
15 15
 class StatsGatherer
16 16
 {
17 17
 
18
-    const COUNT_ALL_EVENTS = 'event';
19
-    const COUNT_ACTIVE_EVENTS = 'active_event';
20
-    const COUNT_DATETIMES = 'datetime';
21
-    const COUNT_TICKETS = 'ticket';
22
-    const COUNT_DATETIMES_SOLD = 'datetime_sold';
23
-    const COUNT_TICKETS_FREE = 'free_ticket';
24
-    const COUNT_TICKETS_PAID = 'paid_ticket';
25
-    const COUNT_TICKETS_SOLD = 'ticket_sold';
26
-    const COUNT_REGISTRATIONS_APPROVED = 'registrations_approved';
27
-    const COUNT_REGISTRATIONS_NOT_APPROVED = 'registrations_not_approved';
28
-    const COUNT_REGISTRATIONS_PENDING = 'registrations_pending';
29
-    const COUNT_REGISTRATIONS_INCOMPLETE = 'registrations_incomplete';
30
-    const COUNT_REGISTRATIONS_ALL = 'registrations_all';
31
-    const COUNT_REGISTRATIONS_CANCELLED = 'registrations_cancelled';
32
-    const COUNT_REGISTRATIONS_DECLINED = 'registrations_declined';
33
-    const SUM_TRANSACTIONS_COMPLETE_TOTAL = 'transactions_complete_total_sum';
34
-    const SUM_TRANSACTIONS_ALL_PAID = 'transactions_all_paid';
35
-    const INFO_SITE_CURRENCY = 'site_currency';
18
+	const COUNT_ALL_EVENTS = 'event';
19
+	const COUNT_ACTIVE_EVENTS = 'active_event';
20
+	const COUNT_DATETIMES = 'datetime';
21
+	const COUNT_TICKETS = 'ticket';
22
+	const COUNT_DATETIMES_SOLD = 'datetime_sold';
23
+	const COUNT_TICKETS_FREE = 'free_ticket';
24
+	const COUNT_TICKETS_PAID = 'paid_ticket';
25
+	const COUNT_TICKETS_SOLD = 'ticket_sold';
26
+	const COUNT_REGISTRATIONS_APPROVED = 'registrations_approved';
27
+	const COUNT_REGISTRATIONS_NOT_APPROVED = 'registrations_not_approved';
28
+	const COUNT_REGISTRATIONS_PENDING = 'registrations_pending';
29
+	const COUNT_REGISTRATIONS_INCOMPLETE = 'registrations_incomplete';
30
+	const COUNT_REGISTRATIONS_ALL = 'registrations_all';
31
+	const COUNT_REGISTRATIONS_CANCELLED = 'registrations_cancelled';
32
+	const COUNT_REGISTRATIONS_DECLINED = 'registrations_declined';
33
+	const SUM_TRANSACTIONS_COMPLETE_TOTAL = 'transactions_complete_total_sum';
34
+	const SUM_TRANSACTIONS_ALL_PAID = 'transactions_all_paid';
35
+	const INFO_SITE_CURRENCY = 'site_currency';
36 36
 
37 37
 
38
-    /**
39
-     * @var EEM_Payment_Method
40
-     */
41
-    private $payment_method_model;
38
+	/**
39
+	 * @var EEM_Payment_Method
40
+	 */
41
+	private $payment_method_model;
42 42
 
43 43
 
44
-    /**
45
-     * @var EEM_Event
46
-     */
47
-    private $event_model;
44
+	/**
45
+	 * @var EEM_Event
46
+	 */
47
+	private $event_model;
48 48
 
49
-    /**
50
-     * @var EEM_Datetime
51
-     */
52
-    private $datetime_model;
49
+	/**
50
+	 * @var EEM_Datetime
51
+	 */
52
+	private $datetime_model;
53 53
 
54 54
 
55
-    /**
56
-     * @var EEM_Ticket
57
-     */
58
-    private $ticket_model;
55
+	/**
56
+	 * @var EEM_Ticket
57
+	 */
58
+	private $ticket_model;
59 59
 
60 60
 
61
-    /**
62
-     * @var EEM_Registration
63
-     */
64
-    private $registration_model;
61
+	/**
62
+	 * @var EEM_Registration
63
+	 */
64
+	private $registration_model;
65 65
 
66 66
 
67
-    /**
68
-     * @var EEM_Transaction
69
-     */
70
-    private $transaction_model;
67
+	/**
68
+	 * @var EEM_Transaction
69
+	 */
70
+	private $transaction_model;
71 71
 
72 72
 
73
-    /**
74
-     * @var EE_Config
75
-     */
76
-    private $config;
73
+	/**
74
+	 * @var EE_Config
75
+	 */
76
+	private $config;
77 77
 
78 78
 
79
-    /**
80
-     * StatsGatherer constructor.
81
-     *
82
-     * @param EEM_Payment_Method $payment_method_model
83
-     * @param EEM_Event          $event_model
84
-     * @param EEM_Datetime       $datetime_model
85
-     * @param EEM_Ticket         $ticket_model
86
-     * @param EEM_Registration   $registration_model
87
-     * @param EEM_Transaction    $transaction_model
88
-     * @param EE_Config          $config
89
-     */
90
-    public function __construct(
91
-        EEM_Payment_Method $payment_method_model,
92
-        EEM_Event $event_model,
93
-        EEM_Datetime $datetime_model,
94
-        EEM_Ticket $ticket_model,
95
-        EEM_Registration $registration_model,
96
-        EEM_Transaction $transaction_model,
97
-        EE_Config $config
98
-    ) {
99
-        $this->payment_method_model = $payment_method_model;
100
-        $this->event_model = $event_model;
101
-        $this->datetime_model = $datetime_model;
102
-        $this->ticket_model = $ticket_model;
103
-        $this->registration_model = $registration_model;
104
-        $this->transaction_model = $transaction_model;
105
-        $this->config = $config;
106
-    }
79
+	/**
80
+	 * StatsGatherer constructor.
81
+	 *
82
+	 * @param EEM_Payment_Method $payment_method_model
83
+	 * @param EEM_Event          $event_model
84
+	 * @param EEM_Datetime       $datetime_model
85
+	 * @param EEM_Ticket         $ticket_model
86
+	 * @param EEM_Registration   $registration_model
87
+	 * @param EEM_Transaction    $transaction_model
88
+	 * @param EE_Config          $config
89
+	 */
90
+	public function __construct(
91
+		EEM_Payment_Method $payment_method_model,
92
+		EEM_Event $event_model,
93
+		EEM_Datetime $datetime_model,
94
+		EEM_Ticket $ticket_model,
95
+		EEM_Registration $registration_model,
96
+		EEM_Transaction $transaction_model,
97
+		EE_Config $config
98
+	) {
99
+		$this->payment_method_model = $payment_method_model;
100
+		$this->event_model = $event_model;
101
+		$this->datetime_model = $datetime_model;
102
+		$this->ticket_model = $ticket_model;
103
+		$this->registration_model = $registration_model;
104
+		$this->transaction_model = $transaction_model;
105
+		$this->config = $config;
106
+	}
107 107
 
108 108
 
109
-    /**
110
-     * Return the stats array for PUE UXIP stats.
111
-     *
112
-     * @return array
113
-     */
114
-    public function stats()
115
-    {
116
-        $stats = $this->paymentMethodStats();
117
-        // a-ok so let's setup our stats.
118
-        $stats = array_merge($stats, array(
119
-            'is_multisite'                    => is_multisite() && is_main_site(),
120
-            'active_theme'                    => $this->getActiveThemeStat(),
121
-            'ee4_all_events_count'            => $this->getCountFor(self::COUNT_ALL_EVENTS),
122
-            'ee4_active_events_count'         => $this->getCountFor(self::COUNT_ACTIVE_EVENTS),
123
-            'all_dtts_count'                  => $this->getCountFor(self::COUNT_DATETIMES),
124
-            'dtt_sold'                        => $this->getCountFor(self::COUNT_DATETIMES_SOLD),
125
-            'all_tkt_count'                   => $this->getCountFor(self::COUNT_TICKETS),
126
-            'free_tkt_count'                  => $this->getCountFor(self::COUNT_TICKETS_FREE),
127
-            'paid_tkt_count'                  => $this->getCountFor(self::COUNT_TICKETS_PAID),
128
-            'tkt_sold'                        => $this->getCountFor(self::COUNT_TICKETS_SOLD),
129
-            'approve_registration_count'      => $this->getCountFor(self::COUNT_REGISTRATIONS_APPROVED),
130
-            'pending_registration_count'      => $this->getCountFor(self::COUNT_REGISTRATIONS_PENDING),
131
-            'not_approved_registration_count' => $this->getCountFor(self::COUNT_REGISTRATIONS_NOT_APPROVED),
132
-            'incomplete_registration_count'   => $this->getCountFor(self::COUNT_REGISTRATIONS_INCOMPLETE),
133
-            'cancelled_registration_count'    => $this->getCountFor(self::COUNT_REGISTRATIONS_CANCELLED),
134
-            'declined_registration_count'     => $this->getCountFor(self::COUNT_REGISTRATIONS_DECLINED),
135
-            'all_registration_count'          => $this->getCountFor(self::COUNT_REGISTRATIONS_ALL),
136
-            'completed_transaction_total_sum' => $this->getCountFor(self::SUM_TRANSACTIONS_COMPLETE_TOTAL),
137
-            'all_transaction_paid_sum'        => $this->getCountFor(self::SUM_TRANSACTIONS_ALL_PAID),
138
-            self::INFO_SITE_CURRENCY          => $this->config->currency instanceof EE_Currency_Config
139
-                ? $this->config->currency->code
140
-                : 'unknown',
141
-            'phpversion'                      => implode(
142
-                '.',
143
-                array(PHP_MAJOR_VERSION, PHP_MINOR_VERSION, PHP_RELEASE_VERSION)
144
-            ),
145
-        ));
146
-        // remove any values that equal null.  This ensures any stats that weren't retrieved successfully are excluded.
147
-        return array_filter($stats, function ($value) {
148
-            return $value !== null;
149
-        });
150
-    }
109
+	/**
110
+	 * Return the stats array for PUE UXIP stats.
111
+	 *
112
+	 * @return array
113
+	 */
114
+	public function stats()
115
+	{
116
+		$stats = $this->paymentMethodStats();
117
+		// a-ok so let's setup our stats.
118
+		$stats = array_merge($stats, array(
119
+			'is_multisite'                    => is_multisite() && is_main_site(),
120
+			'active_theme'                    => $this->getActiveThemeStat(),
121
+			'ee4_all_events_count'            => $this->getCountFor(self::COUNT_ALL_EVENTS),
122
+			'ee4_active_events_count'         => $this->getCountFor(self::COUNT_ACTIVE_EVENTS),
123
+			'all_dtts_count'                  => $this->getCountFor(self::COUNT_DATETIMES),
124
+			'dtt_sold'                        => $this->getCountFor(self::COUNT_DATETIMES_SOLD),
125
+			'all_tkt_count'                   => $this->getCountFor(self::COUNT_TICKETS),
126
+			'free_tkt_count'                  => $this->getCountFor(self::COUNT_TICKETS_FREE),
127
+			'paid_tkt_count'                  => $this->getCountFor(self::COUNT_TICKETS_PAID),
128
+			'tkt_sold'                        => $this->getCountFor(self::COUNT_TICKETS_SOLD),
129
+			'approve_registration_count'      => $this->getCountFor(self::COUNT_REGISTRATIONS_APPROVED),
130
+			'pending_registration_count'      => $this->getCountFor(self::COUNT_REGISTRATIONS_PENDING),
131
+			'not_approved_registration_count' => $this->getCountFor(self::COUNT_REGISTRATIONS_NOT_APPROVED),
132
+			'incomplete_registration_count'   => $this->getCountFor(self::COUNT_REGISTRATIONS_INCOMPLETE),
133
+			'cancelled_registration_count'    => $this->getCountFor(self::COUNT_REGISTRATIONS_CANCELLED),
134
+			'declined_registration_count'     => $this->getCountFor(self::COUNT_REGISTRATIONS_DECLINED),
135
+			'all_registration_count'          => $this->getCountFor(self::COUNT_REGISTRATIONS_ALL),
136
+			'completed_transaction_total_sum' => $this->getCountFor(self::SUM_TRANSACTIONS_COMPLETE_TOTAL),
137
+			'all_transaction_paid_sum'        => $this->getCountFor(self::SUM_TRANSACTIONS_ALL_PAID),
138
+			self::INFO_SITE_CURRENCY          => $this->config->currency instanceof EE_Currency_Config
139
+				? $this->config->currency->code
140
+				: 'unknown',
141
+			'phpversion'                      => implode(
142
+				'.',
143
+				array(PHP_MAJOR_VERSION, PHP_MINOR_VERSION, PHP_RELEASE_VERSION)
144
+			),
145
+		));
146
+		// remove any values that equal null.  This ensures any stats that weren't retrieved successfully are excluded.
147
+		return array_filter($stats, function ($value) {
148
+			return $value !== null;
149
+		});
150
+	}
151 151
 
152
-    /**
153
-     * @param string $which enum (@see constants prefixed with COUNT)
154
-     * @return int|null
155
-     */
156
-    private function getCountFor($which)
157
-    {
158
-        try {
159
-            switch ($which) {
160
-                case self::COUNT_ALL_EVENTS:
161
-                    $count = $this->event_model->count();
162
-                    break;
163
-                case self::COUNT_TICKETS:
164
-                    $count = $this->ticket_model->count();
165
-                    break;
166
-                case self::COUNT_DATETIMES:
167
-                    $count = $this->datetime_model->count();
168
-                    break;
169
-                case self::COUNT_ACTIVE_EVENTS:
170
-                    $count = $this->event_model->get_active_events(array(), true);
171
-                    break;
172
-                case self::COUNT_DATETIMES_SOLD:
173
-                    $count = $this->datetime_model->sum(array(), 'DTT_sold');
174
-                    break;
175
-                case self::COUNT_TICKETS_FREE:
176
-                    $count = $this->ticket_model->count(array(
177
-                        array(
178
-                            'TKT_price' => 0,
179
-                        ),
180
-                    ));
181
-                    break;
182
-                case self::COUNT_TICKETS_PAID:
183
-                    $count = $this->ticket_model->count(array(
184
-                        array(
185
-                            'TKT_price' => array('>', 0),
186
-                        ),
187
-                    ));
188
-                    break;
189
-                case self::COUNT_TICKETS_SOLD:
190
-                    $count = $this->ticket_model->sum(array(), 'TKT_sold');
191
-                    break;
192
-                case self::COUNT_REGISTRATIONS_ALL:
193
-                    $count = $this->registration_model->count();
194
-                    break;
195
-                case self::COUNT_REGISTRATIONS_CANCELLED:
196
-                    $count = $this->registration_model->count(
197
-                        array(
198
-                            array(
199
-                                'STS_ID' => EEM_Registration::status_id_cancelled,
200
-                            ),
201
-                        )
202
-                    );
203
-                    break;
204
-                case self::COUNT_REGISTRATIONS_INCOMPLETE:
205
-                    $count = $this->registration_model->count(
206
-                        array(
207
-                            array(
208
-                                'STS_ID' => EEM_Registration::status_id_incomplete,
209
-                            ),
210
-                        )
211
-                    );
212
-                    break;
213
-                case self::COUNT_REGISTRATIONS_NOT_APPROVED:
214
-                    $count = $this->registration_model->count(
215
-                        array(
216
-                            array(
217
-                                'STS_ID' => EEM_Registration::status_id_not_approved,
218
-                            ),
219
-                        )
220
-                    );
221
-                    break;
222
-                case self::COUNT_REGISTRATIONS_DECLINED:
223
-                    $count = $this->registration_model->count(
224
-                        array(
225
-                            array(
226
-                                'STS_ID' => EEM_Registration::status_id_declined,
227
-                            ),
228
-                        )
229
-                    );
230
-                    break;
231
-                case self::COUNT_REGISTRATIONS_PENDING:
232
-                    $count = $this->registration_model->count(
233
-                        array(
234
-                            array(
235
-                                'STS_ID' => EEM_Registration::status_id_pending_payment,
236
-                            ),
237
-                        )
238
-                    );
239
-                    break;
240
-                case self::COUNT_REGISTRATIONS_APPROVED:
241
-                    $count = $this->registration_model->count(
242
-                        array(
243
-                            array(
244
-                                'STS_ID' => EEM_Registration::status_id_approved,
245
-                            ),
246
-                        )
247
-                    );
248
-                    break;
249
-                case self::SUM_TRANSACTIONS_COMPLETE_TOTAL:
250
-                    $count = $this->transaction_model->sum(
251
-                        array(
252
-                            array(
253
-                                'STS_ID' => EEM_Transaction::complete_status_code,
254
-                            ),
255
-                        ),
256
-                        'TXN_total'
257
-                    );
258
-                    break;
259
-                case self::SUM_TRANSACTIONS_ALL_PAID:
260
-                    $count = $this->transaction_model->sum(
261
-                        array(),
262
-                        'TXN_paid'
263
-                    );
264
-                    break;
265
-                default:
266
-                    $count = null;
267
-                    break;
268
-            }
269
-        } catch (Exception $e) {
270
-            $count = null;
271
-        }
272
-        return $count;
273
-    }
152
+	/**
153
+	 * @param string $which enum (@see constants prefixed with COUNT)
154
+	 * @return int|null
155
+	 */
156
+	private function getCountFor($which)
157
+	{
158
+		try {
159
+			switch ($which) {
160
+				case self::COUNT_ALL_EVENTS:
161
+					$count = $this->event_model->count();
162
+					break;
163
+				case self::COUNT_TICKETS:
164
+					$count = $this->ticket_model->count();
165
+					break;
166
+				case self::COUNT_DATETIMES:
167
+					$count = $this->datetime_model->count();
168
+					break;
169
+				case self::COUNT_ACTIVE_EVENTS:
170
+					$count = $this->event_model->get_active_events(array(), true);
171
+					break;
172
+				case self::COUNT_DATETIMES_SOLD:
173
+					$count = $this->datetime_model->sum(array(), 'DTT_sold');
174
+					break;
175
+				case self::COUNT_TICKETS_FREE:
176
+					$count = $this->ticket_model->count(array(
177
+						array(
178
+							'TKT_price' => 0,
179
+						),
180
+					));
181
+					break;
182
+				case self::COUNT_TICKETS_PAID:
183
+					$count = $this->ticket_model->count(array(
184
+						array(
185
+							'TKT_price' => array('>', 0),
186
+						),
187
+					));
188
+					break;
189
+				case self::COUNT_TICKETS_SOLD:
190
+					$count = $this->ticket_model->sum(array(), 'TKT_sold');
191
+					break;
192
+				case self::COUNT_REGISTRATIONS_ALL:
193
+					$count = $this->registration_model->count();
194
+					break;
195
+				case self::COUNT_REGISTRATIONS_CANCELLED:
196
+					$count = $this->registration_model->count(
197
+						array(
198
+							array(
199
+								'STS_ID' => EEM_Registration::status_id_cancelled,
200
+							),
201
+						)
202
+					);
203
+					break;
204
+				case self::COUNT_REGISTRATIONS_INCOMPLETE:
205
+					$count = $this->registration_model->count(
206
+						array(
207
+							array(
208
+								'STS_ID' => EEM_Registration::status_id_incomplete,
209
+							),
210
+						)
211
+					);
212
+					break;
213
+				case self::COUNT_REGISTRATIONS_NOT_APPROVED:
214
+					$count = $this->registration_model->count(
215
+						array(
216
+							array(
217
+								'STS_ID' => EEM_Registration::status_id_not_approved,
218
+							),
219
+						)
220
+					);
221
+					break;
222
+				case self::COUNT_REGISTRATIONS_DECLINED:
223
+					$count = $this->registration_model->count(
224
+						array(
225
+							array(
226
+								'STS_ID' => EEM_Registration::status_id_declined,
227
+							),
228
+						)
229
+					);
230
+					break;
231
+				case self::COUNT_REGISTRATIONS_PENDING:
232
+					$count = $this->registration_model->count(
233
+						array(
234
+							array(
235
+								'STS_ID' => EEM_Registration::status_id_pending_payment,
236
+							),
237
+						)
238
+					);
239
+					break;
240
+				case self::COUNT_REGISTRATIONS_APPROVED:
241
+					$count = $this->registration_model->count(
242
+						array(
243
+							array(
244
+								'STS_ID' => EEM_Registration::status_id_approved,
245
+							),
246
+						)
247
+					);
248
+					break;
249
+				case self::SUM_TRANSACTIONS_COMPLETE_TOTAL:
250
+					$count = $this->transaction_model->sum(
251
+						array(
252
+							array(
253
+								'STS_ID' => EEM_Transaction::complete_status_code,
254
+							),
255
+						),
256
+						'TXN_total'
257
+					);
258
+					break;
259
+				case self::SUM_TRANSACTIONS_ALL_PAID:
260
+					$count = $this->transaction_model->sum(
261
+						array(),
262
+						'TXN_paid'
263
+					);
264
+					break;
265
+				default:
266
+					$count = null;
267
+					break;
268
+			}
269
+		} catch (Exception $e) {
270
+			$count = null;
271
+		}
272
+		return $count;
273
+	}
274 274
 
275
-    /**
276
-     * Return the active theme.
277
-     *
278
-     * @return false|string
279
-     */
280
-    private function getActiveThemeStat()
281
-    {
282
-        $theme = wp_get_theme();
283
-        return $theme->get('Name');
284
-    }
275
+	/**
276
+	 * Return the active theme.
277
+	 *
278
+	 * @return false|string
279
+	 */
280
+	private function getActiveThemeStat()
281
+	{
282
+		$theme = wp_get_theme();
283
+		return $theme->get('Name');
284
+	}
285 285
 
286
-    /**
287
-     * @return array
288
-     */
289
-    private function paymentMethodStats()
290
-    {
291
-        $payment_method_stats = array();
292
-        try {
293
-            $active_payment_methods = $this->payment_method_model->get_all_active(
294
-                null,
295
-                array('group_by' => 'PMD_type')
296
-            );
297
-            if ($active_payment_methods) {
298
-                foreach ($active_payment_methods as $payment_method) {
299
-                    $payment_method_stats[ $payment_method->name() . '_active_payment_method' ] = 1;
300
-                }
301
-            }
302
-        } catch (Exception $e) {
303
-            // do nothing just prevents fatals.
304
-        }
305
-        return $payment_method_stats;
306
-    }
286
+	/**
287
+	 * @return array
288
+	 */
289
+	private function paymentMethodStats()
290
+	{
291
+		$payment_method_stats = array();
292
+		try {
293
+			$active_payment_methods = $this->payment_method_model->get_all_active(
294
+				null,
295
+				array('group_by' => 'PMD_type')
296
+			);
297
+			if ($active_payment_methods) {
298
+				foreach ($active_payment_methods as $payment_method) {
299
+					$payment_method_stats[ $payment_method->name() . '_active_payment_method' ] = 1;
300
+				}
301
+			}
302
+		} catch (Exception $e) {
303
+			// do nothing just prevents fatals.
304
+		}
305
+		return $payment_method_stats;
306
+	}
307 307
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
             ),
145 145
         ));
146 146
         // remove any values that equal null.  This ensures any stats that weren't retrieved successfully are excluded.
147
-        return array_filter($stats, function ($value) {
147
+        return array_filter($stats, function($value) {
148 148
             return $value !== null;
149 149
         });
150 150
     }
@@ -296,7 +296,7 @@  discard block
 block discarded – undo
296 296
             );
297 297
             if ($active_payment_methods) {
298 298
                 foreach ($active_payment_methods as $payment_method) {
299
-                    $payment_method_stats[ $payment_method->name() . '_active_payment_method' ] = 1;
299
+                    $payment_method_stats[$payment_method->name().'_active_payment_method'] = 1;
300 300
                 }
301 301
             }
302 302
         } catch (Exception $e) {
Please login to merge, or discard this patch.
core/domain/services/pue/Stats.php 2 patches
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -76,9 +76,9 @@  discard block
 block discarded – undo
76 76
     public function statsCallback()
77 77
     {
78 78
         // returns a callback that can is used to retrieve the stats to send along to the pue server.
79
-        return function () {
79
+        return function() {
80 80
             // we only send stats one a week, so let's see if our stat timestamp has expired.
81
-            if (! $this->sendStats()) {
81
+            if ( ! $this->sendStats()) {
82 82
                 return array();
83 83
             }
84 84
             return $this->stats_gatherer->stats();
@@ -126,9 +126,9 @@  discard block
 block discarded – undo
126 126
      */
127 127
     public static function optinText($extra = true)
128 128
     {
129
-        if (! $extra) {
129
+        if ( ! $extra) {
130 130
             echo '<h2 class="ee-admin-settings-hdr" '
131
-                 . (! $extra ? 'id="UXIP_settings"' : '')
131
+                 . ( ! $extra ? 'id="UXIP_settings"' : '')
132 132
                  . '>'
133 133
                  . esc_html__('User eXperience Improvement Program (UXIP)', 'event_espresso')
134 134
                  . EEH_Template::get_help_tab_link('organization_logo_info')
@@ -159,7 +159,7 @@  discard block
 block discarded – undo
159 159
                 ),
160 160
                 '<a href="https://eventespresso.com/about/user-experience-improvement-program-uxip/" target="_blank">',
161 161
                 '</a>',
162
-                '<a href="' . $settings_url . '" target="_blank">',
162
+                '<a href="'.$settings_url.'" target="_blank">',
163 163
                 '</a>'
164 164
             );
165 165
         }
@@ -173,14 +173,14 @@  discard block
 block discarded – undo
173 173
     {
174 174
         wp_register_script(
175 175
             'ee-data-optin-js',
176
-            EE_GLOBAL_ASSETS_URL . 'scripts/ee-data-optin.js',
176
+            EE_GLOBAL_ASSETS_URL.'scripts/ee-data-optin.js',
177 177
             array('jquery'),
178 178
             EVENT_ESPRESSO_VERSION,
179 179
             true
180 180
         );
181 181
         wp_register_style(
182 182
             'ee-data-optin-css',
183
-            EE_GLOBAL_ASSETS_URL . 'css/ee-data-optin.css',
183
+            EE_GLOBAL_ASSETS_URL.'css/ee-data-optin.css',
184 184
             array(),
185 185
             EVENT_ESPRESSO_VERSION
186 186
         );
Please login to merge, or discard this patch.
Indentation   +201 added lines, -201 removed lines patch added patch discarded remove patch
@@ -22,86 +22,86 @@  discard block
 block discarded – undo
22 22
 class Stats
23 23
 {
24 24
 
25
-    const OPTIONS_KEY_EXPIRY_TIMESTAMP_FOR_SENDING_STATS = 'ee_uxip_stats_expiry';
26
-
27
-    /**
28
-     * @var Config
29
-     */
30
-    private $config;
31
-
32
-
33
-    /**
34
-     * @var StatsGatherer
35
-     */
36
-    private $stats_gatherer;
37
-
38
-
39
-    /**
40
-     * @var EE_Maintenance_Mode
41
-     */
42
-    private $maintenance_mode;
43
-
44
-    public function __construct(
45
-        Config $config,
46
-        EE_Maintenance_Mode $maintenance_mode,
47
-        StatsGatherer $stats_gatherer
48
-    ) {
49
-        $this->config = $config;
50
-        $this->maintenance_mode = $maintenance_mode;
51
-        $this->stats_gatherer = $stats_gatherer;
52
-        $this->setUxipNotices();
53
-    }
54
-
55
-
56
-    /**
57
-     * Displays uxip opt-in notice if necessary.
58
-     */
59
-    private function setUxipNotices()
60
-    {
61
-        if ($this->canDisplayNotices()) {
62
-            add_action('admin_notices', array($this, 'optinNotice'));
63
-            add_action('admin_enqueue_scripts', array($this, 'enqueueScripts'));
64
-            add_action('wp_ajax_espresso_data_optin', array($this, 'ajaxHandler'));
65
-        }
66
-    }
67
-
68
-
69
-    /**
70
-     * This returns the callback that PluginUpdateEngineChecker will use for getting any extra stats to send.
71
-     *
72
-     * @return Closure
73
-     */
74
-    public function statsCallback()
75
-    {
76
-        // returns a callback that can is used to retrieve the stats to send along to the pue server.
77
-        return function () {
78
-            // we only send stats one a week, so let's see if our stat timestamp has expired.
79
-            if (! $this->sendStats()) {
80
-                return array();
81
-            }
82
-            return $this->stats_gatherer->stats();
83
-        };
84
-    }
85
-
86
-
87
-    /**
88
-     * Return whether notices can be displayed or not
89
-     *
90
-     * @return bool
91
-     */
92
-    private function canDisplayNotices()
93
-    {
94
-        return ! $this->config->hasNotifiedForUxip()
95
-               && $this->maintenance_mode->level() !== EE_Maintenance_Mode::level_2_complete_maintenance;
96
-    }
97
-
98
-
99
-    /**
100
-     * Callback for the admin_notices hook that outputs the UXIP optin-in notice.
101
-     */
102
-    public function optinNotice()
103
-    {
104
-        ?>
25
+	const OPTIONS_KEY_EXPIRY_TIMESTAMP_FOR_SENDING_STATS = 'ee_uxip_stats_expiry';
26
+
27
+	/**
28
+	 * @var Config
29
+	 */
30
+	private $config;
31
+
32
+
33
+	/**
34
+	 * @var StatsGatherer
35
+	 */
36
+	private $stats_gatherer;
37
+
38
+
39
+	/**
40
+	 * @var EE_Maintenance_Mode
41
+	 */
42
+	private $maintenance_mode;
43
+
44
+	public function __construct(
45
+		Config $config,
46
+		EE_Maintenance_Mode $maintenance_mode,
47
+		StatsGatherer $stats_gatherer
48
+	) {
49
+		$this->config = $config;
50
+		$this->maintenance_mode = $maintenance_mode;
51
+		$this->stats_gatherer = $stats_gatherer;
52
+		$this->setUxipNotices();
53
+	}
54
+
55
+
56
+	/**
57
+	 * Displays uxip opt-in notice if necessary.
58
+	 */
59
+	private function setUxipNotices()
60
+	{
61
+		if ($this->canDisplayNotices()) {
62
+			add_action('admin_notices', array($this, 'optinNotice'));
63
+			add_action('admin_enqueue_scripts', array($this, 'enqueueScripts'));
64
+			add_action('wp_ajax_espresso_data_optin', array($this, 'ajaxHandler'));
65
+		}
66
+	}
67
+
68
+
69
+	/**
70
+	 * This returns the callback that PluginUpdateEngineChecker will use for getting any extra stats to send.
71
+	 *
72
+	 * @return Closure
73
+	 */
74
+	public function statsCallback()
75
+	{
76
+		// returns a callback that can is used to retrieve the stats to send along to the pue server.
77
+		return function () {
78
+			// we only send stats one a week, so let's see if our stat timestamp has expired.
79
+			if (! $this->sendStats()) {
80
+				return array();
81
+			}
82
+			return $this->stats_gatherer->stats();
83
+		};
84
+	}
85
+
86
+
87
+	/**
88
+	 * Return whether notices can be displayed or not
89
+	 *
90
+	 * @return bool
91
+	 */
92
+	private function canDisplayNotices()
93
+	{
94
+		return ! $this->config->hasNotifiedForUxip()
95
+			   && $this->maintenance_mode->level() !== EE_Maintenance_Mode::level_2_complete_maintenance;
96
+	}
97
+
98
+
99
+	/**
100
+	 * Callback for the admin_notices hook that outputs the UXIP optin-in notice.
101
+	 */
102
+	public function optinNotice()
103
+	{
104
+		?>
105 105
         <div class="updated data-collect-optin" id="espresso-data-collect-optin-container">
106 106
             <div id="data-collect-optin-options-container">
107 107
                 <span class="dashicons dashicons-admin-site"></span>
@@ -114,125 +114,125 @@  discard block
 block discarded – undo
114 114
             </div>
115 115
         </div>
116 116
         <?php
117
-    }
118
-
119
-
120
-    /**
121
-     * Retrieves the optin text (static so it can be used in multiple places as necessary).
122
-     *
123
-     * @param bool $extra
124
-     */
125
-    public static function optinText($extra = true)
126
-    {
127
-        if (! $extra) {
128
-            echo '<h2 class="ee-admin-settings-hdr" '
129
-                 . (! $extra ? 'id="UXIP_settings"' : '')
130
-                 . '>'
131
-                 . esc_html__('User eXperience Improvement Program (UXIP)', 'event_espresso')
132
-                 . EEH_Template::get_help_tab_link('organization_logo_info')
133
-                 . '</h2>';
134
-            printf(
135
-                esc_html__(
136
-                    '%1$sPlease help us make Event Espresso better and vote for your favorite features.%2$s The %3$sUser eXperience Improvement Program (UXIP)%4$s, has been created so when you use Event Espresso you are voting for the features and settings that are important to you. The UXIP helps us understand how you use our products and services, track problems and in what context. If you opt-out of the UXIP you essentially elect for us to disregard how you use Event Espresso as we build new features and make changes. Participation in the program is completely voluntary and it is disabled by default. The end results of the UXIP are software improvements to better meet your needs. The data we collect will never be sold, traded, or misused in any way. %5$sPlease see our %6$sPrivacy Policy%7$s for more information.',
137
-                    'event_espresso'
138
-                ),
139
-                '<p><em>',
140
-                '</em></p>',
141
-                '<a href="https://eventespresso.com/about/user-experience-improvement-program-uxip/" target="_blank">',
142
-                '</a>',
143
-                '<br><br>',
144
-                '<a href="https://eventespresso.com/about/privacy-policy/" target="_blank">',
145
-                '</a>'
146
-            );
147
-        } else {
148
-            $settings_url = EE_Admin_Page::add_query_args_and_nonce(
149
-                array('action' => 'default'),
150
-                admin_url('admin.php?page=espresso_general_settings')
151
-            );
152
-            $settings_url .= '#UXIP_settings';
153
-            printf(
154
-                esc_html__(
155
-                    'The Event Espresso UXIP feature is not yet active on your site. For %1$smore info%2$s and to opt-in %3$sclick here%4$s.',
156
-                    'event_espresso'
157
-                ),
158
-                '<a href="https://eventespresso.com/about/user-experience-improvement-program-uxip/" target="_blank">',
159
-                '</a>',
160
-                '<a href="' . $settings_url . '" target="_blank">',
161
-                '</a>'
162
-            );
163
-        }
164
-    }
165
-
166
-
167
-    /**
168
-     * Callback for admin_enqueue_scripts that sets up the scripts and styles for the uxip notice
169
-     */
170
-    public function enqueueScripts()
171
-    {
172
-        wp_register_script(
173
-            'ee-data-optin-js',
174
-            EE_GLOBAL_ASSETS_URL . 'scripts/ee-data-optin.js',
175
-            array('jquery'),
176
-            EVENT_ESPRESSO_VERSION,
177
-            true
178
-        );
179
-        wp_register_style(
180
-            'ee-data-optin-css',
181
-            EE_GLOBAL_ASSETS_URL . 'css/ee-data-optin.css',
182
-            array(),
183
-            EVENT_ESPRESSO_VERSION
184
-        );
185
-
186
-        wp_enqueue_script('ee-data-optin-js');
187
-        wp_enqueue_style('ee-data-optin-css');
188
-    }
189
-
190
-
191
-    /**
192
-     * Callback for wp_ajax_espresso_data_optin that handles the ajax request
193
-     */
194
-    public function ajaxHandler()
195
-    {
196
-        // verify nonce
197
-        if (isset($_POST['nonce']) && ! wp_verify_nonce($_POST['nonce'], 'ee-data-optin')) {
198
-            exit();
199
-        }
200
-
201
-        // update has notified option
202
-        $this->config->setHasNotifiedAboutUxip();
203
-        exit();
204
-    }
205
-
206
-
207
-    /**
208
-     * Used to determine whether additional stats are sent.
209
-     */
210
-    private function sendStats()
211
-    {
212
-        return $this->config->isOptedInForUxip()
213
-               && $this->maintenance_mode->level() !== EE_Maintenance_Mode::level_2_complete_maintenance
214
-               && $this->statSendTimestampExpired();
215
-    }
216
-
217
-
218
-    /**
219
-     * Returns true when the timestamp used to track whether stats get sent (currently a weekly interval) is expired.
220
-     * Returns false otherwise.
221
-     *
222
-     * @return bool
223
-     */
224
-    private function statSendTimestampExpired()
225
-    {
226
-        $current_expiry = get_option(self::OPTIONS_KEY_EXPIRY_TIMESTAMP_FOR_SENDING_STATS, null);
227
-        if ($current_expiry === null) {
228
-            add_option(self::OPTIONS_KEY_EXPIRY_TIMESTAMP_FOR_SENDING_STATS, time() + WEEK_IN_SECONDS, '', 'no');
229
-            return true;
230
-        }
231
-
232
-        if (time() > (int) $current_expiry) {
233
-            update_option(self::OPTIONS_KEY_EXPIRY_TIMESTAMP_FOR_SENDING_STATS, time() + WEEK_IN_SECONDS);
234
-            return true;
235
-        }
236
-        return false;
237
-    }
117
+	}
118
+
119
+
120
+	/**
121
+	 * Retrieves the optin text (static so it can be used in multiple places as necessary).
122
+	 *
123
+	 * @param bool $extra
124
+	 */
125
+	public static function optinText($extra = true)
126
+	{
127
+		if (! $extra) {
128
+			echo '<h2 class="ee-admin-settings-hdr" '
129
+				 . (! $extra ? 'id="UXIP_settings"' : '')
130
+				 . '>'
131
+				 . esc_html__('User eXperience Improvement Program (UXIP)', 'event_espresso')
132
+				 . EEH_Template::get_help_tab_link('organization_logo_info')
133
+				 . '</h2>';
134
+			printf(
135
+				esc_html__(
136
+					'%1$sPlease help us make Event Espresso better and vote for your favorite features.%2$s The %3$sUser eXperience Improvement Program (UXIP)%4$s, has been created so when you use Event Espresso you are voting for the features and settings that are important to you. The UXIP helps us understand how you use our products and services, track problems and in what context. If you opt-out of the UXIP you essentially elect for us to disregard how you use Event Espresso as we build new features and make changes. Participation in the program is completely voluntary and it is disabled by default. The end results of the UXIP are software improvements to better meet your needs. The data we collect will never be sold, traded, or misused in any way. %5$sPlease see our %6$sPrivacy Policy%7$s for more information.',
137
+					'event_espresso'
138
+				),
139
+				'<p><em>',
140
+				'</em></p>',
141
+				'<a href="https://eventespresso.com/about/user-experience-improvement-program-uxip/" target="_blank">',
142
+				'</a>',
143
+				'<br><br>',
144
+				'<a href="https://eventespresso.com/about/privacy-policy/" target="_blank">',
145
+				'</a>'
146
+			);
147
+		} else {
148
+			$settings_url = EE_Admin_Page::add_query_args_and_nonce(
149
+				array('action' => 'default'),
150
+				admin_url('admin.php?page=espresso_general_settings')
151
+			);
152
+			$settings_url .= '#UXIP_settings';
153
+			printf(
154
+				esc_html__(
155
+					'The Event Espresso UXIP feature is not yet active on your site. For %1$smore info%2$s and to opt-in %3$sclick here%4$s.',
156
+					'event_espresso'
157
+				),
158
+				'<a href="https://eventespresso.com/about/user-experience-improvement-program-uxip/" target="_blank">',
159
+				'</a>',
160
+				'<a href="' . $settings_url . '" target="_blank">',
161
+				'</a>'
162
+			);
163
+		}
164
+	}
165
+
166
+
167
+	/**
168
+	 * Callback for admin_enqueue_scripts that sets up the scripts and styles for the uxip notice
169
+	 */
170
+	public function enqueueScripts()
171
+	{
172
+		wp_register_script(
173
+			'ee-data-optin-js',
174
+			EE_GLOBAL_ASSETS_URL . 'scripts/ee-data-optin.js',
175
+			array('jquery'),
176
+			EVENT_ESPRESSO_VERSION,
177
+			true
178
+		);
179
+		wp_register_style(
180
+			'ee-data-optin-css',
181
+			EE_GLOBAL_ASSETS_URL . 'css/ee-data-optin.css',
182
+			array(),
183
+			EVENT_ESPRESSO_VERSION
184
+		);
185
+
186
+		wp_enqueue_script('ee-data-optin-js');
187
+		wp_enqueue_style('ee-data-optin-css');
188
+	}
189
+
190
+
191
+	/**
192
+	 * Callback for wp_ajax_espresso_data_optin that handles the ajax request
193
+	 */
194
+	public function ajaxHandler()
195
+	{
196
+		// verify nonce
197
+		if (isset($_POST['nonce']) && ! wp_verify_nonce($_POST['nonce'], 'ee-data-optin')) {
198
+			exit();
199
+		}
200
+
201
+		// update has notified option
202
+		$this->config->setHasNotifiedAboutUxip();
203
+		exit();
204
+	}
205
+
206
+
207
+	/**
208
+	 * Used to determine whether additional stats are sent.
209
+	 */
210
+	private function sendStats()
211
+	{
212
+		return $this->config->isOptedInForUxip()
213
+			   && $this->maintenance_mode->level() !== EE_Maintenance_Mode::level_2_complete_maintenance
214
+			   && $this->statSendTimestampExpired();
215
+	}
216
+
217
+
218
+	/**
219
+	 * Returns true when the timestamp used to track whether stats get sent (currently a weekly interval) is expired.
220
+	 * Returns false otherwise.
221
+	 *
222
+	 * @return bool
223
+	 */
224
+	private function statSendTimestampExpired()
225
+	{
226
+		$current_expiry = get_option(self::OPTIONS_KEY_EXPIRY_TIMESTAMP_FOR_SENDING_STATS, null);
227
+		if ($current_expiry === null) {
228
+			add_option(self::OPTIONS_KEY_EXPIRY_TIMESTAMP_FOR_SENDING_STATS, time() + WEEK_IN_SECONDS, '', 'no');
229
+			return true;
230
+		}
231
+
232
+		if (time() > (int) $current_expiry) {
233
+			update_option(self::OPTIONS_KEY_EXPIRY_TIMESTAMP_FOR_SENDING_STATS, time() + WEEK_IN_SECONDS);
234
+			return true;
235
+		}
236
+		return false;
237
+	}
238 238
 }
Please login to merge, or discard this patch.
core/domain/services/ticket/CancelTicketLineItemService.php 2 patches
Indentation   +105 added lines, -105 removed lines patch added patch discarded remove patch
@@ -20,113 +20,113 @@
 block discarded – undo
20 20
 {
21 21
 
22 22
 
23
-    /**
24
-     * @param \EE_Registration $registration
25
-     * @param int              $quantity
26
-     * @return bool|int
27
-     */
28
-    public function forRegistration(\EE_Registration $registration, $quantity = 1)
29
-    {
30
-        return $this->cancel(
31
-            $registration->transaction(),
32
-            $registration->ticket(),
33
-            $quantity,
34
-            $registration->ticket_line_item()
35
-        );
36
-    }
23
+	/**
24
+	 * @param \EE_Registration $registration
25
+	 * @param int              $quantity
26
+	 * @return bool|int
27
+	 */
28
+	public function forRegistration(\EE_Registration $registration, $quantity = 1)
29
+	{
30
+		return $this->cancel(
31
+			$registration->transaction(),
32
+			$registration->ticket(),
33
+			$quantity,
34
+			$registration->ticket_line_item()
35
+		);
36
+	}
37 37
 
38 38
 
39
-    /**
40
-     * @param \EE_Transaction $transaction
41
-     * @param \EE_Ticket      $ticket
42
-     * @param int             $quantity
43
-     * @param \EE_Line_Item   $ticket_line_item
44
-     * @return bool|int
45
-     */
46
-    public function cancel(
47
-        \EE_Transaction $transaction,
48
-        \EE_Ticket $ticket,
49
-        $quantity = 1,
50
-        \EE_Line_Item $ticket_line_item = null
51
-    ) {
52
-        $ticket_line_item = $ticket_line_item instanceof \EE_Line_Item
53
-            ? $ticket_line_item
54
-            : $this->getTicketLineItem($transaction, $ticket);
55
-        // first we need to decrement the ticket quantity
56
-        \EEH_Line_Item::decrement_quantity($ticket_line_item, $quantity);
57
-        // no tickets left for this line item ?
58
-        if ((int) $ticket_line_item->quantity() === 0) {
59
-            // then just set this line item as cancelled, save, and get out
60
-            $ticket_line_item->set_type(\EEM_Line_Item::type_cancellation);
61
-            $success = $ticket_line_item->save();
62
-        } else {
63
-            // otherwise create a new cancelled line item, so that we have a record of the cancellation
64
-            $items_subtotal = \EEH_Line_Item::get_pre_tax_subtotal(
65
-                \EEH_Line_Item::get_event_line_item_for_ticket(
66
-                    $transaction->total_line_item(),
67
-                    $ticket
68
-                )
69
-            );
70
-            $cancelled_line_item = \EE_Line_Item::new_instance(
71
-                array(
72
-                    'LIN_name'       => $ticket_line_item->name(),
73
-                    'LIN_desc'       => sprintf(
74
-                        __('%1$s Cancelled: %2$s', 'event_espresso'),
75
-                        $ticket_line_item->desc(),
76
-                        date('Y-m-d h:i a')
77
-                    ),
78
-                    'LIN_unit_price' => (float) $ticket_line_item->unit_price(),
79
-                    'LIN_quantity'   => $quantity,
80
-                    'LIN_percent'    => null,
81
-                    'LIN_is_taxable' => false,
82
-                    'LIN_order'      => $items_subtotal instanceof \EE_Line_Item
83
-                        ? count($items_subtotal->children())
84
-                        : 0,
85
-                    'LIN_total'      => (float) $ticket_line_item->unit_price(),
86
-                    'LIN_type'       => \EEM_Line_Item::type_cancellation,
87
-                )
88
-            );
89
-            $success = \EEH_Line_Item::add_item($transaction->total_line_item(), $cancelled_line_item);
90
-        }
91
-        if (! $success) {
92
-            throw new \RuntimeException(
93
-                sprintf(
94
-                    __('An error occurred while attempting to cancel ticket line item %1$s', 'event_espresso'),
95
-                    $ticket_line_item->ID()
96
-                )
97
-            );
98
-        }
99
-        return $success;
100
-    }
39
+	/**
40
+	 * @param \EE_Transaction $transaction
41
+	 * @param \EE_Ticket      $ticket
42
+	 * @param int             $quantity
43
+	 * @param \EE_Line_Item   $ticket_line_item
44
+	 * @return bool|int
45
+	 */
46
+	public function cancel(
47
+		\EE_Transaction $transaction,
48
+		\EE_Ticket $ticket,
49
+		$quantity = 1,
50
+		\EE_Line_Item $ticket_line_item = null
51
+	) {
52
+		$ticket_line_item = $ticket_line_item instanceof \EE_Line_Item
53
+			? $ticket_line_item
54
+			: $this->getTicketLineItem($transaction, $ticket);
55
+		// first we need to decrement the ticket quantity
56
+		\EEH_Line_Item::decrement_quantity($ticket_line_item, $quantity);
57
+		// no tickets left for this line item ?
58
+		if ((int) $ticket_line_item->quantity() === 0) {
59
+			// then just set this line item as cancelled, save, and get out
60
+			$ticket_line_item->set_type(\EEM_Line_Item::type_cancellation);
61
+			$success = $ticket_line_item->save();
62
+		} else {
63
+			// otherwise create a new cancelled line item, so that we have a record of the cancellation
64
+			$items_subtotal = \EEH_Line_Item::get_pre_tax_subtotal(
65
+				\EEH_Line_Item::get_event_line_item_for_ticket(
66
+					$transaction->total_line_item(),
67
+					$ticket
68
+				)
69
+			);
70
+			$cancelled_line_item = \EE_Line_Item::new_instance(
71
+				array(
72
+					'LIN_name'       => $ticket_line_item->name(),
73
+					'LIN_desc'       => sprintf(
74
+						__('%1$s Cancelled: %2$s', 'event_espresso'),
75
+						$ticket_line_item->desc(),
76
+						date('Y-m-d h:i a')
77
+					),
78
+					'LIN_unit_price' => (float) $ticket_line_item->unit_price(),
79
+					'LIN_quantity'   => $quantity,
80
+					'LIN_percent'    => null,
81
+					'LIN_is_taxable' => false,
82
+					'LIN_order'      => $items_subtotal instanceof \EE_Line_Item
83
+						? count($items_subtotal->children())
84
+						: 0,
85
+					'LIN_total'      => (float) $ticket_line_item->unit_price(),
86
+					'LIN_type'       => \EEM_Line_Item::type_cancellation,
87
+				)
88
+			);
89
+			$success = \EEH_Line_Item::add_item($transaction->total_line_item(), $cancelled_line_item);
90
+		}
91
+		if (! $success) {
92
+			throw new \RuntimeException(
93
+				sprintf(
94
+					__('An error occurred while attempting to cancel ticket line item %1$s', 'event_espresso'),
95
+					$ticket_line_item->ID()
96
+				)
97
+			);
98
+		}
99
+		return $success;
100
+	}
101 101
 
102 102
 
103
-    /**
104
-     * @param \EE_Transaction $transaction
105
-     * @param \EE_Ticket      $ticket
106
-     * @return \EE_Line_Item
107
-     * @throws EntityNotFoundException
108
-     * @throws \EE_Error
109
-     */
110
-    protected static function getTicketLineItem(\EE_Transaction $transaction, \EE_Ticket $ticket)
111
-    {
112
-        $line_item = null;
113
-        $ticket_line_items = \EEH_Line_Item::get_line_items_by_object_type_and_IDs(
114
-            $transaction->total_line_item(),
115
-            'Ticket',
116
-            array($ticket->ID())
117
-        );
118
-        foreach ($ticket_line_items as $ticket_line_item) {
119
-            if ($ticket_line_item instanceof \EE_Line_Item
120
-                && $ticket_line_item->OBJ_type() === 'Ticket'
121
-                && $ticket_line_item->OBJ_ID() === $ticket->ID()
122
-            ) {
123
-                $line_item = $ticket_line_item;
124
-                break;
125
-            }
126
-        }
127
-        if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
128
-            throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
129
-        }
130
-        return $line_item;
131
-    }
103
+	/**
104
+	 * @param \EE_Transaction $transaction
105
+	 * @param \EE_Ticket      $ticket
106
+	 * @return \EE_Line_Item
107
+	 * @throws EntityNotFoundException
108
+	 * @throws \EE_Error
109
+	 */
110
+	protected static function getTicketLineItem(\EE_Transaction $transaction, \EE_Ticket $ticket)
111
+	{
112
+		$line_item = null;
113
+		$ticket_line_items = \EEH_Line_Item::get_line_items_by_object_type_and_IDs(
114
+			$transaction->total_line_item(),
115
+			'Ticket',
116
+			array($ticket->ID())
117
+		);
118
+		foreach ($ticket_line_items as $ticket_line_item) {
119
+			if ($ticket_line_item instanceof \EE_Line_Item
120
+				&& $ticket_line_item->OBJ_type() === 'Ticket'
121
+				&& $ticket_line_item->OBJ_ID() === $ticket->ID()
122
+			) {
123
+				$line_item = $ticket_line_item;
124
+				break;
125
+			}
126
+		}
127
+		if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
128
+			throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
129
+		}
130
+		return $line_item;
131
+	}
132 132
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -88,7 +88,7 @@  discard block
 block discarded – undo
88 88
             );
89 89
             $success = \EEH_Line_Item::add_item($transaction->total_line_item(), $cancelled_line_item);
90 90
         }
91
-        if (! $success) {
91
+        if ( ! $success) {
92 92
             throw new \RuntimeException(
93 93
                 sprintf(
94 94
                     __('An error occurred while attempting to cancel ticket line item %1$s', 'event_espresso'),
@@ -124,7 +124,7 @@  discard block
 block discarded – undo
124 124
                 break;
125 125
             }
126 126
         }
127
-        if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
127
+        if ( ! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
128 128
             throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
129 129
         }
130 130
         return $line_item;
Please login to merge, or discard this patch.
core/domain/services/capabilities/CapabilitiesChecker.php 2 patches
Indentation   +72 added lines, -72 removed lines patch added patch discarded remove patch
@@ -18,84 +18,84 @@
 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 (! $this->capabilities()->current_user_can(
77
-                $capability,
78
-                $cap_check->context(),
79
-                $cap_check->ID()
80
-            )) {
81
-                throw new InsufficientPermissionsException($cap_check->context());
82
-            }
83
-        }
84
-        return true;
85
-    }
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 (! $this->capabilities()->current_user_can(
77
+				$capability,
78
+				$cap_check->context(),
79
+				$cap_check->ID()
80
+			)) {
81
+				throw new InsufficientPermissionsException($cap_check->context());
82
+			}
83
+		}
84
+		return true;
85
+	}
86 86
 
87 87
 
88
-    /**
89
-     * @param string $capability - the capability to be checked, like: 'ee_edit_registrations'
90
-     * @param string $context    - what the user is attempting to do, like: 'Edit Registration'
91
-     * @param int    $ID         - (optional) ID for item where current_user_can is being called from
92
-     * @return bool
93
-     * @throws InvalidDataTypeException
94
-     * @throws InsufficientPermissionsException
95
-     * @throws InvalidClassException
96
-     */
97
-    public function process($capability, $context, $ID = 0)
98
-    {
99
-        return $this->processCapCheck(new CapCheck($capability, $context, $ID));
100
-    }
88
+	/**
89
+	 * @param string $capability - the capability to be checked, like: 'ee_edit_registrations'
90
+	 * @param string $context    - what the user is attempting to do, like: 'Edit Registration'
91
+	 * @param int    $ID         - (optional) ID for item where current_user_can is being called from
92
+	 * @return bool
93
+	 * @throws InvalidDataTypeException
94
+	 * @throws InsufficientPermissionsException
95
+	 * @throws InvalidClassException
96
+	 */
97
+	public function process($capability, $context, $ID = 0)
98
+	{
99
+		return $this->processCapCheck(new CapCheck($capability, $context, $ID));
100
+	}
101 101
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -62,7 +62,7 @@  discard block
 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
             );
@@ -73,7 +73,7 @@  discard block
 block discarded – undo
73 73
         }
74 74
         $capabilities = (array) $cap_check->capability();
75 75
         foreach ($capabilities as $capability) {
76
-            if (! $this->capabilities()->current_user_can(
76
+            if ( ! $this->capabilities()->current_user_can(
77 77
                 $capability,
78 78
                 $cap_check->context(),
79 79
                 $cap_check->ID()
Please login to merge, or discard this patch.
domain/services/attendee/forms/AttendeeContactDetailsMetaboxFormHandler.php 1 patch
Indentation   +75 added lines, -75 removed lines patch added patch discarded remove patch
@@ -27,84 +27,84 @@
 block discarded – undo
27 27
 {
28 28
 
29 29
 
30
-    protected $attendee;
30
+	protected $attendee;
31 31
 
32 32
 
33
-    /**
34
-     * AttendeeContactDetailsMetaboxFormHandler constructor.
35
-     *
36
-     * @param EE_Attendee $attendee
37
-     * @param EE_Registry $registry
38
-     * @throws DomainException
39
-     * @throws InvalidDataTypeException
40
-     * @throws InvalidArgumentException
41
-     */
42
-    public function __construct(EE_Attendee $attendee, EE_Registry $registry)
43
-    {
44
-        $this->attendee = $attendee;
45
-        $label = esc_html__('Contact Details', 'event_espresso');
46
-        parent::__construct(
47
-            $label,
48
-            $label,
49
-            'attendee_contact_details',
50
-            '',
51
-            FormHandler::DO_NOT_SETUP_FORM,
52
-            $registry
53
-        );
54
-    }
33
+	/**
34
+	 * AttendeeContactDetailsMetaboxFormHandler constructor.
35
+	 *
36
+	 * @param EE_Attendee $attendee
37
+	 * @param EE_Registry $registry
38
+	 * @throws DomainException
39
+	 * @throws InvalidDataTypeException
40
+	 * @throws InvalidArgumentException
41
+	 */
42
+	public function __construct(EE_Attendee $attendee, EE_Registry $registry)
43
+	{
44
+		$this->attendee = $attendee;
45
+		$label = esc_html__('Contact Details', 'event_espresso');
46
+		parent::__construct(
47
+			$label,
48
+			$label,
49
+			'attendee_contact_details',
50
+			'',
51
+			FormHandler::DO_NOT_SETUP_FORM,
52
+			$registry
53
+		);
54
+	}
55 55
 
56
-    /**
57
-     * creates and returns the actual form
58
-     *
59
-     * @return EE_Form_Section_Proper
60
-     * @throws EE_Error
61
-     */
62
-    public function generate()
63
-    {
64
-        return new EE_Form_Section_Proper(
65
-            array(
66
-                'name'            => 'attendee_contact_details',
67
-                'html_id'         => 'attendee-contact-details',
68
-                'html_class'      => 'form-table',
69
-                'layout_strategy' => new EE_Admin_One_Column_Layout(),
70
-                'subsections'     => array(
71
-                    'ATT_email' => new EE_Email_Input(
72
-                        array(
73
-                            'default'         => $this->attendee->email(),
74
-                            'html_label_text' => esc_html__('Email Address', 'event_espresso'),
75
-                            'required'        => true,
76
-                        )
77
-                    ),
78
-                    'ATT_phone' => new EE_Text_Input(
79
-                        array(
80
-                            'default'         => $this->attendee->phone(),
81
-                            'html_label_text' => esc_html__('Phone Number', 'event_espresso'),
82
-                        )
83
-                    ),
84
-                ),
85
-            )
86
-        );
87
-    }
56
+	/**
57
+	 * creates and returns the actual form
58
+	 *
59
+	 * @return EE_Form_Section_Proper
60
+	 * @throws EE_Error
61
+	 */
62
+	public function generate()
63
+	{
64
+		return new EE_Form_Section_Proper(
65
+			array(
66
+				'name'            => 'attendee_contact_details',
67
+				'html_id'         => 'attendee-contact-details',
68
+				'html_class'      => 'form-table',
69
+				'layout_strategy' => new EE_Admin_One_Column_Layout(),
70
+				'subsections'     => array(
71
+					'ATT_email' => new EE_Email_Input(
72
+						array(
73
+							'default'         => $this->attendee->email(),
74
+							'html_label_text' => esc_html__('Email Address', 'event_espresso'),
75
+							'required'        => true,
76
+						)
77
+					),
78
+					'ATT_phone' => new EE_Text_Input(
79
+						array(
80
+							'default'         => $this->attendee->phone(),
81
+							'html_label_text' => esc_html__('Phone Number', 'event_espresso'),
82
+						)
83
+					),
84
+				),
85
+			)
86
+		);
87
+	}
88 88
 
89 89
 
90
-    /**
91
-     * Process form data.
92
-     *
93
-     * @param array $form_data
94
-     * @return bool
95
-     * @throws EE_Error
96
-     * @throws InvalidFormSubmissionException
97
-     * @throws LogicException
98
-     */
99
-    public function process($form_data = array())
100
-    {
101
-        $valid_data = (array) parent::process($form_data);
102
-        if (empty($valid_data)) {
103
-            return false;
104
-        }
105
-        $this->attendee->set_email($valid_data['ATT_email']);
106
-        $this->attendee->set_phone($valid_data['ATT_phone']);
107
-        $updated = $this->attendee->save();
108
-        return $updated !== false;
109
-    }
90
+	/**
91
+	 * Process form data.
92
+	 *
93
+	 * @param array $form_data
94
+	 * @return bool
95
+	 * @throws EE_Error
96
+	 * @throws InvalidFormSubmissionException
97
+	 * @throws LogicException
98
+	 */
99
+	public function process($form_data = array())
100
+	{
101
+		$valid_data = (array) parent::process($form_data);
102
+		if (empty($valid_data)) {
103
+			return false;
104
+		}
105
+		$this->attendee->set_email($valid_data['ATT_email']);
106
+		$this->attendee->set_phone($valid_data['ATT_phone']);
107
+		$updated = $this->attendee->save();
108
+		return $updated !== false;
109
+	}
110 110
 }
Please login to merge, or discard this patch.
core/domain/values/EmailAddress.php 1 patch
Indentation   +44 added lines, -44 removed lines patch added patch discarded remove patch
@@ -15,56 +15,56 @@
 block discarded – undo
15 15
 class EmailAddress
16 16
 {
17 17
 
18
-    /**
19
-     * @var string $email_address
20
-     */
21
-    private $email_address;
18
+	/**
19
+	 * @var string $email_address
20
+	 */
21
+	private $email_address;
22 22
 
23 23
 
24
-    /**
25
-     * EmailAddress constructor.
26
-     *
27
-     * @param string                  $email_address
28
-     * @param EmailValidatorInterface $validator
29
-     * @throws EmailValidationException
30
-     */
31
-    public function __construct($email_address, EmailValidatorInterface $validator)
32
-    {
33
-        $validator->validate($email_address);
34
-        $this->email_address = $email_address;
35
-    }
24
+	/**
25
+	 * EmailAddress constructor.
26
+	 *
27
+	 * @param string                  $email_address
28
+	 * @param EmailValidatorInterface $validator
29
+	 * @throws EmailValidationException
30
+	 */
31
+	public function __construct($email_address, EmailValidatorInterface $validator)
32
+	{
33
+		$validator->validate($email_address);
34
+		$this->email_address = $email_address;
35
+	}
36 36
 
37 37
 
38
-    /**
39
-     * returns the string value for this EmailAddress
40
-     *
41
-     * @return string
42
-     */
43
-    public function get()
44
-    {
45
-        return $this->email_address;
46
-    }
38
+	/**
39
+	 * returns the string value for this EmailAddress
40
+	 *
41
+	 * @return string
42
+	 */
43
+	public function get()
44
+	{
45
+		return $this->email_address;
46
+	}
47 47
 
48 48
 
49
-    /**
50
-     * compare another EmailAddress to this one to determine if they are the same
51
-     *
52
-     * @param EmailAddress $address
53
-     * @return bool
54
-     */
55
-    public function equals(EmailAddress $address)
56
-    {
57
-        return strtolower((string) $this) === strtolower((string) $address);
58
-    }
49
+	/**
50
+	 * compare another EmailAddress to this one to determine if they are the same
51
+	 *
52
+	 * @param EmailAddress $address
53
+	 * @return bool
54
+	 */
55
+	public function equals(EmailAddress $address)
56
+	{
57
+		return strtolower((string) $this) === strtolower((string) $address);
58
+	}
59 59
 
60 60
 
61
-    /**
62
-     * allows an EmailAddress object to be used as a string
63
-     *
64
-     * @return string
65
-     */
66
-    public function __toString()
67
-    {
68
-        return $this->email_address;
69
-    }
61
+	/**
62
+	 * allows an EmailAddress object to be used as a string
63
+	 *
64
+	 * @return string
65
+	 */
66
+	public function __toString()
67
+	{
68
+		return $this->email_address;
69
+	}
70 70
 }
Please login to merge, or discard this patch.
core/domain/values/model/CustomSelects.php 2 patches
Indentation   +335 added lines, -335 removed lines patch added patch discarded remove patch
@@ -17,339 +17,339 @@
 block discarded – undo
17 17
  */
18 18
 class CustomSelects
19 19
 {
20
-    const TYPE_SIMPLE = 'simple';
21
-    const TYPE_COMPLEX = 'complex';
22
-    const TYPE_STRUCTURED = 'structured';
23
-
24
-    private $valid_operators = array('COUNT', 'SUM');
25
-
26
-
27
-    /**
28
-     * Original incoming select array
29
-     *
30
-     * @var array
31
-     */
32
-    private $original_selects;
33
-
34
-    /**
35
-     * Select string that can be added to the query
36
-     *
37
-     * @var string
38
-     */
39
-    private $columns_to_select_expression;
40
-
41
-
42
-    /**
43
-     * An array of aliases for the columns included in the incoming select array.
44
-     *
45
-     * @var array
46
-     */
47
-    private $column_aliases_in_select;
48
-
49
-
50
-    /**
51
-     * Enum representation of the "type" of array coming into this value object.
52
-     *
53
-     * @var string
54
-     */
55
-    private $type = '';
56
-
57
-
58
-    /**
59
-     * CustomSelects constructor.
60
-     * Incoming selects can be in one of the following formats:
61
-     * ---- self::TYPE_SIMPLE array ----
62
-     * This is considered the "simple" type. In this case the array is an numerically indexed array with single or
63
-     * multiple columns to select as the values.
64
-     * eg. array( 'ATT_ID', 'REG_ID' )
65
-     * eg. array( '*' )
66
-     * If you want to use the columns in any WHERE, GROUP BY, or HAVING clauses, you must instead use the "complex" or
67
-     * "structured" method.
68
-     * ---- self::TYPE_COMPLEX array ----
69
-     * This is considered the "complex" type.  In this case the array is indexed by arbitrary strings that serve as
70
-     * column alias, and the value is an numerically indexed array where there are two values.  The first value (0) is
71
-     * the selection and the second value (1) is the data type.  Data types must be one of the types defined in
72
-     * EEM_Base::$_valid_wpdb_data_types.
73
-     * eg. array( 'count' => array('count(REG_ID)', '%d') )
74
-     * Complex array configuration allows for using the column alias in any WHERE, GROUP BY, or HAVING clauses.
75
-     * ---- self::TYPE_STRUCTURED array ---
76
-     * This is considered the "structured" type. This type is similar to the complex type except that the array attached
77
-     * to the column alias contains three values.  The first value is the qualified column name (which can include
78
-     * join syntax for models).  The second value is the operator performed on the column (i.e. 'COUNT', 'SUM' etc).,
79
-     * the third value is the data type.  Note, if the select does not have an operator, you can use an empty string for
80
-     * the second value.
81
-     * Note: for now SUM is only for simple single column expressions (i.e. SUM(Transaction.TXN_total))
82
-     * eg. array( 'registration_count' => array('Registration.REG_ID', 'count', '%d') );
83
-     * NOTE: mixing array types in the incoming $select will cause errors.
84
-     *
85
-     * @param array $selects
86
-     * @throws InvalidArgumentException
87
-     */
88
-    public function __construct(array $selects)
89
-    {
90
-        $this->original_selects = $selects;
91
-        $this->deriveType($selects);
92
-        $this->deriveParts($selects);
93
-    }
94
-
95
-
96
-    /**
97
-     * Derives what type of custom select has been sent in.
98
-     *
99
-     * @param array $selects
100
-     * @throws InvalidArgumentException
101
-     */
102
-    private function deriveType(array $selects)
103
-    {
104
-        // first if the first key for this array is an integer then its coming in as a simple format, so we'll also
105
-        // ensure all elements of the array are simple.
106
-        if (is_int(key($selects))) {
107
-            // let's ensure all keys are ints
108
-            $invalid_keys = array_filter(
109
-                array_keys($selects),
110
-                function ($value) {
111
-                    return ! is_int($value);
112
-                }
113
-            );
114
-            if (! empty($invalid_keys)) {
115
-                throw new InvalidArgumentException(
116
-                    sprintf(
117
-                        esc_html__(
118
-                            'Incoming array looks like its formatted for "%1$s" type selects, however it has elements that are not indexed numerically',
119
-                            'event_espresso'
120
-                        ),
121
-                        self::TYPE_SIMPLE
122
-                    )
123
-                );
124
-            }
125
-            $this->type = self::TYPE_SIMPLE;
126
-            return;
127
-        }
128
-        // made it here so that means we've got either complex or structured selects.  Let's find out which by popping
129
-        // the first array element off.
130
-        $first_element = reset($selects);
131
-
132
-        if (! is_array($first_element)) {
133
-            throw new InvalidArgumentException(
134
-                sprintf(
135
-                    esc_html__(
136
-                        'Incoming array looks like its formatted as a "%1$s" or "%2$s" type.  However, the values in the array must be arrays themselves and they are not.',
137
-                        'event_espresso'
138
-                    ),
139
-                    self::TYPE_COMPLEX,
140
-                    self::TYPE_STRUCTURED
141
-                )
142
-            );
143
-        }
144
-        $this->type = count($first_element) === 2
145
-            ? self::TYPE_COMPLEX
146
-            : self::TYPE_STRUCTURED;
147
-    }
148
-
149
-
150
-    /**
151
-     * Sets up the various properties for the vo depending on type.
152
-     *
153
-     * @param array $selects
154
-     * @throws InvalidArgumentException
155
-     */
156
-    private function deriveParts(array $selects)
157
-    {
158
-        $column_parts = array();
159
-        switch ($this->type) {
160
-            case self::TYPE_SIMPLE:
161
-                $column_parts = $selects;
162
-                $this->column_aliases_in_select = $selects;
163
-                break;
164
-            case self::TYPE_COMPLEX:
165
-                foreach ($selects as $alias => $parts) {
166
-                    $this->validateSelectValueForType($parts, $alias);
167
-                    $column_parts[] = "{$parts[0]} AS {$alias}";
168
-                    $this->column_aliases_in_select[] = $alias;
169
-                }
170
-                break;
171
-            case self::TYPE_STRUCTURED:
172
-                foreach ($selects as $alias => $parts) {
173
-                    $this->validateSelectValueForType($parts, $alias);
174
-                    $column_parts[] = $parts[1] !== ''
175
-                        ? $this->assembleSelectStringWithOperator($parts, $alias)
176
-                        : "{$parts[0]} AS {$alias}";
177
-                    $this->column_aliases_in_select[] = $alias;
178
-                }
179
-                break;
180
-        }
181
-        $this->columns_to_select_expression = implode(', ', $column_parts);
182
-    }
183
-
184
-
185
-    /**
186
-     * Validates self::TYPE_COMPLEX and self::TYPE_STRUCTURED select statement parts.
187
-     *
188
-     * @param array  $select_parts
189
-     * @param string $alias
190
-     * @throws InvalidArgumentException
191
-     */
192
-    private function validateSelectValueForType(array $select_parts, $alias)
193
-    {
194
-        $valid_data_types = array('%d', '%s', '%f');
195
-        if (count($select_parts) !== $this->expectedSelectPartCountForType()) {
196
-            throw new InvalidArgumentException(
197
-                sprintf(
198
-                    esc_html__(
199
-                        'The provided select part array for the %1$s column is expected to have a count of %2$d because the incoming select array is of type %3$s.  However the count was %4$d.',
200
-                        'event_espresso'
201
-                    ),
202
-                    $alias,
203
-                    $this->expectedSelectPartCountForType(),
204
-                    $this->type,
205
-                    count($select_parts)
206
-                )
207
-            );
208
-        }
209
-        // validate data type.
210
-        $data_type = $this->type === self::TYPE_COMPLEX ? $select_parts[1] : '';
211
-        $data_type = $this->type === self::TYPE_STRUCTURED ? $select_parts[2] : $data_type;
212
-
213
-        if (! in_array($data_type, $valid_data_types, true)) {
214
-            throw new InvalidArgumentException(
215
-                sprintf(
216
-                    esc_html__(
217
-                        'Datatype %1$s (for selection "%2$s" and alias "%3$s") is not a valid wpdb datatype (eg %%s)',
218
-                        'event_espresso'
219
-                    ),
220
-                    $data_type,
221
-                    $select_parts[0],
222
-                    $alias,
223
-                    implode(', ', $valid_data_types)
224
-                )
225
-            );
226
-        }
227
-    }
228
-
229
-
230
-    /**
231
-     * Each type will have an expected count of array elements, this returns what that expected count is.
232
-     *
233
-     * @param string $type
234
-     * @return int
235
-     */
236
-    private function expectedSelectPartCountForType($type = '')
237
-    {
238
-        $type = $type === '' ? $this->type : $type;
239
-        $types_count_map = array(
240
-            self::TYPE_COMPLEX    => 2,
241
-            self::TYPE_STRUCTURED => 3,
242
-        );
243
-        return isset($types_count_map[ $type ]) ? $types_count_map[ $type ] : 0;
244
-    }
245
-
246
-
247
-    /**
248
-     * Prepares the select statement part for for structured type selects.
249
-     *
250
-     * @param array  $select_parts
251
-     * @param string $alias
252
-     * @return string
253
-     * @throws InvalidArgumentException
254
-     */
255
-    private function assembleSelectStringWithOperator(array $select_parts, $alias)
256
-    {
257
-        $operator = strtoupper($select_parts[1]);
258
-        // validate operator
259
-        if (! in_array($operator, $this->valid_operators, true)) {
260
-            throw new InvalidArgumentException(
261
-                sprintf(
262
-                    esc_html__(
263
-                        'An invalid operator has been provided (%1$s) for the column %2$s.  Valid operators must be one of the following: %3$s.',
264
-                        'event_espresso'
265
-                    ),
266
-                    $operator,
267
-                    $alias,
268
-                    implode(', ', $this->valid_operators)
269
-                )
270
-            );
271
-        }
272
-        return $operator . '(' . $select_parts[0] . ') AS ' . $alias;
273
-    }
274
-
275
-
276
-    /**
277
-     * Return the datatype from the given select part.
278
-     * Remember the select_part has already been validated on object instantiation.
279
-     *
280
-     * @param array $select_part
281
-     * @return string
282
-     */
283
-    private function getDataTypeForSelectType(array $select_part)
284
-    {
285
-        switch ($this->type) {
286
-            case self::TYPE_COMPLEX:
287
-                return $select_part[1];
288
-            case self::TYPE_STRUCTURED:
289
-                return $select_part[2];
290
-            default:
291
-                return '';
292
-        }
293
-    }
294
-
295
-
296
-    /**
297
-     * Returns the original select array sent into the VO.
298
-     *
299
-     * @return array
300
-     */
301
-    public function originalSelects()
302
-    {
303
-        return $this->original_selects;
304
-    }
305
-
306
-
307
-    /**
308
-     * Returns the final assembled select expression derived from the incoming select array.
309
-     *
310
-     * @return string
311
-     */
312
-    public function columnsToSelectExpression()
313
-    {
314
-        return $this->columns_to_select_expression;
315
-    }
316
-
317
-
318
-    /**
319
-     * Returns all the column aliases derived from the incoming select array.
320
-     *
321
-     * @return array
322
-     */
323
-    public function columnAliases()
324
-    {
325
-        return $this->column_aliases_in_select;
326
-    }
327
-
328
-
329
-    /**
330
-     * Returns the enum type for the incoming select array.
331
-     *
332
-     * @return string
333
-     */
334
-    public function type()
335
-    {
336
-        return $this->type;
337
-    }
338
-
339
-
340
-    /**
341
-     * Return the datatype for the given column_alias
342
-     *
343
-     * @param string $column_alias
344
-     * @return string  (if there's no data type we return string as the default).
345
-     */
346
-    public function getDataTypeForAlias($column_alias)
347
-    {
348
-        if (isset($this->original_selects[ $column_alias ])
349
-            && in_array($column_alias, $this->columnAliases(), true)
350
-        ) {
351
-            return $this->getDataTypeForSelectType($this->original_selects[ $column_alias ]);
352
-        }
353
-        return '%s';
354
-    }
20
+	const TYPE_SIMPLE = 'simple';
21
+	const TYPE_COMPLEX = 'complex';
22
+	const TYPE_STRUCTURED = 'structured';
23
+
24
+	private $valid_operators = array('COUNT', 'SUM');
25
+
26
+
27
+	/**
28
+	 * Original incoming select array
29
+	 *
30
+	 * @var array
31
+	 */
32
+	private $original_selects;
33
+
34
+	/**
35
+	 * Select string that can be added to the query
36
+	 *
37
+	 * @var string
38
+	 */
39
+	private $columns_to_select_expression;
40
+
41
+
42
+	/**
43
+	 * An array of aliases for the columns included in the incoming select array.
44
+	 *
45
+	 * @var array
46
+	 */
47
+	private $column_aliases_in_select;
48
+
49
+
50
+	/**
51
+	 * Enum representation of the "type" of array coming into this value object.
52
+	 *
53
+	 * @var string
54
+	 */
55
+	private $type = '';
56
+
57
+
58
+	/**
59
+	 * CustomSelects constructor.
60
+	 * Incoming selects can be in one of the following formats:
61
+	 * ---- self::TYPE_SIMPLE array ----
62
+	 * This is considered the "simple" type. In this case the array is an numerically indexed array with single or
63
+	 * multiple columns to select as the values.
64
+	 * eg. array( 'ATT_ID', 'REG_ID' )
65
+	 * eg. array( '*' )
66
+	 * If you want to use the columns in any WHERE, GROUP BY, or HAVING clauses, you must instead use the "complex" or
67
+	 * "structured" method.
68
+	 * ---- self::TYPE_COMPLEX array ----
69
+	 * This is considered the "complex" type.  In this case the array is indexed by arbitrary strings that serve as
70
+	 * column alias, and the value is an numerically indexed array where there are two values.  The first value (0) is
71
+	 * the selection and the second value (1) is the data type.  Data types must be one of the types defined in
72
+	 * EEM_Base::$_valid_wpdb_data_types.
73
+	 * eg. array( 'count' => array('count(REG_ID)', '%d') )
74
+	 * Complex array configuration allows for using the column alias in any WHERE, GROUP BY, or HAVING clauses.
75
+	 * ---- self::TYPE_STRUCTURED array ---
76
+	 * This is considered the "structured" type. This type is similar to the complex type except that the array attached
77
+	 * to the column alias contains three values.  The first value is the qualified column name (which can include
78
+	 * join syntax for models).  The second value is the operator performed on the column (i.e. 'COUNT', 'SUM' etc).,
79
+	 * the third value is the data type.  Note, if the select does not have an operator, you can use an empty string for
80
+	 * the second value.
81
+	 * Note: for now SUM is only for simple single column expressions (i.e. SUM(Transaction.TXN_total))
82
+	 * eg. array( 'registration_count' => array('Registration.REG_ID', 'count', '%d') );
83
+	 * NOTE: mixing array types in the incoming $select will cause errors.
84
+	 *
85
+	 * @param array $selects
86
+	 * @throws InvalidArgumentException
87
+	 */
88
+	public function __construct(array $selects)
89
+	{
90
+		$this->original_selects = $selects;
91
+		$this->deriveType($selects);
92
+		$this->deriveParts($selects);
93
+	}
94
+
95
+
96
+	/**
97
+	 * Derives what type of custom select has been sent in.
98
+	 *
99
+	 * @param array $selects
100
+	 * @throws InvalidArgumentException
101
+	 */
102
+	private function deriveType(array $selects)
103
+	{
104
+		// first if the first key for this array is an integer then its coming in as a simple format, so we'll also
105
+		// ensure all elements of the array are simple.
106
+		if (is_int(key($selects))) {
107
+			// let's ensure all keys are ints
108
+			$invalid_keys = array_filter(
109
+				array_keys($selects),
110
+				function ($value) {
111
+					return ! is_int($value);
112
+				}
113
+			);
114
+			if (! empty($invalid_keys)) {
115
+				throw new InvalidArgumentException(
116
+					sprintf(
117
+						esc_html__(
118
+							'Incoming array looks like its formatted for "%1$s" type selects, however it has elements that are not indexed numerically',
119
+							'event_espresso'
120
+						),
121
+						self::TYPE_SIMPLE
122
+					)
123
+				);
124
+			}
125
+			$this->type = self::TYPE_SIMPLE;
126
+			return;
127
+		}
128
+		// made it here so that means we've got either complex or structured selects.  Let's find out which by popping
129
+		// the first array element off.
130
+		$first_element = reset($selects);
131
+
132
+		if (! is_array($first_element)) {
133
+			throw new InvalidArgumentException(
134
+				sprintf(
135
+					esc_html__(
136
+						'Incoming array looks like its formatted as a "%1$s" or "%2$s" type.  However, the values in the array must be arrays themselves and they are not.',
137
+						'event_espresso'
138
+					),
139
+					self::TYPE_COMPLEX,
140
+					self::TYPE_STRUCTURED
141
+				)
142
+			);
143
+		}
144
+		$this->type = count($first_element) === 2
145
+			? self::TYPE_COMPLEX
146
+			: self::TYPE_STRUCTURED;
147
+	}
148
+
149
+
150
+	/**
151
+	 * Sets up the various properties for the vo depending on type.
152
+	 *
153
+	 * @param array $selects
154
+	 * @throws InvalidArgumentException
155
+	 */
156
+	private function deriveParts(array $selects)
157
+	{
158
+		$column_parts = array();
159
+		switch ($this->type) {
160
+			case self::TYPE_SIMPLE:
161
+				$column_parts = $selects;
162
+				$this->column_aliases_in_select = $selects;
163
+				break;
164
+			case self::TYPE_COMPLEX:
165
+				foreach ($selects as $alias => $parts) {
166
+					$this->validateSelectValueForType($parts, $alias);
167
+					$column_parts[] = "{$parts[0]} AS {$alias}";
168
+					$this->column_aliases_in_select[] = $alias;
169
+				}
170
+				break;
171
+			case self::TYPE_STRUCTURED:
172
+				foreach ($selects as $alias => $parts) {
173
+					$this->validateSelectValueForType($parts, $alias);
174
+					$column_parts[] = $parts[1] !== ''
175
+						? $this->assembleSelectStringWithOperator($parts, $alias)
176
+						: "{$parts[0]} AS {$alias}";
177
+					$this->column_aliases_in_select[] = $alias;
178
+				}
179
+				break;
180
+		}
181
+		$this->columns_to_select_expression = implode(', ', $column_parts);
182
+	}
183
+
184
+
185
+	/**
186
+	 * Validates self::TYPE_COMPLEX and self::TYPE_STRUCTURED select statement parts.
187
+	 *
188
+	 * @param array  $select_parts
189
+	 * @param string $alias
190
+	 * @throws InvalidArgumentException
191
+	 */
192
+	private function validateSelectValueForType(array $select_parts, $alias)
193
+	{
194
+		$valid_data_types = array('%d', '%s', '%f');
195
+		if (count($select_parts) !== $this->expectedSelectPartCountForType()) {
196
+			throw new InvalidArgumentException(
197
+				sprintf(
198
+					esc_html__(
199
+						'The provided select part array for the %1$s column is expected to have a count of %2$d because the incoming select array is of type %3$s.  However the count was %4$d.',
200
+						'event_espresso'
201
+					),
202
+					$alias,
203
+					$this->expectedSelectPartCountForType(),
204
+					$this->type,
205
+					count($select_parts)
206
+				)
207
+			);
208
+		}
209
+		// validate data type.
210
+		$data_type = $this->type === self::TYPE_COMPLEX ? $select_parts[1] : '';
211
+		$data_type = $this->type === self::TYPE_STRUCTURED ? $select_parts[2] : $data_type;
212
+
213
+		if (! in_array($data_type, $valid_data_types, true)) {
214
+			throw new InvalidArgumentException(
215
+				sprintf(
216
+					esc_html__(
217
+						'Datatype %1$s (for selection "%2$s" and alias "%3$s") is not a valid wpdb datatype (eg %%s)',
218
+						'event_espresso'
219
+					),
220
+					$data_type,
221
+					$select_parts[0],
222
+					$alias,
223
+					implode(', ', $valid_data_types)
224
+				)
225
+			);
226
+		}
227
+	}
228
+
229
+
230
+	/**
231
+	 * Each type will have an expected count of array elements, this returns what that expected count is.
232
+	 *
233
+	 * @param string $type
234
+	 * @return int
235
+	 */
236
+	private function expectedSelectPartCountForType($type = '')
237
+	{
238
+		$type = $type === '' ? $this->type : $type;
239
+		$types_count_map = array(
240
+			self::TYPE_COMPLEX    => 2,
241
+			self::TYPE_STRUCTURED => 3,
242
+		);
243
+		return isset($types_count_map[ $type ]) ? $types_count_map[ $type ] : 0;
244
+	}
245
+
246
+
247
+	/**
248
+	 * Prepares the select statement part for for structured type selects.
249
+	 *
250
+	 * @param array  $select_parts
251
+	 * @param string $alias
252
+	 * @return string
253
+	 * @throws InvalidArgumentException
254
+	 */
255
+	private function assembleSelectStringWithOperator(array $select_parts, $alias)
256
+	{
257
+		$operator = strtoupper($select_parts[1]);
258
+		// validate operator
259
+		if (! in_array($operator, $this->valid_operators, true)) {
260
+			throw new InvalidArgumentException(
261
+				sprintf(
262
+					esc_html__(
263
+						'An invalid operator has been provided (%1$s) for the column %2$s.  Valid operators must be one of the following: %3$s.',
264
+						'event_espresso'
265
+					),
266
+					$operator,
267
+					$alias,
268
+					implode(', ', $this->valid_operators)
269
+				)
270
+			);
271
+		}
272
+		return $operator . '(' . $select_parts[0] . ') AS ' . $alias;
273
+	}
274
+
275
+
276
+	/**
277
+	 * Return the datatype from the given select part.
278
+	 * Remember the select_part has already been validated on object instantiation.
279
+	 *
280
+	 * @param array $select_part
281
+	 * @return string
282
+	 */
283
+	private function getDataTypeForSelectType(array $select_part)
284
+	{
285
+		switch ($this->type) {
286
+			case self::TYPE_COMPLEX:
287
+				return $select_part[1];
288
+			case self::TYPE_STRUCTURED:
289
+				return $select_part[2];
290
+			default:
291
+				return '';
292
+		}
293
+	}
294
+
295
+
296
+	/**
297
+	 * Returns the original select array sent into the VO.
298
+	 *
299
+	 * @return array
300
+	 */
301
+	public function originalSelects()
302
+	{
303
+		return $this->original_selects;
304
+	}
305
+
306
+
307
+	/**
308
+	 * Returns the final assembled select expression derived from the incoming select array.
309
+	 *
310
+	 * @return string
311
+	 */
312
+	public function columnsToSelectExpression()
313
+	{
314
+		return $this->columns_to_select_expression;
315
+	}
316
+
317
+
318
+	/**
319
+	 * Returns all the column aliases derived from the incoming select array.
320
+	 *
321
+	 * @return array
322
+	 */
323
+	public function columnAliases()
324
+	{
325
+		return $this->column_aliases_in_select;
326
+	}
327
+
328
+
329
+	/**
330
+	 * Returns the enum type for the incoming select array.
331
+	 *
332
+	 * @return string
333
+	 */
334
+	public function type()
335
+	{
336
+		return $this->type;
337
+	}
338
+
339
+
340
+	/**
341
+	 * Return the datatype for the given column_alias
342
+	 *
343
+	 * @param string $column_alias
344
+	 * @return string  (if there's no data type we return string as the default).
345
+	 */
346
+	public function getDataTypeForAlias($column_alias)
347
+	{
348
+		if (isset($this->original_selects[ $column_alias ])
349
+			&& in_array($column_alias, $this->columnAliases(), true)
350
+		) {
351
+			return $this->getDataTypeForSelectType($this->original_selects[ $column_alias ]);
352
+		}
353
+		return '%s';
354
+	}
355 355
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -107,11 +107,11 @@  discard block
 block discarded – undo
107 107
             // let's ensure all keys are ints
108 108
             $invalid_keys = array_filter(
109 109
                 array_keys($selects),
110
-                function ($value) {
110
+                function($value) {
111 111
                     return ! is_int($value);
112 112
                 }
113 113
             );
114
-            if (! empty($invalid_keys)) {
114
+            if ( ! empty($invalid_keys)) {
115 115
                 throw new InvalidArgumentException(
116 116
                     sprintf(
117 117
                         esc_html__(
@@ -129,7 +129,7 @@  discard block
 block discarded – undo
129 129
         // the first array element off.
130 130
         $first_element = reset($selects);
131 131
 
132
-        if (! is_array($first_element)) {
132
+        if ( ! is_array($first_element)) {
133 133
             throw new InvalidArgumentException(
134 134
                 sprintf(
135 135
                     esc_html__(
@@ -210,7 +210,7 @@  discard block
 block discarded – undo
210 210
         $data_type = $this->type === self::TYPE_COMPLEX ? $select_parts[1] : '';
211 211
         $data_type = $this->type === self::TYPE_STRUCTURED ? $select_parts[2] : $data_type;
212 212
 
213
-        if (! in_array($data_type, $valid_data_types, true)) {
213
+        if ( ! in_array($data_type, $valid_data_types, true)) {
214 214
             throw new InvalidArgumentException(
215 215
                 sprintf(
216 216
                     esc_html__(
@@ -240,7 +240,7 @@  discard block
 block discarded – undo
240 240
             self::TYPE_COMPLEX    => 2,
241 241
             self::TYPE_STRUCTURED => 3,
242 242
         );
243
-        return isset($types_count_map[ $type ]) ? $types_count_map[ $type ] : 0;
243
+        return isset($types_count_map[$type]) ? $types_count_map[$type] : 0;
244 244
     }
245 245
 
246 246
 
@@ -256,7 +256,7 @@  discard block
 block discarded – undo
256 256
     {
257 257
         $operator = strtoupper($select_parts[1]);
258 258
         // validate operator
259
-        if (! in_array($operator, $this->valid_operators, true)) {
259
+        if ( ! in_array($operator, $this->valid_operators, true)) {
260 260
             throw new InvalidArgumentException(
261 261
                 sprintf(
262 262
                     esc_html__(
@@ -269,7 +269,7 @@  discard block
 block discarded – undo
269 269
                 )
270 270
             );
271 271
         }
272
-        return $operator . '(' . $select_parts[0] . ') AS ' . $alias;
272
+        return $operator.'('.$select_parts[0].') AS '.$alias;
273 273
     }
274 274
 
275 275
 
@@ -345,10 +345,10 @@  discard block
 block discarded – undo
345 345
      */
346 346
     public function getDataTypeForAlias($column_alias)
347 347
     {
348
-        if (isset($this->original_selects[ $column_alias ])
348
+        if (isset($this->original_selects[$column_alias])
349 349
             && in_array($column_alias, $this->columnAliases(), true)
350 350
         ) {
351
-            return $this->getDataTypeForSelectType($this->original_selects[ $column_alias ]);
351
+            return $this->getDataTypeForSelectType($this->original_selects[$column_alias]);
352 352
         }
353 353
         return '%s';
354 354
     }
Please login to merge, or discard this patch.
core/services/loaders/Loader.php 1 patch
Indentation   +111 added lines, -111 removed lines patch added patch discarded remove patch
@@ -15,115 +15,115 @@
 block discarded – undo
15 15
 class Loader implements LoaderInterface
16 16
 {
17 17
 
18
-    /**
19
-     * @var LoaderDecoratorInterface $new_loader
20
-     */
21
-    private $new_loader;
22
-
23
-    /**
24
-     * @var LoaderDecoratorInterface $shared_loader
25
-     */
26
-    private $shared_loader;
27
-
28
-    /**
29
-     * @var ClassInterfaceCache $class_cache
30
-     */
31
-    private $class_cache;
32
-
33
-    /**
34
-     * Loader constructor.
35
-     *
36
-     * @param LoaderDecoratorInterface        $new_loader
37
-     * @param CachingLoaderDecoratorInterface $shared_loader
38
-     * @param ClassInterfaceCache             $class_cache
39
-     */
40
-    public function __construct(
41
-        LoaderDecoratorInterface $new_loader,
42
-        CachingLoaderDecoratorInterface $shared_loader,
43
-        ClassInterfaceCache $class_cache
44
-    ) {
45
-        $this->new_loader    = $new_loader;
46
-        $this->shared_loader = $shared_loader;
47
-        $this->class_cache   = $class_cache;
48
-    }
49
-
50
-
51
-    /**
52
-     * @return LoaderDecoratorInterface
53
-     */
54
-    public function getNewLoader()
55
-    {
56
-        return $this->new_loader;
57
-    }
58
-
59
-
60
-    /**
61
-     * @return CachingLoaderDecoratorInterface
62
-     */
63
-    public function getSharedLoader()
64
-    {
65
-        return $this->shared_loader;
66
-    }
67
-
68
-
69
-    /**
70
-     * @param FullyQualifiedName|string $fqcn
71
-     * @param array                     $arguments
72
-     * @param bool                      $shared
73
-     * @return mixed
74
-     */
75
-    public function load($fqcn, array $arguments = array(), $shared = true)
76
-    {
77
-        $fqcn = $this->class_cache->getFqn($fqcn);
78
-        if ($this->class_cache->hasInterface($fqcn, 'EventEspresso\core\interfaces\ReservedInstanceInterface')) {
79
-            $shared = true;
80
-        }
81
-        return $shared
82
-            ? $this->getSharedLoader()->load($fqcn, $arguments, $shared)
83
-            : $this->getNewLoader()->load($fqcn, $arguments, $shared);
84
-    }
85
-
86
-
87
-    /**
88
-     * @param FullyQualifiedName|string $fqcn
89
-     * @param array                     $arguments
90
-     * @return mixed
91
-     */
92
-    public function getNew($fqcn, array $arguments = array())
93
-    {
94
-        return $this->load($fqcn, $arguments, false);
95
-    }
96
-
97
-
98
-    /**
99
-     * @param FullyQualifiedName|string $fqcn
100
-     * @param array                     $arguments
101
-     * @return mixed
102
-     */
103
-    public function getShared($fqcn, array $arguments = array())
104
-    {
105
-        return $this->load($fqcn, $arguments);
106
-    }
107
-
108
-
109
-    /**
110
-     * @param FullyQualifiedName|string $fqcn
111
-     * @param mixed                     $object
112
-     * @return bool
113
-     * @throws InvalidArgumentException
114
-     */
115
-    public function share($fqcn, $object)
116
-    {
117
-        $fqcn = $this->class_cache->getFqn($fqcn);
118
-        return $this->getSharedLoader()->share($fqcn, $object);
119
-    }
120
-
121
-
122
-    /**
123
-     * calls reset() on loaders if that method exists
124
-     */
125
-    public function reset()
126
-    {
127
-        $this->shared_loader->reset();
128
-    }
18
+	/**
19
+	 * @var LoaderDecoratorInterface $new_loader
20
+	 */
21
+	private $new_loader;
22
+
23
+	/**
24
+	 * @var LoaderDecoratorInterface $shared_loader
25
+	 */
26
+	private $shared_loader;
27
+
28
+	/**
29
+	 * @var ClassInterfaceCache $class_cache
30
+	 */
31
+	private $class_cache;
32
+
33
+	/**
34
+	 * Loader constructor.
35
+	 *
36
+	 * @param LoaderDecoratorInterface        $new_loader
37
+	 * @param CachingLoaderDecoratorInterface $shared_loader
38
+	 * @param ClassInterfaceCache             $class_cache
39
+	 */
40
+	public function __construct(
41
+		LoaderDecoratorInterface $new_loader,
42
+		CachingLoaderDecoratorInterface $shared_loader,
43
+		ClassInterfaceCache $class_cache
44
+	) {
45
+		$this->new_loader    = $new_loader;
46
+		$this->shared_loader = $shared_loader;
47
+		$this->class_cache   = $class_cache;
48
+	}
49
+
50
+
51
+	/**
52
+	 * @return LoaderDecoratorInterface
53
+	 */
54
+	public function getNewLoader()
55
+	{
56
+		return $this->new_loader;
57
+	}
58
+
59
+
60
+	/**
61
+	 * @return CachingLoaderDecoratorInterface
62
+	 */
63
+	public function getSharedLoader()
64
+	{
65
+		return $this->shared_loader;
66
+	}
67
+
68
+
69
+	/**
70
+	 * @param FullyQualifiedName|string $fqcn
71
+	 * @param array                     $arguments
72
+	 * @param bool                      $shared
73
+	 * @return mixed
74
+	 */
75
+	public function load($fqcn, array $arguments = array(), $shared = true)
76
+	{
77
+		$fqcn = $this->class_cache->getFqn($fqcn);
78
+		if ($this->class_cache->hasInterface($fqcn, 'EventEspresso\core\interfaces\ReservedInstanceInterface')) {
79
+			$shared = true;
80
+		}
81
+		return $shared
82
+			? $this->getSharedLoader()->load($fqcn, $arguments, $shared)
83
+			: $this->getNewLoader()->load($fqcn, $arguments, $shared);
84
+	}
85
+
86
+
87
+	/**
88
+	 * @param FullyQualifiedName|string $fqcn
89
+	 * @param array                     $arguments
90
+	 * @return mixed
91
+	 */
92
+	public function getNew($fqcn, array $arguments = array())
93
+	{
94
+		return $this->load($fqcn, $arguments, false);
95
+	}
96
+
97
+
98
+	/**
99
+	 * @param FullyQualifiedName|string $fqcn
100
+	 * @param array                     $arguments
101
+	 * @return mixed
102
+	 */
103
+	public function getShared($fqcn, array $arguments = array())
104
+	{
105
+		return $this->load($fqcn, $arguments);
106
+	}
107
+
108
+
109
+	/**
110
+	 * @param FullyQualifiedName|string $fqcn
111
+	 * @param mixed                     $object
112
+	 * @return bool
113
+	 * @throws InvalidArgumentException
114
+	 */
115
+	public function share($fqcn, $object)
116
+	{
117
+		$fqcn = $this->class_cache->getFqn($fqcn);
118
+		return $this->getSharedLoader()->share($fqcn, $object);
119
+	}
120
+
121
+
122
+	/**
123
+	 * calls reset() on loaders if that method exists
124
+	 */
125
+	public function reset()
126
+	{
127
+		$this->shared_loader->reset();
128
+	}
129 129
 }
Please login to merge, or discard this patch.