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

DisplayTicketSelector   C

Complexity

Total Complexity 67

Size/Duplication

Total Lines 495
Duplicated Lines 1.21 %

Coupling/Cohesion

Components 1
Dependencies 12

Importance

Changes 0
Metric Value
dl 6
loc 495
rs 5.7097
c 0
b 0
f 0
wmc 67
lcom 1
cbo 12

12 Methods

Rating   Name   Duplication   Size   Complexity  
A setIframe() 0 4 1
A getMaxAttendees() 0 4 1
A setMaxAttendees() 0 4 1
F display() 0 144 26
D formOpen() 0 45 9
C displaySubmitButton() 0 72 13
A displayRegisterNowButton() 0 19 2
B displayViewDetailsButton() 0 39 4
A ticketSelectorEndDiv() 0 4 1
A clearTicketSelector() 0 5 1
A formClose() 0 4 1
C setEvent() 6 26 7

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like DisplayTicketSelector often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use DisplayTicketSelector, and based on these observations, apply Extract Interface, too.

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 DisplayTicketSelector
12
 * Description
13
 *
14
 * @package       Event Espresso
15
 * @subpackage    core
16
 * @author        Brent Christensen
17
 * @since         $VID:$
18
 */
19
class DisplayTicketSelector
20
{
21
22
    /**
23
     * event that ticket selector is being generated for
24
     *
25
     * @access protected
26
     * @var \EE_Event $event
27
     */
28
    protected $event;
29
30
    /**
31
     * Used to flag when the ticket selector is being called from an external iframe.
32
     *
33
     * @var bool $iframe
34
     */
35
    protected $iframe = false;
36
37
    /**
38
     * max attendees that can register for event at one time
39
     *
40
     * @var int $max_attendees
41
     */
42
    private $max_attendees = EE_INF;
43
44
45
46
    /**
47
     * @param boolean $iframe
48
     */
49
    public function setIframe( $iframe = true )
50
    {
51
        $this->iframe = filter_var( $iframe, FILTER_VALIDATE_BOOLEAN );
52
    }
53
54
55
56
    /**
57
     * finds and sets the \EE_Event object for use throughout class
58
     *
59
     * @param    mixed $event
60
     * @return    bool
61
     */
62
    protected function setEvent( $event = null )
63
    {
64
        if ( $event === null ) {
65
            global $post;
66
            $event = $post;
67
        }
68
        if ( $event instanceof \EE_Event ) {
69
            $this->event = $event;
70
        } else if ( $event instanceof \WP_Post ) {
0 ignored issues
show
Bug introduced by
The class WP_Post does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
71
            if ( isset( $event->EE_Event ) && $event->EE_Event instanceof \EE_Event ) {
72
                $this->event = $event->EE_Event;
73
            } else if ( $event->post_type === 'espresso_events' ) {
74
                $event->EE_Event = \EEM_Event::instance()->instantiate_class_from_post_object( $event );
75
                $this->event = $event->EE_Event;
0 ignored issues
show
Documentation Bug introduced by
It seems like $event->EE_Event can also be of type object<EE_Base_Class>. However, the property $event is declared as type object<EE_Event>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
76
            }
77 View Code Duplication
        } else {
78
            $user_msg = __( 'No Event object or an invalid Event object was supplied.', 'event_espresso' );
79
            $dev_msg = $user_msg . __(
80
                    'In order to generate a ticket selector, please ensure you are passing either an EE_Event object or a WP_Post object of the post type "espresso_event" to the EE_Ticket_Selector class constructor.',
81
                    'event_espresso'
82
                );
83
            \EE_Error::add_error( $user_msg . '||' . $dev_msg, __FILE__, __FUNCTION__, __LINE__ );
84
            return false;
85
        }
86
        return true;
87
    }
88
89
90
91
    /**
92
     * @return int
93
     */
94
    public function getMaxAttendees()
95
    {
96
        return $this->max_attendees;
97
    }
98
99
100
101
    /**
102
     * @param int $max_attendees
103
     */
104
    public function setMaxAttendees( $max_attendees )
105
    {
106
        $this->max_attendees = absint( $max_attendees );
107
    }
108
109
110
111
    /**
112
     * creates buttons for selecting number of attendees for an event
113
     *
114
     * @param    \WP_Post|int $event
115
     * @param    bool         $view_details
116
     * @return    string
117
     * @throws \EE_Error
118
     */
119
    public function display( $event = null, $view_details = false )
120
    {
121
        // reset filter for displaying submit button
122
        remove_filter( 'FHEE__EE_Ticket_Selector__display_ticket_selector_submit', '__return_true' );
123
        // poke and prod incoming event till it tells us what it is
124
        if ( ! $this->setEvent( $event ) ) {
125
            return false;
126
        }
127
	    if ( apply_filters( 'FHEE__EED_Events_Archive__event_list_iframe', false ) ) {
128
		    $this->setIframe();
129
	    }
130
	    $event_post = $this->event instanceof \EE_Event ? $this->event->ID() : $event;
131
        // grab event status
132
        $_event_active_status = $this->event->get_active_status();
133
        if (
134
            ! is_admin()
135
            && (
136
                ! $this->event->display_ticket_selector()
137
                || $view_details
138
                || post_password_required( $event_post )
139
                || (
140
                    $_event_active_status !== \EE_Datetime::active
141
                    && $_event_active_status !== \EE_Datetime::upcoming
142
                    && $_event_active_status !== \EE_Datetime::sold_out
143
                    && ! (
144
                        $_event_active_status === \EE_Datetime::inactive
145
                        && is_user_logged_in()
146
                    )
147
                )
148
            )
149
        ) {
150
            return ! is_single() ? $this->displayViewDetailsButton() : '';
151
        }
152
	    $template_args = array();
153
        $template_args[ 'event_status' ] = $_event_active_status;
154
        $template_args[ 'date_format' ] = apply_filters(
155
            'FHEE__EED_Ticket_Selector__display_ticket_selector__date_format',
156
            get_option( 'date_format' )
157
        );
158
        $template_args[ 'time_format' ] = apply_filters(
159
            'FHEE__EED_Ticket_Selector__display_ticket_selector__time_format',
160
            get_option( 'time_format' )
161
        );
162
        $template_args[ 'EVT_ID' ] = $this->event->ID();
163
        $template_args[ 'event' ] = $this->event;
164
        // is the event expired ?
165
        $template_args[ 'event_is_expired' ] = $this->event->is_expired();
166
        if ( $template_args[ 'event_is_expired' ] ) {
167
            return '<div class="ee-event-expired-notice"><span class="important-notice">' . __(
168
                'We\'re sorry, but all tickets sales have ended because the event is expired.',
169
                'event_espresso'
170
            ) . '</span></div>';
171
        }
172
        $ticket_query_args = array(
173
            array( 'Datetime.EVT_ID' => $this->event->ID() ),
174
            'order_by' => array(
175
                'TKT_order'              => 'ASC',
176
                'TKT_required'           => 'DESC',
177
                'TKT_start_date'         => 'ASC',
178
                'TKT_end_date'           => 'ASC',
179
                'Datetime.DTT_EVT_start' => 'DESC',
180
            ),
181
        );
182
        if ( ! \EE_Registry::instance()->CFG->template_settings->EED_Ticket_Selector->show_expired_tickets ) {
183
            //use the correct applicable time query depending on what version of core is being run.
184
            $current_time = method_exists( 'EEM_Datetime', 'current_time_for_query' )
185
                ? time()
186
                : current_time( 'timestamp' );
187
            $ticket_query_args[ 0 ][ 'TKT_end_date' ] = array( '>', $current_time );
188
        }
189
        // get all tickets for this event ordered by the datetime
190
        $template_args[ 'tickets' ] = \EEM_Ticket::instance()->get_all( $ticket_query_args );
191
        if ( count( $template_args[ 'tickets' ] ) < 1 ) {
192
            return '<div class="ee-event-expired-notice"><span class="important-notice">' . __(
193
                'We\'re sorry, but all ticket sales have ended.',
194
                'event_espresso'
195
            ) . '</span></div>';
196
        }
197
        // filter the maximum qty that can appear in the Ticket Selector qty dropdowns
198
        $this->setMaxAttendees(
199
            apply_filters(
200
                'FHEE__EE_Ticket_Selector__display_ticket_selector__max_tickets',
201
                $this->event->additional_limit()
202
            )
203
        );
204
        $template_args[ 'max_atndz' ] = $this->getMaxAttendees();
205
        if ( $template_args[ 'max_atndz' ] < 1 ) {
206
            $sales_closed_msg = __(
207
                'We\'re sorry, but ticket sales have been closed at this time. Please check back again later.',
208
                'event_espresso'
209
            );
210
            if ( current_user_can( 'edit_post', $this->event->ID() ) ) {
211
                $link = get_edit_post_link( $this->event->ID() );
212
                $sales_closed_msg .= sprintf(
213
                    __(
214
                        '%sNote to Event Admin:%sThe "Maximum number of tickets allowed per order for this event" in the Event Registration Options has been set to "0". This effectively turns off ticket sales. %s(click to edit this event)%s',
215
                        'event_espresso'
216
                    ),
217
                    '<div class="ee-attention" style="text-align: left;"><b>',
218
                    '</b><br />',
219
                    $link = '<span class="edit-link"><a class="post-edit-link" href="' . $link . '">',
220
                    '</a></span></div>'
221
                );
222
            }
223
            return '<p><span class="important-notice">' . $sales_closed_msg . '</span></p>';
224
        }
225
        $templates[ 'ticket_selector' ] = TICKET_SELECTOR_TEMPLATES_PATH . 'ticket_selector_chart.template.php';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$templates was never initialized. Although not strictly required by PHP, it is generally a good practice to add $templates = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
226
        $templates[ 'ticket_selector' ] = apply_filters(
227
            'FHEE__EE_Ticket_Selector__display_ticket_selector__template_path',
228
            $templates[ 'ticket_selector' ],
229
            $this->event
230
        );
231
	    // redirecting to another site for registration ??
232
        $external_url = $this->event->external_url() !== null || $this->event->external_url() !== ''
233
            ? $this->event->external_url()
234
            : '';
235
        // if not redirecting to another site for registration
236
        if ( ! $external_url ) {
237
            // then display the ticket selector
238
            $ticket_selector = \EEH_Template::locate_template( $templates[ 'ticket_selector' ], $template_args );
239
        } else {
240
            // if not we still need to trigger the display of the submit button
241
            add_filter( 'FHEE__EE_Ticket_Selector__display_ticket_selector_submit', '__return_true' );
242
            //display notice to admin that registration is external
243
            $ticket_selector = ! is_admin()
244
                ? ''
245
                : __(
246
                    'Registration is at an external URL for this event.',
247
                    'event_espresso'
248
                );
249
        }
250
        $ticket_selector = ! is_admin()
251
            ? $this->formOpen(
252
                $this->event->ID(),
253
                $external_url
254
            ) . $ticket_selector
255
            : $ticket_selector;
256
        // now set up the form (but not for the admin)
257
        // submit button and form close tag
258
        $ticket_selector .= ! is_admin() ? $this->displaySubmitButton() : '';
259
        // set no cache headers and constants
260
        \EE_System::do_not_cache();
261
        return $ticket_selector;
262
    }
263
264
265
266
    /**
267
     * formOpen
268
     *
269
     * @param        int    $ID
270
     * @param        string $external_url
271
     * @return        string
272
     */
273
    public function formOpen( $ID = 0, $external_url = '' )
274
    {
275
        // if redirecting, we don't need any anything else
276
        if ( $external_url ) {
277
            $html = '<form method="GET" action="' . \EEH_URL::refactor_url($external_url) . '"';
278
            // open link in new window ?
279
            $html .= apply_filters(
280
                'FHEE__EventEspresso_modules_ticket_selector_DisplayTicketSelector__formOpen__external_url_target_blank',
281
                false
282
            )
283
                ? ' target="_blank"'
284
                : '';
285
            $html .= '>';
286
            $query_args = \EEH_URL::get_query_string( $external_url );
287
            foreach ( (array)$query_args as $query_arg => $value ) {
288
                $html .= '<input type="hidden" name="' . $query_arg . '" value="' . $value . '">';
289
            }
290
            return $html;
291
        }
292
        // if this is a "Dude Where's my Ticket Selector?" ( DWMTS ) type event( ie: $_max_atndz === 1),
293
        // and its the event list, and there is no submit button, then don't start building a form
294
        // because the "View Details" button will build its own form
295
        if (
296
            $this->getMaxAttendees() === 1
297
            && is_archive()
298
            && ! apply_filters('FHEE__EE_Ticket_Selector__display_ticket_selector_submit', false)
299
        ) {
300
            return '';
301
        }
302
        $checkout_url = \EEH_Event_View::event_link_url( $ID );
303
        if ( ! $checkout_url ) {
304
            \EE_Error::add_error(
305
                __( 'The URL for the Event Details page could not be retrieved.', 'event_espresso' ),
306
                __FILE__,
307
                __FUNCTION__,
308
                __LINE__
309
            );
310
        }
311
        $extra_params = $this->iframe ? ' target="_blank"' : '';
312
        $html = '<form method="POST" action="' . $checkout_url . '"' . $extra_params . '>';
313
        $html .= wp_nonce_field( 'process_ticket_selections', 'process_ticket_selections_nonce_' . $ID, true, false );
314
        $html .= '<input type="hidden" name="ee" value="process_ticket_selections">';
315
        $html = apply_filters( 'FHEE__EE_Ticket_Selector__ticket_selector_form_open__html', $html, $this->event );
316
        return $html;
317
    }
318
319
320
321
    /**
322
     * displaySubmitButton
323
     *
324
     * @access        public
325
     * @return        string
326
     * @throws \EE_Error
327
     */
328
    public function displaySubmitButton()
329
    {
330
        $html = '';
331
        if ( ! is_admin() ) {
332
            // standard TS displayed with submit button, ie: "Register Now"
333
            if ( apply_filters( 'FHEE__EE_Ticket_Selector__display_ticket_selector_submit', false ) ) {
334
                $html .= $this->displayRegisterNowButton();
335
                $html .= empty($external_url)
0 ignored issues
show
Bug introduced by
The variable $external_url seems to never exist, and therefore empty should always return true. 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...
336
                    ? $this->ticketSelectorEndDiv()
337
                    : $this->clearTicketSelector();
338
                $html .= '<br/>' . $this->formClose();
339
            } else if ($this->getMaxAttendees() === 1 ) {
340
                // its a "Dude Where's my Ticket Selector?" (DWMTS) type event (ie: $_max_atndz === 1)
341
                if ( $this->event->is_sold_out() ) {
342
                    // then instead of a View Details or Submit button, just display a "Sold Out" message
343
                    $html .= apply_filters(
344
                        'FHEE__EE_Ticket_Selector__display_ticket_selector_submit__sold_out_msg',
345
                        sprintf(
346
                            __(
347
                                '%1$s"%2$s" is currently sold out.%4$sPlease check back again later, as spots may become available.%3$s',
348
                                'event_espresso'
349
                            ),
350
                            '<p class="no-ticket-selector-msg clear-float">',
351
                            $this->event->name(),
352
                            '</p>',
353
                            '<br />'
354
                        ),
355
                        $this->event
356
                    );
357
                    if (
358
                        apply_filters(
359
                            'FHEE__EE_Ticket_Selector__display_ticket_selector_submit__no_tickets_but_display_register_now_button',
360
                            false,
361
                            $this->event
362
                        )
363
                    ) {
364
                        $html .= $this->displayRegisterNowButton();
365
                    }
366
                    // sold out DWMTS event, no TS, no submit or view details button, but has additional content
367
                    $html .= $this->ticketSelectorEndDiv();
368
                } else if (
369
                    apply_filters( 'FHEE__EE_Ticket_Selector__hide_ticket_selector', false )
370
                    && ! is_single()
371
                ) {
372
                    // this is a "Dude Where's my Ticket Selector?" (DWMTS) type event,
373
                    // but no tickets are available, so display event's "View Details" button.
374
                    // it is being viewed via somewhere other than a single post
375
                    $html .= $this->displayViewDetailsButton(true);
376
                }
377
            } else if ( is_archive() ) {
378
                // event list, no tickets available so display event's "View Details" button
379
                $html .= $this->ticketSelectorEndDiv();
380
                $html .= $this->displayViewDetailsButton();
381
            } else {
382
                if (
383
                    apply_filters(
384
                        'FHEE__EE_Ticket_Selector__display_ticket_selector_submit__no_tickets_but_display_register_now_button',
385
                        false,
386
                        $this->event
387
                    )
388
                ) {
389
                    $html .= $this->displayRegisterNowButton();
390
                }
391
                // no submit or view details button, and no additional content
392
                $html .= $this->ticketSelectorEndDiv();
393
            }
394
            if ( ! $this->iframe && ! is_archive() ) {
395
                $html .= \EEH_Template::powered_by_event_espresso('', '', array('utm_content' => 'ticket_selector'));
396
            }
397
        }
398
        return $html;
399
    }
400
401
402
403
    /**
404
     * @return string
405
     * @throws \EE_Error
406
     */
407
    public function displayRegisterNowButton()
408
    {
409
        $btn_text = apply_filters(
410
            'FHEE__EE_Ticket_Selector__display_ticket_selector_submit__btn_text',
411
            __('Register Now', 'event_espresso'),
412
            $this->event
413
        );
414
        $external_url = $this->event->external_url();
415
        $html = '<input id="ticket-selector-submit-' . $this->event->ID() . '-btn"';
416
        $html .= ' class="ticket-selector-submit-btn ';
417
        $html .= empty($external_url) ? 'ticket-selector-submit-ajax"' : '"';
418
        $html .= ' type="submit" value="' . $btn_text . '" />';
419
        $html .= apply_filters(
420
            'FHEE__EE_Ticket_Selector__after_ticket_selector_submit',
421
            '',
422
            $this->event
423
        );
424
        return $html;
425
    }
426
427
428
429
    /**
430
     * displayViewDetailsButton
431
     *
432
     * @param bool $DWMTS indicates a "Dude Where's my Ticket Selector?" (DWMTS) type event
433
     *                    (ie: $_max_atndz === 1) where there are no available tickets,
434
     *                    either because they are sold out, expired, or not yet on sale.
435
     *                    In this case, we need to close the form BEFORE adding any closing divs
436
     * @return string
437
     * @throws \EE_Error
438
     */
439
    public function displayViewDetailsButton( $DWMTS = false )
440
    {
441
        if ( ! $this->event->get_permalink() ) {
442
            \EE_Error::add_error(
443
                __( 'The URL for the Event Details page could not be retrieved.', 'event_espresso' ),
444
                __FILE__, __FUNCTION__, __LINE__
445
            );
446
        }
447
        $view_details_btn = '<form method="POST" action="'
448
                            . apply_filters(
449
                                'FHEE__EE_Ticket_Selector__display_view_details_btn__btn_url',
450
                                $this->event->get_permalink(),
451
                                $this->event
452
                            )
453
                            . '"';
454
        $view_details_btn .= $this->iframe ? ' target="_blank"' : '';
455
        $view_details_btn .= '>';
456
        $btn_text = apply_filters(
457
            'FHEE__EE_Ticket_Selector__display_view_details_btn__btn_text',
458
            __( 'View Details', 'event_espresso' ),
459
            $this->event
460
        );
461
        $view_details_btn .= '<input id="ticket-selector-submit-'
462
                             . $this->event->ID()
463
                             . '-btn" class="ticket-selector-submit-btn view-details-btn" type="submit" value="'
464
                             . $btn_text
465
                             . '" />';
466
        $view_details_btn .= apply_filters( 'FHEE__EE_Ticket_Selector__after_view_details_btn', '', $this->event );
467
        if ( $DWMTS ) {
468
            $view_details_btn .= $this->formClose();
469
            $view_details_btn .= $this->ticketSelectorEndDiv();
470
            $view_details_btn .= '<br/>';
471
        } else {
472
            $view_details_btn .= $this->clearTicketSelector();
473
            $view_details_btn .= '<br/>';
474
            $view_details_btn .= $this->formClose();
475
        }
476
        return $view_details_btn;
477
    }
478
479
480
481
    /**
482
     * @return string
483
     */
484
    public function ticketSelectorEndDiv()
485
    {
486
        return '<div class="clear"></div></div>';
487
    }
488
489
490
491
    /**
492
     * @return string
493
     */
494
    public function clearTicketSelector()
495
    {
496
        // standard TS displayed, appears after a "Register Now" or "view Details" button
497
        return '<div class="clear"></div>';
498
    }
499
500
501
502
    /**
503
     * @access        public
504
     * @return        string
505
     */
506
    public function formClose()
507
    {
508
        return '</form>';
509
    }
510
511
512
513
}
514
// End of file DisplayTicketSelector.php
515
// Location: /DisplayTicketSelector.php