Completed
Branch EDTR/master (6f8f75)
by
unknown
17:58 queued 09:20
created

AdvancedEditorEntityData::getGraphQLCurrentUser()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 29

Duplication

Lines 29
Ratio 100 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 0
dl 29
loc 29
rs 9.456
c 0
b 0
f 0
1
<?php
2
3
namespace EventEspresso\core\domain\services\admin\events\editor;
4
5
use DomainException;
6
use EE_Admin_Config;
7
use EE_Datetime;
8
use EE_Error;
9
use EE_Event;
10
use EEM_Datetime;
11
use EEM_Event;
12
use EEM_Price;
13
use EEM_Price_Type;
14
use EEM_Ticket;
15
use EE_Ticket;
16
use EEM_Venue;
17
use EventEspresso\core\domain\services\assets\EspressoEditorAssetManager;
18
use EventEspresso\core\domain\services\converters\RestApiSpoofer;
19
use EventEspresso\core\exceptions\InvalidDataTypeException;
20
use EventEspresso\core\exceptions\InvalidInterfaceException;
21
use EventEspresso\core\exceptions\ModelConfigurationException;
22
use EventEspresso\core\exceptions\RestPasswordIncorrectException;
23
use EventEspresso\core\exceptions\RestPasswordRequiredException;
24
use EventEspresso\core\exceptions\UnexpectedEntityException;
25
use EventEspresso\core\libraries\rest_api\RestException;
26
use InvalidArgumentException;
27
use ReflectionException;
28
use WP_Post;
29
use WPGraphQL\Router;
30
use GraphQLRelay\Relay;
31
32
/**
33
 * Class AdvancedEditorEntityData
34
 * Description
35
 *
36
 * @package EventEspresso\core\domain\services\admin\events\editor
37
 * @author  Brent Christensen
38
 * @since   $VID:$
39
 */
