Completed
Branch BUG-10381-asset-loading (f91422)
by
unknown
170:16 queued 157:41
created

setInitialTicketDatetimeAvailability()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 39
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 20
nc 5
nop 1
dl 0
loc 39
rs 8.439
c 0
b 0
f 0
1
<?php
2
namespace EventEspresso\modules\ticket_selector;
3
4
if ( ! defined( 'EVENT_ESPRESSO_VERSION' ) ) {
5
    exit( 'No direct script access allowed' );
6
}
7
8
9
10
/**
11
 * Class ProcessTicketSelector
12
 * Description
13
 *
14
 * @package       Event Espresso
15
 * @subpackage    core
16
 * @author        Brent Christensen
17
 * @since         4.9.0
18
 */
19
class ProcessTicketSelector
20
{
21
22
    /**
23
     * array of datetimes and the spaces available for them
24
     *
25
     * @access private
26
     * @var array
27
     */
28
    private static $_available_spaces = array();
29
30
31
32
    /**
33
     * cancelTicketSelections
34
     *
35
     * @return        string
36
     */
37
    public function cancelTicketSelections()
38
    {
39
        // check nonce
40
        if ( ! $this->processTicketSelectorNonce('cancel_ticket_selections')) {
41
            return false;
42
        }
43
        \EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
44
        if (\EE_Registry::instance()->REQ->is_set('event_id')) {
45
            wp_safe_redirect(
46
                \EEH_Event_View::event_link_url(
47
                    \EE_Registry::instance()->REQ->get('event_id')
48
                )
49
            );
50
        } else {
51
            wp_safe_redirect(
52
                site_url('/' . \EE_Registry::instance()->CFG->core->event_cpt_slug . '/')
53
            );
54
        }
55
        exit();
56
    }
57
58
59
    /**
60
     * processTicketSelectorNonce
61
     *
62
     * @param  string $nonce_name
63
     * @param string  $id
64
     * @return bool
65
     */
66
    private function processTicketSelectorNonce($nonce_name, $id = '')
67
    {
68
        $nonce_name_with_id = ! empty($id) ? "{$nonce_name}_nonce_{$id}" : "{$nonce_name}_nonce";
69
        if (
70
            ! is_admin()
71
            && (
72
                ! \EE_Registry::instance()->REQ->is_set($nonce_name_with_id)
73
                || ! wp_verify_nonce(
74
                    \EE_Registry::instance()->REQ->get($nonce_name_with_id),
75
                    $nonce_name
76
                )
77
            )
78
        ) {
79
            \EE_Error::add_error(
80
                sprintf(
81
                    __(
82
                        'We\'re sorry but your request failed to pass a security check.%sPlease click the back button on your browser and try again.',
83
                        'event_espresso'
84
                    ),
85
                    '<br/>'
86
                ),
87
                __FILE__,
88
                __FUNCTION__,
89
                __LINE__
90
            );
91
            return false;
92
        }
93
        return true;
94
    }
95
96
97
98
    /**
99
     * process_ticket_selections
100
     *
101
     * @return array|bool
102
     * @throws \EE_Error
103
     */
104
    public function processTicketSelections()
105
    {
106
        do_action( 'EED_Ticket_Selector__process_ticket_selections__before' );
107
        // do we have an event id?
108 View Code Duplication
        if ( ! \EE_Registry::instance()->REQ->is_set( 'tkt-slctr-event-id' ) ) {
109
            // $_POST['tkt-slctr-event-id'] was not set ?!?!?!?
110
            \EE_Error::add_error(
111
                sprintf(
112
                    __(
113
                        'An event id was not provided or was not received.%sPlease click the back button on your browser and try again.',
114
                        'event_espresso'
115
                    ),
116
                    '<br/>'
117
                ),
118
                __FILE__,
119
                __FUNCTION__,
120
                __LINE__
121
            );
122
        }
123
        //if event id is valid
124
        $id = absint( \EE_Registry::instance()->REQ->get( 'tkt-slctr-event-id' ) );
125
        // check nonce
126
        if ( ! $this->processTicketSelectorNonce('process_ticket_selections', $id)) {
127
            return false;
128
        }
129
        //		d( \EE_Registry::instance()->REQ );
130
        self::$_available_spaces = array(
131
            'tickets'   => array(),
132
            'datetimes' => array(),
133
        );
134
        //we should really only have 1 registration in the works now (ie, no MER) so clear any previous items in the cart.
135
        // When MER happens this will probably need to be tweaked, possibly wrapped in a conditional checking for some constant defined in MER etc.
136
        \EE_Registry::instance()->load_core( 'Session' );
137
        // unless otherwise requested, clear the session
138
        if ( apply_filters( 'FHEE__EE_Ticket_Selector__process_ticket_selections__clear_session', true ) ) {
139
            \EE_Registry::instance()->SSN->clear_session( __CLASS__, __FUNCTION__ );
140
        }
141
        //d( \EE_Registry::instance()->SSN );
142
        do_action( 'AHEE_log', __FILE__, __FUNCTION__, '' );
143
        // validate/sanitize data
144
        $valid = $this->validatePostData( $id );
145
        //EEH_Debug_Tools::printr( $_REQUEST, '$_REQUEST', __FILE__, __LINE__ );
146
        //EEH_Debug_Tools::printr( $valid, '$valid', __FILE__, __LINE__ );
147
        //EEH_Debug_Tools::printr( $valid[ 'total_tickets' ], 'total_tickets', __FILE__, __LINE__ );
148
        //EEH_Debug_Tools::printr( $valid[ 'max_atndz' ], 'max_atndz', __FILE__, __LINE__ );
149
        //check total tickets ordered vs max number of attendees that can register
150
        if ( $valid[ 'total_tickets' ] > $valid[ 'max_atndz' ] ) {
151
            // ordering too many tickets !!!
152
            $total_tickets_string = _n(
153
                'You have attempted to purchase %s ticket.',
154
                'You have attempted to purchase %s tickets.',
155
                $valid[ 'total_tickets' ],
156
                'event_espresso'
157
            );
158
            $limit_error_1 = sprintf( $total_tickets_string, $valid[ 'total_tickets' ] );
159
            // dev only message
160
            $max_atndz_string = _n(
161
                'The registration limit for this event is %s ticket per registration, therefore the total number of tickets you may purchase at a time can not exceed %s.',
162
                'The registration limit for this event is %s tickets per registration, therefore the total number of tickets you may purchase at a time can not exceed %s.',
163
                $valid[ 'max_atndz' ],
164
                'event_espresso'
165
            );
166
            $limit_error_2 = sprintf( $max_atndz_string, $valid[ 'max_atndz' ], $valid[ 'max_atndz' ] );
167
            \EE_Error::add_error( $limit_error_1 . '<br/>' . $limit_error_2, __FILE__, __FUNCTION__, __LINE__ );
168
        } else {
169
            // all data appears to be valid
170
            $tckts_slctd = false;
171
            $tickets_added = 0;
172
            $valid = apply_filters('FHEE__EED_Ticket_Selector__process_ticket_selections__valid_post_data', $valid);
173
            if ($valid['total_tickets'] > 0) {
174
                // load cart
175
               \EE_Registry::instance()->load_core( 'Cart' );
176
                // cycle thru the number of data rows sent from the event listing
177
                for ( $x = 0; $x < $valid[ 'rows' ]; $x++ ) {
178
                    // does this row actually contain a ticket quantity?
179
                    if ( isset( $valid['qty'][$x] ) && $valid['qty'][$x] > 0 ) {
180
                        // YES we have a ticket quantity
181
                        $tckts_slctd = true;
182
                        //						d( $valid['ticket_obj'][$x] );
183
                        if ( $valid['ticket_obj'][$x] instanceof \EE_Ticket ) {
184
                            // then add ticket to cart
185
                            $tickets_added += $this->addTicketToCart(
186
                                $valid[ 'ticket_obj' ][ $x ],
187
                                $valid[ 'qty' ][ $x ]
188
                            );
189
                            if ( \EE_Error::has_error() ) {
190
                                break;
191
                            }
192
                        } else {
193
                            // nothing added to cart retrieved
194
                            \EE_Error::add_error(
195
                                sprintf(
196
                                    __(
197
                                        'A valid ticket could not be retrieved for the event.%sPlease click the back button on your browser and try again.',
198
                                        'event_espresso'
199
                                    ),
200
                                    '<br/>'
201
                                ),
202
                                __FILE__, __FUNCTION__, __LINE__
203
                            );
204
                        }
205
                    }
206
                }
207
            }
208
            do_action(
209
                'AHEE__EE_Ticket_Selector__process_ticket_selections__after_tickets_added_to_cart',
210
                \EE_Registry::instance()->CART,
211
                $this
212
            );
213
            //d( \EE_Registry::instance()->CART );
214
            //die(); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< KILL REDIRECT HERE BEFORE CART UPDATE
215
            if (apply_filters('FHEE__EED_Ticket_Selector__process_ticket_selections__tckts_slctd', $tckts_slctd)) {
216
                if (apply_filters('FHEE__EED_Ticket_Selector__process_ticket_selections__success', $tickets_added)) {
217
                    do_action(
218
                        'FHEE__EE_Ticket_Selector__process_ticket_selections__before_redirecting_to_checkout',
219
                        \EE_Registry::instance()->CART,
220
                        $this
221
                    );
222
                    \EE_Registry::instance()->CART->recalculate_all_cart_totals();
223
                    \EE_Registry::instance()->CART->save_cart( false );
224
                    // exit('KILL REDIRECT AFTER CART UPDATE'); // <<<<<<<<  OR HERE TO KILL REDIRECT AFTER CART UPDATE
225
                    // just return TRUE for registrations being made from admin
226
                    if ( is_admin() ) {
227
                        return true;
228
                    }
229
                    \EE_Error::get_notices(false, true);
230
                    wp_safe_redirect(
231
                        apply_filters(
232
                            'FHEE__EE_Ticket_Selector__process_ticket_selections__success_redirect_url',
233
                            \EE_Registry::instance()->CFG->core->reg_page_url()
234
                        )
235
                    );
236
                    exit();
237
                } else {
238
                    if ( ! \EE_Error::has_error() && ! \EE_Error::has_error(true, 'attention')) {
239
                        // nothing added to cart
240
                        \EE_Error::add_attention( __( 'No tickets were added for the event', 'event_espresso' ),
241
                                                  __FILE__, __FUNCTION__, __LINE__ );
242
                    }
243
                }
244
            } else {
245
                // no ticket quantities were selected
246
                \EE_Error::add_error( __( 'You need to select a ticket quantity before you can proceed.',
247
                                          'event_espresso' ), __FILE__, __FUNCTION__, __LINE__ );
248
            }
249
        }
250
        //die(); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< KILL BEFORE REDIRECT
251
        // at this point, just return if registration is being made from admin
252
        if ( is_admin() ) {
253
            return false;
254
        }
255
        if ( $valid[ 'return_url' ] ) {
256
            \EE_Error::get_notices( false, true );
257
            wp_safe_redirect( $valid[ 'return_url' ] );
258
            exit();
259
        } elseif ( isset( $event_to_add[ 'id' ] ) ) {
0 ignored issues
show
Bug introduced by
The variable $event_to_add seems to never exist, and therefore isset should always return false. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
260
            \EE_Error::get_notices( false, true );
261
            wp_safe_redirect( get_permalink( $event_to_add[ 'id' ] ) );
262
            exit();
263
        } else {
264
            echo \EE_Error::get_notices();
265
        }
266
        return false;
267
    }
268
269
270
271
    /**
272
     * validate_post_data
273
     *
274
     * @param int $id
275
     * @return array|FALSE
276
     */
277
    private function validatePostData( $id = 0 )
278
    {
279
        do_action( 'AHEE_log', __FILE__, __FUNCTION__, '' );
280
        if ( ! $id ) {
281
            \EE_Error::add_error(
282
                __( 'The event id provided was not valid.', 'event_espresso' ),
283
                __FILE__,
284
                __FUNCTION__,
285
                __LINE__
286
            );
287
            return false;
288
        }
289
        // start with an empty array()
290
        $valid_data = array();
291
        // grab valid id
292
        $valid_data[ 'id' ] = $id;
293
        // array of other form names
294
        $inputs_to_clean = array(
295
            'event_id'   => 'tkt-slctr-event-id',
296
            'max_atndz'  => 'tkt-slctr-max-atndz-',
297
            'rows'       => 'tkt-slctr-rows-',
298
            'qty'        => 'tkt-slctr-qty-',
299
            'ticket_id'  => 'tkt-slctr-ticket-id-',
300
            'return_url' => 'tkt-slctr-return-url-',
301
        );
302
        // let's track the total number of tickets ordered.'
303
        $valid_data[ 'total_tickets' ] = 0;
304
        // cycle through $inputs_to_clean array
305
        foreach ( $inputs_to_clean as $what => $input_to_clean ) {
306
            // check for POST data
307
            if ( \EE_Registry::instance()->REQ->is_set( $input_to_clean . $id ) ) {
308
                // grab value
309
                $input_value = \EE_Registry::instance()->REQ->get( $input_to_clean . $id );
310
                switch ( $what ) {
311
                    // integers
312
                    case 'event_id':
313
                        $valid_data[ $what ] = absint( $input_value );
314
                        // get event via the event id we put in the form
315
                        $valid_data[ 'event' ] = \EE_Registry::instance()
316
                                                             ->load_model( 'Event' )
317
                                                             ->get_one_by_ID( $valid_data[ 'event_id' ] );
318
                        break;
319
                    case 'rows':
320
                    case 'max_atndz':
321
                        $valid_data[ $what ] = absint( $input_value );
322
                        break;
323
                    // arrays of integers
324
                    case 'qty':
325
                        /** @var array $row_qty */
326
                        $row_qty = $input_value;
327
                        // if qty is coming from a radio button input, then we need to assemble an array of rows
328
                        if ( ! is_array( $row_qty ) ) {
329
                            // get number of rows
330
                            $rows = \EE_Registry::instance()->REQ->is_set( 'tkt-slctr-rows-' . $id )
331
                                ? absint( \EE_Registry::instance()->REQ->get( 'tkt-slctr-rows-' . $id ) )
332
                                : 1;
333
                            // explode ints by the dash
334
                            $row_qty = explode( '-', $row_qty );
335
                            $row = isset( $row_qty[ 0 ] ) ? absint( $row_qty[ 0 ] ) : 1;
336
                            $qty = isset( $row_qty[ 1 ] ) ? absint( $row_qty[ 1 ] ) : 0;
337
                            $row_qty = array( $row => $qty );
338
                            for ( $x = 1; $x <= $rows; $x++ ) {
339
                                if ( ! isset( $row_qty[ $x ] ) ) {
340
                                    $row_qty[ $x ] = 0;
341
                                }
342
                            }
343
                        }
344
                        ksort( $row_qty );
345
                        // cycle thru values
346
                        foreach ( $row_qty as $qty ) {
347
                            $qty = absint( $qty );
348
                            // sanitize as integers
349
                            $valid_data[ $what ][] = $qty;
350
                            $valid_data[ 'total_tickets' ] += $qty;
351
                        }
352
                        break;
353
                    // array of integers
354
                    case 'ticket_id':
355
                        $value_array = array();
356
                        // cycle thru values
357
                        foreach ( (array)$input_value as $key => $value ) {
358
                            // allow only numbers, letters,  spaces, commas and dashes
359
                            $value_array[ $key ] = wp_strip_all_tags( $value );
360
                            // get ticket via the ticket id we put in the form
361
                            $ticket_obj = \EE_Registry::instance()->load_model( 'Ticket' )->get_one_by_ID( $value );
362
                            $valid_data[ 'ticket_obj' ][ $key ] = $ticket_obj;
363
                        }
364
                        $valid_data[ $what ] = $value_array;
365
                        break;
366
                    case 'return_url' :
367
                        // grab and sanitize return-url
368
                        $input_value = esc_url_raw( $input_value );
369
                        // was the request coming from an iframe ? if so, then:
370
                        if ( strpos($input_value, 'event_list=iframe')) {
371
                            // get anchor fragment
372
                            $input_value = explode('#', $input_value);
373
                            $input_value = end($input_value);
374
                            // use event list url instead, but append anchor
375
                            $input_value = \EEH_Event_View::event_archive_url() . '#' . $input_value;
376
                        }
377
                        $valid_data[$what] = $input_value;
378
                        break;
379
                }    // end switch $what
380
            }
381
        }    // end foreach $inputs_to_clean
382
        return $valid_data;
383
    }
384
385
386
387
    /**
388
     * adds a ticket to the cart
389
     *
390
     * @param \EE_Ticket $ticket
391
     * @param int        $qty
392
     * @return TRUE on success, FALSE on fail
393
     * @throws \EE_Error
394
     */
395
    private function addTicketToCart( \EE_Ticket $ticket = null, $qty = 1 )
396
    {
397
        do_action( 'AHEE_log', __FILE__, __FUNCTION__, '' );
398
        // get the number of spaces left for this datetime ticket
399
        $available_spaces = $this->ticketDatetimeAvailability( $ticket );
0 ignored issues
show
Bug introduced by
It seems like $ticket defined by parameter $ticket on line 395 can be null; however, EventEspresso\modules\ti...tDatetimeAvailability() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
400
        // compare available spaces against the number of tickets being purchased
401
        if ( $available_spaces >= $qty ) {
402
            // allow addons to prevent a ticket from being added to cart
403
            if (
404
                ! apply_filters(
405
                    'FHEE__EE_Ticket_Selector___add_ticket_to_cart__allow_add_to_cart',
406
                    true,
407
                    $ticket,
408
                    $qty,
409
                    $available_spaces
410
                )
411
            ) {
412
                return false;
413
            }
414
            $qty = absint(apply_filters('FHEE__EE_Ticket_Selector___add_ticket_to_cart__ticket_qty', $qty, $ticket));
415
            // add event to cart
416
            if ( \EE_Registry::instance()->CART->add_ticket_to_cart( $ticket, $qty ) ) {
0 ignored issues
show
Bug introduced by
It seems like $ticket defined by parameter $ticket on line 395 can be null; however, EE_Cart::add_ticket_to_cart() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
417
                $this->recalculateTicketDatetimeAvailability( $ticket, $qty );
0 ignored issues
show
Bug introduced by
It seems like $ticket defined by parameter $ticket on line 395 can be null; however, EventEspresso\modules\ti...tDatetimeAvailability() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
418
                return true;
419
            }
420
            return false;
421
        }
422
        // tickets can not be purchased but let's find the exact number left
423
        // for the last ticket selected PRIOR to subtracting tickets
424
        $available_spaces = $this->ticketDatetimeAvailability( $ticket, true );
0 ignored issues
show
Bug introduced by
It seems like $ticket defined by parameter $ticket on line 395 can be null; however, EventEspresso\modules\ti...tDatetimeAvailability() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
425
        // greedy greedy greedy eh?
426 View Code Duplication
        if ( $available_spaces > 0 ) {
427
            if (
428
            apply_filters(
429
                'FHEE__EE_Ticket_Selector___add_ticket_to_cart__allow_display_availability_error',
430
                true,
431
                $ticket,
432
                $qty,
433
                $available_spaces
434
            )
435
            ) {
436
                $this->displayAvailabilityError($available_spaces);
437
            }
438
        } else {
439
            \EE_Error::add_error(
440
                __(
441
                    'We\'re sorry, but there are no available spaces left for this event at this particular date and time.',
442
                    'event_espresso'
443
                ),
444
                __FILE__, __FUNCTION__, __LINE__
445
            );
446
        }
447
        return false;
448
    }
449
450
451
452
    /**
453
     * @param int $available_spaces
454
     * @throws \EE_Error
455
     */
456
    private function displayAvailabilityError($available_spaces = 1)
457
    {
458
        // add error messaging - we're using the _n function that will generate
459
        // the appropriate singular or plural message based on the number of $available_spaces
460
        if (\EE_Registry::instance()->CART->all_ticket_quantity_count()) {
461
            $msg = sprintf(
462
                _n(
463
                    'We\'re sorry, but there is only %1$s available space left for this event at this particular date and time. Please select a different number (or different combination) of tickets by cancelling the current selection and choosing again, or proceed to registration.',
464
                    'We\'re sorry, but there are only %1$s available spaces left for this event at this particular date and time. Please select a different number (or different combination) of tickets by cancelling the current selection and choosing again, or proceed to registration.',
465
                    $available_spaces,
466
                    'event_espresso'
467
                ),
468
                $available_spaces,
469
                '<br />'
470
            );
471
        } else {
472
            $msg = sprintf(
473
                _n(
474
                    'We\'re sorry, but there is only %1$s available space left for this event at this particular date and time. Please select a different number (or different combination) of tickets.',
475
                    'We\'re sorry, but there are only %1$s available spaces left for this event at this particular date and time. Please select a different number (or different combination) of tickets.',
476
                    $available_spaces,
477
                    'event_espresso'
478
                ),
479
                $available_spaces,
480
                '<br />'
481
            );
482
        }
483
        \EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
484
    }
485
486
487
488
    /**
489
     * ticketDatetimeAvailability
490
     * creates an array of tickets plus all of the datetimes available to each ticket
491
     * and tracks the spaces remaining for each of those datetimes
492
     *
493
     * @param \EE_Ticket $ticket - selected ticket
494
     * @param bool       $get_original_ticket_spaces
495
     * @return int
496
     * @throws \EE_Error
497
     */
498
    private function ticketDatetimeAvailability( \EE_Ticket $ticket, $get_original_ticket_spaces = false )
499
    {
500
        // if the $_available_spaces array has not been set up yet...
501
        if ( ! isset( self::$_available_spaces[ 'tickets' ][ $ticket->ID() ] ) ) {
502
            $this->setInitialTicketDatetimeAvailability( $ticket );
503
        }
504
        $available_spaces = $ticket->qty() - $ticket->sold();
505
        if ( isset( self::$_available_spaces[ 'tickets' ][ $ticket->ID() ] ) ) {
506
            // loop thru tickets, which will ALSO include individual ticket records AND a total
507
            foreach ( self::$_available_spaces[ 'tickets' ][ $ticket->ID() ] as $DTD_ID => $spaces ) {
508
                // if we want the original datetime availability BEFORE we started subtracting tickets ?
509
                if ( $get_original_ticket_spaces ) {
510
                    // then grab the available spaces from the "tickets" array
511
                    // and compare with the above to get the lowest number
512
                    $available_spaces = min(
513
                        $available_spaces,
514
                        self::$_available_spaces[ 'tickets' ][ $ticket->ID() ][ $DTD_ID ]
515
                    );
516
                } else {
517
                    // we want the updated ticket availability as stored in the "datetimes" array
518
                    $available_spaces = min( $available_spaces, self::$_available_spaces[ 'datetimes' ][ $DTD_ID ] );
519
                }
520
            }
521
        }
522
        return $available_spaces;
523
    }
524
525
526
527
    /**
528
     * @param \EE_Ticket $ticket
529
     * @return void
530
     * @throws \EE_Error
531
     */
532
    private function setInitialTicketDatetimeAvailability( \EE_Ticket $ticket )
533
    {
534
        // first, get all of the datetimes that are available to this ticket
535
        $datetimes = $ticket->get_many_related(
536
            'Datetime',
537
            array(
538
                array(
539
                    'DTT_EVT_end' => array(
540
                        '>=',
541
                        \EEM_Datetime::instance()->current_time_for_query( 'DTT_EVT_end' ),
542
                    ),
543
                ),
544
                'order_by' => array( 'DTT_EVT_start' => 'ASC' ),
545
            )
546
        );
547
        if ( ! empty( $datetimes ) ) {
548
            // now loop thru all of the datetimes
549
            foreach ( $datetimes as $datetime ) {
550
                if ( $datetime instanceof \EE_Datetime ) {
551
                    // the number of spaces available for the datetime without considering individual ticket quantities
552
                    $spaces_remaining = $datetime->spaces_remaining();
553
                    // save the total available spaces ( the lesser of the ticket qty minus the number of tickets sold
554
                    // or the datetime spaces remaining) to this ticket using the datetime ID as the key
555
                    self::$_available_spaces[ 'tickets' ][ $ticket->ID() ][ $datetime->ID() ] = min(
556
                        $ticket->qty() - $ticket->sold(),
557
                        $spaces_remaining
558
                    );
559
                    // if the remaining spaces for this datetime is already set,
560
                    // then compare that against the datetime spaces remaining, and take the lowest number,
561
                    // else just take the datetime spaces remaining, and assign to the datetimes array
562
                    self::$_available_spaces[ 'datetimes' ][ $datetime->ID() ] = isset(
563
                        self::$_available_spaces[ 'datetimes' ][ $datetime->ID() ]
564
                    )
565
                        ? min( self::$_available_spaces[ 'datetimes' ][ $datetime->ID() ], $spaces_remaining )
566
                        : $spaces_remaining;
567
                }
568
            }
569
        }
570
    }
571
572
573
574
    /**
575
     * @param    \EE_Ticket $ticket
576
     * @param    int        $qty
577
     * @return    void
578
     */
579
    private function recalculateTicketDatetimeAvailability( \EE_Ticket $ticket, $qty = 0 )
580
    {
581
        if ( isset( self::$_available_spaces[ 'tickets' ][ $ticket->ID() ] ) ) {
582
            // loop thru tickets, which will ALSO include individual ticket records AND a total
583
            foreach ( self::$_available_spaces[ 'tickets' ][ $ticket->ID() ] as $DTD_ID => $spaces ) {
584
                // subtract the qty of selected tickets from each datetime's available spaces this ticket has access to,
585
                self::$_available_spaces[ 'datetimes' ][ $DTD_ID ] -= $qty;
586
            }
587
        }
588
    }
589
590
591
}
592
// End of file ProcessTicketSelector.php
593
// Location: /ProcessTicketSelector.php