Completed
Branch Gutenberg/event-attendees-bloc... (e27df5)
by
unknown
42:51 queued 28:10
created

EspressoEventAttendees::validateEntities()   B

Complexity

Conditions 9
Paths 2

Size

Total Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
nc 2
nop 1
dl 0
loc 25
rs 8.0555
c 0
b 0
f 0
1
<?php
2
3
namespace EventEspresso\core\domain\entities\shortcodes;
4
5
use EE_Datetime;
6
use EE_Error;
7
use EE_Event;
8
use EE_Ticket;
9
use EEH_Event_View;
10
use EEH_Template;
11
use EEM_Attendee;
12
use EEM_Datetime;
13
use EEM_Event;
14
use EEM_Registration;
15
use EEM_Ticket;
16
use EventEspresso\core\exceptions\EntityNotFoundException;
17
use EventEspresso\core\services\shortcodes\EspressoShortcode;
18
19
/**
20
 * Class EspressoEventAttendees
21
 * ESPRESSO_EVENT_ATTENDEES shortcode
22
 *
23
 * @package Event Espresso
24
 * @author  Darren Ethier
25
 * @since   4.9.26
26
 */
27
class EspressoEventAttendees extends EspressoShortcode
28
{
29
30
    private $query_params = array(
31
        0 => array(),
32
    );
33
34
    private $template_args = array(
35
        'contacts' => array(),
36
        'event'    => null,
37
        'datetime' => null,
38
        'ticket'   => null,
39
    );
40
41
    /**
42
     * the actual shortcode tag that gets registered with WordPress
43
     *
44
     * @return string
45
     */
46
    public function getTag()
47
    {
48
        return 'ESPRESSO_EVENT_ATTENDEES';
49
    }
50
51
52
    /**
53
     * the time in seconds to cache the results of the processShortcode() method
54
     * 0 means the processShortcode() results will NOT be cached at all
55
     *
56
     * @return int
57
     */
58
    public function cacheExpiration()
59
    {
60
        return 0;
61
    }
62
63
64
    /**
65
     * a place for adding any initialization code that needs to run prior to wp_header().
66
     * this may be required for shortcodes that utilize a corresponding module,
67
     * and need to enqueue assets for that module
68
     *
69
     * @return void
70
     */
71
    public function initializeShortcode()
72
    {
73
        $this->shortcodeHasBeenInitialized();
74
    }
75
76
77
    /**
78
     * process_shortcode - ESPRESSO_EVENT_ATTENDEES - Returns a list of attendees to an event.
79
     *  [ESPRESSO_EVENT_ATTENDEES]
80
     *  - defaults to attendees for earliest active event, or earliest upcoming event.
81
     *  [ESPRESSO_EVENT_ATTENDEES event_id=123]
82
     *  - attendees for specific event.
83
     *  [ESPRESSO_EVENT_ATTENDEES datetime_id=245]
84
     *  - attendees for a specific datetime.
85
     *  [ESPRESSO_EVENT_ATTENDEES ticket_id=123]
86
     *  - attendees for a specific ticket.
87
     *  [ESPRESSO_EVENT_ATTENDEES status=all]
88
     *  - specific registration status (use status id) or all for all attendees regardless of status.
89
     *  Note default is to only return approved attendees
90
     *  [ESPRESSO_EVENT_ATTENDEES show_gravatar=true]
91
     *  - default is to not return gravatar.  Otherwise if this is set then return gravatar for email address given.
92
     *  [ESPRESSO_EVENT_ATTENDEES display_on_archives=true]
93
     *  - default is to not display attendees list on archive pages.
94
     * Note: because of the relationship between event_id, ticket_id, and datetime_id:
95
     * If more than one of those params is included, then preference is given to the following:
96
     *  - event_id is used whenever its present and any others are ignored.
97
     *  - if no event_id then datetime is used whenever its present and any others are ignored.
98
     *  - otherwise ticket_id is used if present.
99
     *
100
     * @param array $attributes
101
     * @return string
102
     * @throws EE_Error
103
     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
104
     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
105
     * @throws \InvalidArgumentException
106
     */
107
    public function processShortcode($attributes = array())
108
    {
109
        // grab attributes and merge with defaults
110
        $attributes = $this->getAttributes((array) $attributes);
111
        $archive = is_archive();
112
        $display_on_archives = filter_var($attributes['display_on_archives'], FILTER_VALIDATE_BOOLEAN);
113
        // don't display on archives unless 'display_on_archives' is true
114
        if ($archive && ! $display_on_archives) {
115
            return '';
116
        }
117
118
        try {
119
            $this->setBaseTemplateArguments($attributes);
120
            $this->validateEntities($attributes);
121
            $this->setBaseQueryParams();
122
        } catch (EntityNotFoundException $e) {
123
            if (WP_DEBUG) {
124
                return '<div class="important-notice ee-error">'
125
                       . $e->getMessage()
126
                       . '</div>';
127
            }
128
            return '';
129
        }
130
        $this->setAdditionalQueryParams($attributes);
131
        // get contacts!
132
        $this->template_args['contacts'] = EEM_Attendee::instance()->get_all($this->query_params);
133
        // all set let's load up the template and return.
134
        return EEH_Template::locate_template(
135
            'loop-espresso_event_attendees.php',
136
            $this->template_args
137
        );
138
    }
139
140
141
    /**
142
     * merge incoming attributes with filtered defaults
143
     *
144
     * @param array $attributes
145
     * @return array
146
     */
147
    private function getAttributes(array $attributes)
148
    {
149
        return (array) apply_filters(
150
            'EES_Espresso_Event_Attendees__process_shortcode__default_shortcode_atts',
151
            $attributes + array(
152
                'event_id'            => null,
153
                'datetime_id'         => null,
154
                'ticket_id'           => null,
155
                'status'              => EEM_Registration::status_id_approved,
156
                'show_gravatar'       => false,
157
                'display_on_archives' => false,
158
            )
159
        );
160
    }
161
162
163
    /**
164
     * Set all the base template arguments from the incoming attributes.
165
     * * Note: because of the relationship between event_id, ticket_id, and datetime_id:
166
     * If more than one of those params is included, then preference is given to the following:
167
     *  - event_id is used whenever its present and any others are ignored.
168
     *  - if no event_id then datetime is used whenever its present and any others are ignored.
169
     *  - otherwise ticket_id is used if present.
170
     *
171
     * @param array $attributes
172
     * @throws EE_Error
173
     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
174
     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
175
     * @throws \InvalidArgumentException
176
     */
177
    private function setBaseTemplateArguments(array $attributes)
178
    {
179
        $this->template_args['show_gravatar'] = $attributes['show_gravatar'];
180
        $this->template_args['event'] = $this->getEvent($attributes);
181
        $this->template_args['datetime'] = empty($attributes['event_id'])
182
            ? $this->getDatetime($attributes)
183
            : null;
184
        $this->template_args['ticket'] = empty($attributes['datetime_id']) && empty($attributes['event_id'])
185
            ? $this->getTicket($attributes)
186
            : null;
187
    }
188
189
190
    /**
191
     * Validates the presence of entities for the given attribute values.
192
     *
193
     * @param array $attributes
194
     * @throws EntityNotFoundException
195
     */
196
    private function validateEntities(array $attributes)
197
    {
198
        if (! $this->template_args['event'] instanceof EE_Event
199
            || (
200
                empty($attributes['event_id'])
201
                && $attributes['datetime_id']
202
                && ! $this->template_args['datetime'] instanceof EE_Datetime
203
            )
204
            || (
205
                empty($attributes['event_id'])
206
                && empty($attributes['datetime_id'])
207
                && $attributes['ticket_id']
208
                && ! $this->template_args['ticket'] instanceof EE_Ticket
209
            )
210
        ) {
211
            throw new EntityNotFoundException(
212
                '',
213
                '',
214
                esc_html__(
215
                    'The [ESPRESSO_EVENT_ATTENDEES] shortcode has been used incorrectly.  Please double check the arguments you used for any typos.  In the case of ID type arguments, its possible the given ID does not correspond to existing data in the database.',
216
                    'event_espresso'
217
                )
218
            );
219
        }
220
    }
221
222
223
    /**
224
     * Sets the query params for the base query elements.
225
     */
226
    private function setBaseQueryParams()
227
    {
228
        switch (true) {
229
            case $this->template_args['datetime'] instanceof EE_Datetime:
230
                $this->query_params = array(
231
                    0                          => array(
232
                        'Registration.Ticket.Datetime.DTT_ID' => $this->template_args['datetime']->ID(),
233
                    ),
234
                    'default_where_conditions' => 'this_model_only',
235
                );
236
                break;
237
            case $this->template_args['ticket'] instanceof EE_Ticket:
238
                $this->query_params[0] = array(
239
                    'Registration.TKT_ID' => $this->template_args['ticket']->ID(),
240
                );
241
                break;
242
            case $this->template_args['event'] instanceof EE_Event:
243
                $this->query_params[0] = array(
244
                    'Registration.EVT_ID' => $this->template_args['event']->ID(),
245
                );
246
                break;
247
        }
248
    }
249
250
251
    /**
252
     * @param array $attributes
253
     * @return EE_Event|null
254
     * @throws EE_Error
255
     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
256
     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
257
     * @throws \InvalidArgumentException
258
     */
259
    private function getEvent(array $attributes)
260
    {
261
        switch (true) {
262
            case ! empty($attributes['event_id']):
263
                $event = EEM_Event::instance()->get_one_by_ID($attributes['event_id']);
264
                break;
265
            case ! empty($attributes['datetime_id']):
266
                $event = EEM_Event::instance()->get_one(array(
267
                    array(
268
                        'Datetime.DTT_ID' => $attributes['datetime_id'],
269
                    ),
270
                ));
271
                break;
272
            case ! empty($attributes['ticket_id']):
273
                $event = EEM_Event::instance()->get_one(array(
274
                    array(
275
                        'Datetime.Ticket.TKT_ID' => $attributes['ticket_id'],
276
                    ),
277
                ));
278
                break;
279
            case is_espresso_event():
280
                $event = EEH_Event_View::get_event();
281
                break;
282
            default:
283
                // one last shot...
284
                // try getting the earliest active event
285
                $events = EEM_Event::instance()->get_active_events(array(
286
                    'limit'    => 1,
287
                    'order_by' => array('Datetime.DTT_EVT_start' => 'ASC'),
288
                ));
289
                //  if none then get the next upcoming
290
                $events = empty($events)
291
                    ? EEM_Event::instance()->get_upcoming_events(array(
292
                        'limit'    => 1,
293
                        'order_by' => array('Datetime.DTT_EVT_start' => 'ASC'),
294
                    ))
295
                    : $events;
296
                $event = reset($events);
297
        }
298
299
        return $event instanceof EE_Event ? $event : null;
300
    }
301
302
303
    /**
304
     * @param array $attributes
305
     * @return EE_Datetime|null
306
     * @throws EE_Error
307
     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
308
     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
309
     * @throws \InvalidArgumentException
310
     */
311 View Code Duplication
    private function getDatetime(array $attributes)
312
    {
313
        if (! empty($attributes['datetime_id'])) {
314
            $datetime = EEM_Datetime::instance()->get_one_by_ID($attributes['datetime_id']);
315
            if ($datetime instanceof EE_Datetime) {
316
                return $datetime;
317
            }
318
        }
319
        return null;
320
    }
321
322
323
    /**
324
     * @param array $attributes
325
     * @return \EE_Base_Class|EE_Ticket|null
326
     * @throws EE_Error
327
     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
328
     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
329
     * @throws \InvalidArgumentException
330
     */
331 View Code Duplication
    private function getTicket(array $attributes)
332
    {
333
        if (! empty($attributes['ticket_id'])) {
334
            $ticket = EEM_Ticket::instance()->get_one_by_ID($attributes['ticket_id']);
335
            if ($ticket instanceof EE_Ticket) {
336
                return $ticket;
337
            }
338
        }
339
        return null;
340
    }
341
342
343
    /**
344
     * @param array $attributes
345
     * @throws EE_Error
346
     */
347
    private function setAdditionalQueryParams(array $attributes)
348
    {
349
        $reg_status_array = EEM_Registration::reg_status_array();
350
        if ($attributes['status'] !== 'all' && isset($reg_status_array[ $attributes['status'] ])) {
351
            $this->query_params[0]['Registration.STS_ID'] = $attributes['status'];
352
        }
353
        $this->query_params['group_by'] = array('ATT_ID');
354
        $this->query_params['order_by'] = (array) apply_filters(
355
            'FHEE__EES_Espresso_Event_Attendees__process_shortcode__order_by',
356
            array('ATT_lname' => 'ASC', 'ATT_fname' => 'ASC')
357
        );
358
    }
359
}
360