40
class AdvancedEditorEntityData
41
{
42
43
    /**
44
     * @var string $namespace The graphql namespace/prefix.
45
     */
46
    protected $namespace = 'Espresso';
47
48
    /**
49
     * @var EE_Event
50
     */
51
    protected $event;
52
53
    /**
54
     * @var RestApiSpoofer
55
     */
56
    protected $spoofer;
57
58
    /**
59
     * @var EE_Admin_Config
60
     */
61
    protected $admin_config;
62
63
    /**
64
     * @var EEM_Datetime $datetime_model
65
     */
66
    protected $datetime_model;
67
68
    /**
69
     * @var EEM_Event $event_model
70
     */
71
    protected $event_model;
72
73
    /**
74
     * @var EEM_Price $price_model
75
     */
76
    protected $price_model;
77
78
    /**
79
     * @var EEM_Price_Type $price_type_model
80
     */
81
    protected $price_type_model;
82
83
    /**
84
     * @var EEM_Ticket $ticket_model
85
     */
86
    protected $ticket_model;
87
    /**
88
     * @var EEM_Venue $venue_model
89
     */
90
    protected $venue_model;
91
92
93
    /**
94
     * AdvancedEditorAdminForm constructor.
95
     *
96
     * @param EE_Event        $event
97
     * @param RestApiSpoofer  $spoofer
98
     * @param EE_Admin_Config $admin_config
99
     * @param EEM_Datetime    $datetime_model
100
     * @param EEM_Event       $event_model
101
     * @param EEM_Price       $price_model
102
     * @param EEM_Price_Type  $price_type_model
103
     * @param EEM_Ticket      $ticket_model
104
     * @param EEM_Venue       $venue_model
105
     */
106
    public function __construct(
107
        EE_Event $event,
108
        RestApiSpoofer $spoofer,
109
        EE_Admin_Config $admin_config,
110
        EEM_Datetime $datetime_model,
111
        EEM_Event $event_model,
112
        EEM_Price $price_model,
113
        EEM_Price_Type $price_type_model,
114
        EEM_Ticket $ticket_model,
115
        EEM_Venue $venue_model
116
    ) {
117
        $this->event = $event;
118
        $this->admin_config = $admin_config;
119
        $this->spoofer = $spoofer;
120
        $this->datetime_model = $datetime_model;
121
        $this->event_model = $event_model;
122
        $this->price_model = $price_model;
123
        $this->price_type_model = $price_type_model;
124
        $this->ticket_model = $ticket_model;
125
        $this->venue_model = $venue_model;
126
        add_action('admin_enqueue_scripts', [$this, 'loadScriptsStyles']);
127
    }
128
129
130
    /**
131
     * @throws EE_Error
132
     * @throws InvalidArgumentException
133
     * @throws InvalidDataTypeException
134
     * @throws InvalidInterfaceException
135
     * @throws ModelConfigurationException
136
     * @throws ReflectionException
137
     * @throws RestException
138
     * @throws RestPasswordIncorrectException
139
     * @throws RestPasswordRequiredException
140
     * @throws UnexpectedEntityException
141
     * @throws DomainException
142
     * @since $VID:$
143
     */
144
    public function loadScriptsStyles()
145
    {
146
        if ($this->admin_config->useAdvancedEditor()) {
147
            $eventId = $this->event instanceof EE_Event ? $this->event->ID() : 0;
148
            if (! $eventId) {
149
                global $post;
150
                $eventId = isset($_REQUEST['post']) ? absint($_REQUEST['post']) : 0;
151
                $eventId = $eventId === 0 && $post instanceof WP_Post && $post->post_type === 'espresso_events'
0 ignored issues
show
Bug introduced by
The class WP_Post does not exist. Is this class maybe located in a folder that is not analyzed, or in a newer version of your dependencies than listed in your composer.lock/composer.json?
Loading history...
152
                    ? $post->ID
153
                    : $eventId;
154
            }
155
            $graphqlEndpoint = class_exists('WPGraphQL') ? trailingslashit(site_url()) . Router::$route : '';
156
            $graphqlEndpoint = esc_url($graphqlEndpoint);
157
            if ($eventId) {
158
                $data = $this->getAllEventData($eventId);
159
                $data = wp_json_encode($data);
160
                $GQLdata = $this->getGraphQLData($eventId);
161
                $GQLdata = wp_json_encode($GQLdata);
162
                add_action(
163
                    'admin_footer',
164
                    static function () use ($data, $graphqlEndpoint) {
165
                        wp_add_inline_script(
166
                            EspressoEditorAssetManager::JS_HANDLE_EDITOR,
167
                            "
168
var eeEditorEventData={$data};
169
var graphqlEndpoint='{$graphqlEndpoint}';
170
",
171
                            'before'
172
                        );
173
                    }
174
                );
175
                add_action(
176
                    'admin_footer',
177
                    static function () use ($data, $GQLdata, $graphqlEndpoint) {
178
                        wp_add_inline_script(
179
                            EspressoEditorAssetManager::JS_HANDLE_EDITOR_PROTOTYPE,
180
                            "
181
var eeEditorEventData={$data};
182
var eeEditorGQLData={$GQLdata};
183
var graphqlEndpoint='{$graphqlEndpoint}';
184
",
185
                            'before'
186
                        );
187
                    }
188
                );
189
            }
190
        }
191
    }
192
193
194
    /**
195
     * @param int $eventId
196
     * @return array
197
     * @throws DomainException
198
     * @throws EE_Error
199
     * @throws InvalidArgumentException
200
     * @throws InvalidDataTypeException
201
     * @throws InvalidInterfaceException
202
     * @throws ModelConfigurationException
203
     * @throws ReflectionException
204
     * @throws RestException
205
     * @throws RestPasswordIncorrectException
206
     * @throws RestPasswordRequiredException
207
     * @throws UnexpectedEntityException
208
     * @since $VID:$
209
     */
210
    protected function getEventDates($eventId)
211
    {
212
        return $this->spoofer->getApiResults(
213
            $this->datetime_model,
214
            [
215
                [
216
                    'EVT_ID'      => $eventId,
217
                    'DTT_deleted' => ['IN', [true, false]]
218
                ]
219
            ]
220
        );
221
    }
222
223
224
    /**
225
     * @param int $eventId
226
     * @param array $eventDates
227
     * @throws DomainException
228
     * @throws EE_Error
229
     * @throws InvalidArgumentException
230
     * @throws InvalidDataTypeException
231
     * @throws InvalidInterfaceException
232
     * @throws ModelConfigurationException
233
     * @throws ReflectionException
234
     * @throws RestException
235
     * @throws RestPasswordIncorrectException
236
     * @throws RestPasswordRequiredException
237
     * @throws UnexpectedEntityException
238
     * @since $VID:$
239
     */
240
    protected function addDefaultEntities($eventId, array $eventDates = [])
241
    {
242
        $default_dates = $this->datetime_model->create_new_blank_datetime();
243
        if (is_array($default_dates) && isset($default_dates[0]) && $default_dates[0] instanceof EE_Datetime) {
244
            $default_date = $default_dates[0];
245
            $default_date->save();
246
            $default_date->_add_relation_to($eventId, 'Event');
247
            $default_tickets = $this->ticket_model->get_all_default_tickets();
248
            $default_prices = $this->price_model->get_all_default_prices();
249
            foreach ($default_tickets as $default_ticket) {
250
                $default_ticket->save();
251
                $default_ticket->_add_relation_to($default_date, 'Datetime');
252
                foreach ($default_prices as $default_price) {
0 ignored issues
show
Bug introduced by
The expression $default_prices of type integer|array<integer,object<EE_Base_Class>> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
253
                    $default_price->save();
254
                    $default_price->_add_relation_to($default_ticket, 'Ticket');
255
                }
256
            }
257
        }
258
    }
259
260
261
    /**
262
     * @param int $eventId
263
     * @return array
264
     * @since $VID:$
265
     */
266
    protected function getGraphQLData($eventId)
267
    {
268
        $datetimes = $this->getGraphQLDatetimes($eventId);
269
270
        if (! empty($datetimes['nodes'])) {
271
            $datetimeIn = wp_list_pluck($datetimes['nodes'], 'id');
272
273
            if (! empty($datetimeIn)) {
274
                $tickets = $this->getGraphQLTickets($datetimeIn);
275
            }
276
        }
277
278
        if (! empty($tickets['nodes'])) {
279
            $ticketIn = wp_list_pluck($tickets['nodes'], 'id');
280
281
            if (! empty($ticketIn)) {
282
                $prices = $this->getGraphQLPrices($ticketIn);
283
            }
284
        }
285
286
        $priceTypes = $this->getGraphQLPriceTypes();
287
288
        $currentUser = $this->getGraphQLCurrentUser();
289
290
        $generalSettings = $this->getGraphQLGeneralSettings();
291
292
        $relations = $this->getRelationalData($eventId);
293
294
        return compact('datetimes', 'tickets', 'prices', 'priceTypes', 'currentUser', 'generalSettings', 'relations');
295
    }
296
297
298
    /**
299
     * @param int $eventId
300
     * @return array|null
301
     * @since $VID:$
302
     */
303 View Code Duplication
    protected function getGraphQLDatetimes($eventId)
304
    {
305
        $field_key = lcfirst($this->namespace) . 'Datetimes';
306
        $query = <<<QUERY
307
        query GET_DATETIMES(\$where: {$this->namespace}RootQueryDatetimesConnectionWhereArgs) {
308
            {$field_key}(where: \$where) {
309
                nodes {
310
                    id
311
                    dbId
312
                    name
313
                    description
314
                    startDate
315
                    endDate
316
                    capacity
317
                    isActive
318
                    isExpired
319
                    isPrimary
320
                    isSoldOut
321
                    isUpcoming
322
                    length
323
                    order
324
                    reserved
325
                    sold
326
                    __typename
327
                }
328
                __typename
329
            }
330
        }
331
QUERY;
332
            $data = [
333
                'operation_name' => 'GET_DATETIMES',
334
                'variables' => [
335
                    'first' => 50,
336
                    'where' => [
337
                        'eventId' => $eventId,
338
                    ],
339
                ],
340
                'query' => $query,
341
            ];
342
343
            $responseData = $this->makeGraphQLRequest($data);
344
            return !empty($responseData[ $field_key ]) ? $responseData[ $field_key ] : null;
345
    }
346
347
348
    /**
349
     * @param array $datetimeIn
350
     * @return array|null
351
     * @since $VID:$
352
     */
353 View Code Duplication
    protected function getGraphQLTickets(array $datetimeIn)
354
    {
355
        $field_key = lcfirst($this->namespace) . 'Tickets';
356
        $query = <<<QUERY
357
        query GET_TICKETS(\$where: {$this->namespace}RootQueryTicketsConnectionWhereArgs) {
358
            {$field_key}(where: \$where) {
359
                nodes {
360
                    id
361
                    dbId
362
                    description
363
                    endDate
364
                    isDefault
365
                    isFree
366
                    isRequired
367
                    isTaxable
368
                    max
369
                    min
370
                    name
371
                    order
372
                    price
373
                    quantity
374
                    reserved
375
                    reverseCalculate
376
                    sold
377
                    startDate
378
                    uses
379
                    __typename
380
                }
381
                __typename
382
            }
383
        }
384
QUERY;
385
            $data = [
386
                'operation_name' => 'GET_TICKETS',
387
                'variables' => [
388
                    'where' => [
389
                        'datetimeIn' => $datetimeIn,
390
                    ],
391
                ],
392
                'query' => $query,
393
            ];
394
395
            $responseData = $this->makeGraphQLRequest($data);
396
            return !empty($responseData[ $field_key ]) ? $responseData[ $field_key ] : null;
397
    }
398
399
400
    /**
401
     * @param array $ticketIn
402
     * @return array|null
403
     * @since $VID:$
404
     */
405 View Code Duplication
    protected function getGraphQLPrices(array $ticketIn)
406
    {
407
        $field_key = lcfirst($this->namespace) . 'Prices';
408
        $query = <<<QUERY
409
        query GET_PRICES(\$where: {$this->namespace}RootQueryPricesConnectionWhereArgs) {
410
            {$field_key}(where: \$where) {
411
                nodes {
412
                    id
413
                    dbId
414
                    amount
415
                    desc
416
                    isBasePrice
417
                    isDefault
418
                    isDeleted
419
                    isDiscount
420
                    isPercent
421
                    isTax
422
                    name
423
                    order
424
                    overrides
425
                    priceTypeOrder
426
                    __typename
427
                }
428
                __typename
429
            }
430
        }
431
QUERY;
432
            $data = [
433
                'operation_name' => 'GET_PRICES',
434
                'variables' => [
435
                    'where' => [
436
                        'ticketIn' => $ticketIn,
437
                    ],
438
                ],
439
                'query' => $query,
440
            ];
441
442
            $responseData = $this->makeGraphQLRequest($data);
443
            return !empty($responseData[ $field_key ]) ? $responseData[ $field_key ] : null;
444
    }
445
446
447
    /**
448
     * @return array|null
449
     * @since $VID:$
450
     */
451 View Code Duplication
    protected function getGraphQLPriceTypes()
452
    {
453
        $field_key = lcfirst($this->namespace) . 'PriceTypes';
454
        $query = <<<QUERY
455
        query GET_PRICES {
456
            {$field_key} {
457
                nodes {
458
                    id
459
                    dbId
460
                    baseType
461
                    isBasePrice
462
                    isDeleted
463
                    isDiscount
464
                    isPercent
465
                    isTax
466
                    name
467
                    order
468
                    __typename
469
                }
470
                __typename
471
            }
472
        }
473
QUERY;
474
            $data = [
475
                'operation_name' => 'GET_PRICES',
476
                'query' => $query,
477
            ];
478
479
            $responseData = $this->makeGraphQLRequest($data);
480
            return !empty($responseData[ $field_key ]) ? $responseData[ $field_key ] : null;
481
    }
482
483
484
    /**
485
     * @return array|null
486
     * @since $VID:$
487
     */
488 View Code Duplication
    protected function getGraphQLCurrentUser()
489
    {
490
        $field_key = 'viewer';
491
        $query = <<<QUERY
492
        query GET_CURRENT_USER {
493
            {$field_key} {
494
                description
495
                email
496
                firstName
497
                id
498
                name
499
                nicename
500
                nickname
501
                lastName
502
                locale
503
                userId
504
                username
505
                __typename
506
            }
507
        }
508
QUERY;
509
            $data = [
510
                'operation_name' => 'GET_CURRENT_USER',
511
                'query' => $query,
512
            ];
513
514
            $responseData = $this->makeGraphQLRequest($data);
515
            return !empty($responseData[ $field_key ]) ? $responseData[ $field_key ] : null;
516
    }
517
518
519
    /**
520
     * @return array|null
521
     * @since $VID:$
522
     */
523 View Code Duplication
    protected function getGraphQLGeneralSettings()
524
    {
525
        $field_key = 'generalSettings';
526
        $query = <<<QUERY
527
        query GET_GENERAL_SETTINGS {
528
            {$field_key} {
529
                dateFormat
530
                timeFormat
531
                timezone
532
                __typename
533
            }
534
        }
535
QUERY;
536
            $data = [
537
                'operation_name' => 'GET_CURRENT_USER',
538
                'query' => $query,
539
            ];
540
541
            $responseData = $this->makeGraphQLRequest($data);
542
            return !empty($responseData[ $field_key ]) ? $responseData[ $field_key ] : null;
543
    }
544
545
546
    /**
547
     * @param array $data
548
     * @return array
549
     * @since $VID:$
550
     */
551
    protected function makeGraphQLRequest($data)
552
    {
553
        try {
554
            $response = graphql($data);
555
            if (!empty($response['data'])) {
556
                return $response['data'];
557
            }
558
            return null;
559
        } catch (\Exception $e) {
560
            // do something with the errors thrown
561
            return null;
562
        }
563
    }
564
565
566
    /**
567
     * @param mixed       $source  The source that's passed down the GraphQL queries
0 ignored issues
show
Bug introduced by
There is no parameter named $source. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
568
     * @param array       $args    The inputArgs on the field
0 ignored issues
show
Bug introduced by
There is no parameter named $args. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
569
     * @param AppContext  $context The AppContext passed down the GraphQL tree
0 ignored issues
show
Bug introduced by
There is no parameter named $context. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
570
     * @param ResolveInfo $info    The ResolveInfo passed down the GraphQL tree
0 ignored issues
show
Bug introduced by
There is no parameter named $info. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
571
     * @return string
572
     * @throws EE_Error
573
     * @throws Exception
574
     * @throws InvalidArgumentException
575
     * @throws InvalidDataTypeException
576
     * @throws InvalidInterfaceException
577
     * @throws ReflectionException
578
     * @throws UserError
579
     * @throws UnexpectedEntityException
580
     * @since $VID:$
581
     */
582
    public static function getRelationalData($eventId)
583
    {
584
585
        $data = [
586
            'datetimes'  => [],
587
            'tickets'    => [],
588
            'prices'     => [],
589
        ];
590
591
        $eem_datetime   = EEM_Datetime::instance();
592
        $eem_ticket     = EEM_Ticket::instance();
593
        $eem_price      = EEM_Price::instance();
594
        $eem_price_type = EEM_Price_Type::instance();
595
596
        // PROCESS DATETIMES
597
        $related_models = [
598
            'tickets' => $eem_ticket,
599
        ];
600
        // Get the IDs of event datetimes.
601
        $datetimeIds = $eem_datetime->get_col([['EVT_ID' => $eventId]]);
602 View Code Duplication
        foreach ($datetimeIds as $datetimeId) {
603
            $GID = self::convertToGlobalId($eem_datetime->item_name(), $datetimeId);
604
            foreach ($related_models as $key => $model) {
605
                // Get the IDs of related entities for the datetime ID.
606
                $Ids = $model->get_col([['Datetime.DTT_ID' => $datetimeId]]);
607
                if (! empty($Ids)) {
608
                    $data['datetimes'][ $GID ][ $key ] = self::convertToGlobalId($model->item_name(), $Ids);
609
                }
610
            }
611
        }
612
613
        // PROCESS TICKETS
614
        $related_models = [
615
            'datetimes' => $eem_datetime,
616
            'prices'    => $eem_price,
617
        ];
618
        // Get the IDs of all datetime tickets.
619
        $ticketIds = $eem_ticket->get_col([['Datetime.DTT_ID' => ['in', $datetimeIds]]]);
620 View Code Duplication
        foreach ($ticketIds as $ticketId) {
621
            $GID = self::convertToGlobalId($eem_ticket->item_name(), $ticketId);
622
623
            foreach ($related_models as $key => $model) {
624
                // Get the IDs of related entities for the ticket ID.
625
                $Ids = $model->get_col([['Ticket.TKT_ID' => $ticketId]]);
626
                if (! empty($Ids)) {
627
                    $data['tickets'][ $GID ][ $key ] = self::convertToGlobalId($model->item_name(), $Ids);
628
                }
629
            }
630
        }
631
632
        // PROCESS PRICES
633
        $related_models = [
634
            'tickets'    => $eem_ticket,
635
            'priceTypes' => $eem_price_type,
636
        ];
637
        // Get the IDs of all ticket prices.
638
        $priceIds = $eem_price->get_col([['Ticket.TKT_ID' => ['in', $ticketIds]]]);
639 View Code Duplication
        foreach ($priceIds as $priceId) {
640
            $GID = self::convertToGlobalId($eem_price->item_name(), $priceId);
641
642
            foreach ($related_models as $key => $model) {
643
                // Get the IDs of related entities for the price ID.
644
                $Ids = $model->get_col([['Price.PRC_ID' => $priceId]]);
645
                if (! empty($Ids)) {
646
                    $data['prices'][ $GID ][ $key ] = self::convertToGlobalId($model->item_name(), $Ids);
647
                }
648
            }
649
        }
650
651
        return $data;
652
    }
653
654
    /**
655
     * Convert the DB ID into GID
656
     *
657
     * @param string    $type
658
     * @param int|int[] $ID
659
     * @return mixed
660
     */
661
    public static function convertToGlobalId($type, $ID)
662
    {
663
        if (is_array($ID)) {
664
            return array_map(function ($id) use ($type) {
665
                return self::convertToGlobalId($type, $id);
666
            }, $ID);
667
        }
668
        return Relay::toGlobalId($type, $ID);
669
    }
670
671
672
    /**
673
     * @param int $eventId
674
     * @return array
675
     * @throws EE_Error
676
     * @throws InvalidDataTypeException
677
     * @throws InvalidInterfaceException
678
     * @throws ModelConfigurationException
679
     * @throws RestPasswordIncorrectException
680
     * @throws RestPasswordRequiredException
681
     * @throws UnexpectedEntityException
682
     * @throws RestException
683
     * @throws InvalidArgumentException
684
     * @throws ReflectionException
685
     * @throws DomainException
686
     * @since $VID:$
687
     */
688
    protected function getAllEventData($eventId)
689
    {
690
        // these should ultimately be extracted out into their own classes (one per model)
691
        $event = $this->spoofer->getOneApiResult(
692
            $this->event_model,
693
            [['EVT_ID' => $eventId]]
694
        );
695
        if (! (is_array($event) && isset($event['EVT_ID']) && $event['EVT_ID'] === $eventId)) {
696
            return [];
697
        }
698
        $eventDates = $this->getEventDates($eventId);
699
        if ((! is_array($eventDates) || empty($eventDates))
700
            || (isset($_REQUEST['action']) && $_REQUEST['action'] === 'create_new')
701
        ) {
702
            $this->addDefaultEntities($eventId);
703
            $eventDates = $this->getEventDates($eventId);
704
        }
705
706
        $event = [$eventId => $event];
707
        $relations = [
708
            'event'    => [
709
                $eventId => [
710
                    'datetime' => []
711
                ]
712
            ],
713
            'datetime' => [],
714
            'ticket'   => [],
715
            'price'    => [],
716
        ];
717
718
        $datetimes = [];
719
        $eventDateTickets = [];
720
        if (is_array($eventDates)) {
721
            foreach ($eventDates as $eventDate) {
722
                if (isset($eventDate['DTT_ID']) && $eventDate['DTT_ID']) {
723
                    $DTT_ID = $eventDate['DTT_ID'];
724
                    $datetimes[ $DTT_ID ] = $eventDate;
725
                    $relations['event'][ $eventId ]['datetime'][] = $DTT_ID;
726
                    $eventDateTickets[ $DTT_ID ] = $this->spoofer->getApiResults(
727
                        $this->ticket_model,
728
                        [[
729
                            'Datetime.DTT_ID' => $DTT_ID,
730
                            'TKT_deleted' => ['IN', [true, false]]
731
                        ]]
732
                    );
733
                }
734
            }
735
        }
736
737
        $prices = [];
738
        $tickets = [];
739
        if (is_array($eventDateTickets)) {
740
            foreach ($eventDateTickets as $DTT_ID => $dateTickets) {
741
                if (is_array($dateTickets)) {
742
                    $relations['datetime'][ $DTT_ID ]['ticket'] = [];
743
                    foreach ($dateTickets as $ticket) {
744
                        if (isset($ticket['TKT_ID']) && $ticket['TKT_ID']) {
745
                            $TKT_ID = $ticket['TKT_ID'];
746
                            $tickets[ $TKT_ID ] = $ticket;
747
                            $relations['datetime'][ $DTT_ID ]['ticket'][] = $TKT_ID;
748
                            $ticketPrices[ $TKT_ID ] = $this->spoofer->getApiResults(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$ticketPrices was never initialized. Although not strictly required by PHP, it is generally a good practice to add $ticketPrices = 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...
749
                                $this->price_model,
750
                                [['Ticket.TKT_ID' => $TKT_ID]]
751
                            );
752
                            if (is_array($ticketPrices[ $TKT_ID ])) {
753
                                $relations['ticket'][ $TKT_ID ]['price'] = [];
754
                                foreach ($ticketPrices[ $TKT_ID ] as $ticketPrice) {
755
                                    $PRC_ID = $ticketPrice['PRC_ID'];
756
                                    $prices[ $PRC_ID ] = $ticketPrice;
757
                                    $relations['ticket'][ $TKT_ID ]['price'][] = $PRC_ID;
758
                                }
759
                            }
760
                        }
761
                    }
762
                }
763
            }
764
        }
765
        $price_type_results = $this->spoofer->getApiResults(
766
            $this->price_type_model,
767
            [['PRT_deleted' => false]]
768
        );
769
        $price_types = [];
770
        foreach ($price_type_results as $price_type) {
771
            $price_types[ $price_type['PRT_ID'] ] = $price_type;
772
        }
773
        $venue = $this->spoofer->getOneApiResult(
774
            $this->venue_model,
775
            [['Event.EVT_ID' => $eventId]]
776
        );
777
        if (is_array($venue) && isset($venue['VNU_ID'])) {
778
            $relations['event'][ $eventId ]['venue'] = [ $venue['VNU_ID'] ];
779
            $venue = [$venue['VNU_ID'] => $venue];
780
        }
781
782
        $schemas = [
783
            'event'      => $this->spoofer->getModelSchema('events'),
784
            'datetime'   => $this->spoofer->getModelSchema('datetimes'),
785
            'ticket'     => $this->spoofer->getModelSchema('tickets'),
786
            'price'      => $this->spoofer->getModelSchema('prices'),
787
            'price_type' => $this->spoofer->getModelSchema('price_types'),
788
            'venue'      => $this->spoofer->getModelSchema('venues'),
789
        ];
790
791
        $tktRegCount = [];
792
        foreach ($tickets as $ticket) {
793
            $tkt_instance = $this->ticket_model->get_one_by_ID($ticket['TKT_ID']);
794
795
            $tktRegCount[ $ticket['TKT_ID'] ] = $tkt_instance instanceof EE_Ticket ?
796
            $tkt_instance->count_registrations()
797
            : 0;
798
        }
799
        return [
800
            'eventId'         => $eventId,
801
            'event'           => $event,
802
            'datetime'        => $datetimes,
803
            'ticket'          => $tickets,
804
            'price'           => $prices,
805
            'price_type'      => $price_types,
806
            'venue'           => $venue,
807
            'schemas'         => $schemas,
808
            'relations'       => $relations,
809
            'tktRegCount'     => $tktRegCount,
810
        ];
811
    }
812
}
813