Completed
Pull Request — master (#241)
by Kristof
07:21 queued 02:55
created

CdbXMLImporter::importBookingInfo()   F

Complexity

Conditions 15
Paths 1870

Size

Total Lines 62
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 62
rs 2.9275
c 0
b 0
f 0
cc 15
eloc 37
nc 1870
nop 3

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace CultuurNet\UDB3\Event\ReadModel\JSONLD;
4
5
use CultureFeed_Cdb_Data_File;
6
use CultureFeed_Cdb_Data_Keyword;
7
use CultuurNet\UDB3\Cdb\CdbId\EventCdbIdExtractorInterface;
8
use CultuurNet\UDB3\Cdb\DateTimeFactory;
9
use CultuurNet\UDB3\Cdb\PriceDescriptionParser;
10
use CultuurNet\UDB3\LabelCollection;
11
use CultuurNet\UDB3\Offer\ReadModel\JSONLD\CdbXMLItemBaseImporter;
12
use CultuurNet\UDB3\SluggerInterface;
13
use CultuurNet\UDB3\StringFilter\StringFilterInterface;
14
15
/**
16
 * Takes care of importing cultural events in the CdbXML format (UDB2)
17
 * into a UDB3 JSON-LD document.
18
 */
19
class CdbXMLImporter
20
{
21
    /**
22
     * @var CdbXMLItemBaseImporter
23
     */
24
    private $cdbXMLItemBaseImporter;
25
26
    /**
27
     * @var EventCdbIdExtractorInterface
28
     */
29
    private $cdbIdExtractor;
30
31
    /**
32
     * @var PriceDescriptionParser
33
     */
34
    private $priceDescriptionParser;
35
36
    /**
37
     * @param CdbXMLItemBaseImporter $dbXMLItemBaseImporter
38
     * @param EventCdbIdExtractorInterface $cdbIdExtractor
39
     */
40
    public function __construct(
41
        CdbXMLItemBaseImporter $dbXMLItemBaseImporter,
42
        EventCdbIdExtractorInterface $cdbIdExtractor,
43
        PriceDescriptionParser $priceDescriptionParser
44
    ) {
45
        $this->cdbXMLItemBaseImporter = $dbXMLItemBaseImporter;
46
        $this->cdbIdExtractor = $cdbIdExtractor;
47
        $this->priceDescriptionParser = $priceDescriptionParser;
48
    }
49
50
    /**
51
     * @var StringFilterInterface[]
52
     */
53
    private $descriptionFilters = [];
54
55
    /**
56
     * Imports a UDB2 event into a UDB3 JSON-LD document.
57
     *
58
     * @param \stdClass $base
59
     *   The JSON-LD document to start from.
60
     * @param \CultureFeed_Cdb_Item_Event $event
61
     *   The cultural event data from UDB2 to import.
62
     * @param PlaceServiceInterface $placeManager
63
     *   The manager from which to retrieve the JSON-LD of a place.
64
     * @param OrganizerServiceInterface $organizerManager
65
     *   The manager from which to retrieve the JSON-LD of an organizer.
66
     * @param SluggerInterface $slugger
67
     *   The slugger that's used to generate a sameAs reference.
68
     *
69
     * @return \stdClass
70
     *   The document with the UDB2 event data merged in.
71
     */
72
    public function documentWithCdbXML(
73
        $base,
74
        \CultureFeed_Cdb_Item_Event $event,
75
        PlaceServiceInterface $placeManager,
76
        OrganizerServiceInterface $organizerManager,
77
        SluggerInterface $slugger
78
    ) {
79
        $jsonLD = clone $base;
80
81
        /** @var \CultureFeed_Cdb_Data_EventDetail $detail */
82
        $detail = null;
83
84
        /** @var \CultureFeed_Cdb_Data_EventDetail[] $details */
85
        $details = $event->getDetails();
86
87
        foreach ($details as $languageDetail) {
88
            $language = $languageDetail->getLanguage();
89
90
            // The first language detail found will be used to retrieve
91
            // properties from which in UDB3 are not any longer considered
92
            // to be language specific.
93
            if (!$detail) {
94
                $detail = $languageDetail;
95
            }
96
97
            $jsonLD->name[$language] = $languageDetail->getTitle();
98
99
            $this->importDescription($languageDetail, $jsonLD, $language);
100
        }
101
102
        $this->cdbXMLItemBaseImporter->importAvailable($event, $jsonLD);
103
104
        $this->importPicture($detail, $jsonLD);
105
106
        $this->importLabels($event, $jsonLD);
107
108
        $jsonLD->calendarSummary = $detail->getCalendarSummary();
109
110
        $this->importLocation($event, $placeManager, $jsonLD);
111
112
        $this->importOrganizer($event, $organizerManager, $jsonLD);
113
114
        $this->importBookingInfo($event, $detail, $jsonLD);
115
116
        $this->importPriceInfo($detail, $jsonLD);
117
118
        $this->importTerms($event, $jsonLD);
119
120
        $this->cdbXMLItemBaseImporter->importPublicationInfo($event, $jsonLD);
121
122
        $this->importCalendar($event, $jsonLD);
123
124
        $this->importTypicalAgeRange($event, $jsonLD);
125
126
        $this->importPerformers($detail, $jsonLD);
127
128
        $this->importLanguages($event, $jsonLD);
129
130
        $this->importUitInVlaanderenReference($event, $slugger, $jsonLD);
131
132
        $this->cdbXMLItemBaseImporter->importExternalId($event, $jsonLD);
133
134
        $this->importSeeAlso($event, $jsonLD);
135
136
        $this->importContactPoint($event, $jsonLD);
137
138
        $this->cdbXMLItemBaseImporter->importWorkflowStatus($event, $jsonLD);
139
140
        return $jsonLD;
141
    }
142
143
    /**
144
     * @param StringFilterInterface $filter
145
     */
146
    public function addDescriptionFilter(StringFilterInterface $filter)
147
    {
148
        $this->descriptionFilters[] = $filter;
149
    }
150
151
    /**
152
     * @param int $unixTime
153
     * @return \DateTime
154
     */
155
    private function dateFromUdb2UnixTime($unixTime)
156
    {
157
        $dateTime = new \DateTime(
158
            '@' . $unixTime,
159
            new \DateTimeZone('Europe/Brussels')
160
        );
161
162
        return $dateTime;
163
    }
164
165
    /**
166
     * @param \CultureFeed_Cdb_Data_EventDetail $languageDetail
167
     * @param \stdClass $jsonLD
168
     * @param string $language
169
     */
170
    private function importDescription($languageDetail, $jsonLD, $language)
171
    {
172
        $descriptions = [
173
            $languageDetail->getShortDescription(),
174
            $languageDetail->getLongDescription()
175
        ];
176
        $descriptions = array_filter($descriptions);
177
        $description = implode('<br/>', $descriptions);
178
179
        foreach ($this->descriptionFilters as $descriptionFilter) {
180
            $description = $descriptionFilter->filter($description);
181
        };
182
183
        $jsonLD->description[$language] = $description;
184
    }
185
186
    /**
187
     * @param \CultureFeed_Cdb_Item_Event $event
188
     * @param $jsonLD
189
     */
190
    private function importLabels(\CultureFeed_Cdb_Item_Event $event, $jsonLD)
191
    {
192
        /** @var CultureFeed_Cdb_Data_Keyword[] $keywords */
193
        $keywords = array_values($event->getKeywords(true));
194
195
        $validKeywords = array_filter(
196
            $keywords,
197
            function (CultureFeed_Cdb_Data_Keyword $keyword) {
198
                return strlen(trim($keyword->getValue())) > 0;
199
            }
200
        );
201
202
        $visibleKeywords = array_filter(
203
            $validKeywords,
204
            function (CultureFeed_Cdb_Data_Keyword $keyword) {
205
                return $keyword->isVisible();
206
            }
207
        );
208
209
        $hiddenKeywords = array_filter(
210
            $validKeywords,
211
            function (CultureFeed_Cdb_Data_Keyword $keyword) {
212
                return !$keyword->isVisible();
213
            }
214
        );
215
216
        $this->addKeywordsAsLabelsProperty($jsonLD, 'labels', $visibleKeywords);
217
        $this->addKeywordsAsLabelsProperty($jsonLD, 'hiddenLabels', $hiddenKeywords);
218
    }
219
220
    /**
221
     * @param object $jsonLD
222
     * @param string $labelsPropertyName
223
     *  The property where the labels should be listed. Used the differentiate between visible and hidden labels.
224
     * @param CultureFeed_Cdb_Data_Keyword[] $keywords
225
     */
226
    private function addKeywordsAsLabelsProperty($jsonLD, $labelsPropertyName, array $keywords)
227
    {
228
        $labels = array_map(
229
            function ($keyword) {
230
                /** @var CultureFeed_Cdb_Data_Keyword $keyword */
231
                return $keyword->getValue();
232
            },
233
            $keywords
234
        );
235
236
        // Create a label collection to get rid of duplicates.
237
        $labelCollection = LabelCollection::fromStrings($labels);
238
239
        if (count($labelCollection) > 0) {
240
            $jsonLD->{$labelsPropertyName} = $labelCollection->toStrings();
241
        }
242
    }
243
244
    /**
245
     * @param \CultureFeed_Cdb_Data_EventDetail $detail
246
     * @param \stdClass $jsonLD
247
     *
248
     * This is based on code found in the culturefeed theme.
249
     * @see https://github.com/cultuurnet/culturefeed/blob/master/culturefeed_agenda/theme/theme.inc#L266-L284
250
     */
251 View Code Duplication
    private function importPicture($detail, $jsonLD)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
252
    {
253
        $mainPicture = null;
254
255
        // first check if there is a media file that is main and has the PHOTO media type
256
        $photos = $detail->getMedia()->byMediaType(CultureFeed_Cdb_Data_File::MEDIA_TYPE_PHOTO);
257
        foreach ($photos as $photo) {
258
            if ($photo->isMain()) {
259
                $mainPicture = $photo;
260
            }
261
        }
262
263
        // the IMAGEWEB media type is deprecated but can still be used as a main image if there is no PHOTO
264
        if (empty($mainPicture)) {
265
            $images = $detail->getMedia()->byMediaType(CultureFeed_Cdb_Data_File::MEDIA_TYPE_IMAGEWEB);
266
            foreach ($images as $image) {
267
                if ($image->isMain()) {
268
                    $mainPicture = $image;
269
                }
270
            }
271
        }
272
273
        // if there is no explicit main image we just use the oldest picture of any type
274
        if (empty($mainPicture)) {
275
            $pictures = $detail->getMedia()->byMediaTypes(
276
                [
277
                    CultureFeed_Cdb_Data_File::MEDIA_TYPE_PHOTO,
278
                    CultureFeed_Cdb_Data_File::MEDIA_TYPE_IMAGEWEB
279
                ]
280
            );
281
282
            $pictures->rewind();
283
            $mainPicture = count($pictures) > 0 ? $pictures->current() : null;
284
        }
285
286
        if ($mainPicture) {
287
            $jsonLD->image = $mainPicture->getHLink();
288
        }
289
    }
290
291
    /**
292
     * @param \CultureFeed_Cdb_Item_Event $event
293
     * @param PlaceServiceInterface $placeManager
294
     * @param \stdClass $jsonLD
295
     */
296
    private function importLocation(\CultureFeed_Cdb_Item_Event $event, PlaceServiceInterface $placeManager, $jsonLD)
297
    {
298
        $location = array();
299
        $location['@type'] = 'Place';
300
301
        $location_id = $this->cdbIdExtractor->getRelatedPlaceCdbId($event);
302
303
        if ($location_id) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $location_id of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
304
            $location += (array)$placeManager->placeJSONLD($location_id);
305
        } else {
306
            $location_cdb = $event->getLocation();
307
            $location['name']['nl'] = $location_cdb->getLabel();
308
            $address = $location_cdb->getAddress()->getPhysicalAddress();
309
            if ($address) {
310
                $location['address'] = array(
311
                    'addressCountry' => $address->getCountry(),
312
                    'addressLocality' => $address->getCity(),
313
                    'postalCode' => $address->getZip(),
314
                    'streetAddress' =>
315
                        $address->getStreet() . ' ' . $address->getHouseNumber(
316
                        ),
317
                );
318
            }
319
        }
320
        $jsonLD->location = $location;
321
    }
322
323
    /**
324
     * @param \CultureFeed_Cdb_Item_Event $event
325
     * @param OrganizerServiceInterface $organizerManager
326
     * @param \stdClass $jsonLD
327
     */
328
    private function importOrganizer(
329
        \CultureFeed_Cdb_Item_Event $event,
330
        OrganizerServiceInterface $organizerManager,
331
        $jsonLD
332
    ) {
333
        $organizer = null;
334
        $organizer_id = $this->cdbIdExtractor->getRelatedOrganizerCdbId($event);
335
        $organizer_cdb = $event->getOrganiser();
336
        $contact_info_cdb = $event->getContactInfo();
337
338
        if ($organizer_id) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $organizer_id of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
339
            $organizer = (array)$organizerManager->organizerJSONLD($organizer_id);
340
        } elseif ($organizer_cdb && $contact_info_cdb) {
341
            $organizer = array();
342
            $organizer['name'] = $organizer_cdb->getLabel();
343
344
            $emails_cdb = $contact_info_cdb->getMails();
345
            if (count($emails_cdb) > 0) {
346
                $organizer['email'] = array();
347
                foreach ($emails_cdb as $email) {
348
                    $organizer['email'][] = $email->getMailAddress();
349
                }
350
            }
351
352
            $phones_cdb = $contact_info_cdb->getPhones();
353
            if (count($phones_cdb) > 0) {
354
                $organizer['phone'] = array();
355
                foreach ($phones_cdb as $phone) {
356
                    $organizer['phone'][] = $phone->getNumber();
357
                }
358
            }
359
        }
360
361
        if (!is_null($organizer)) {
362
            $organizer['@type'] = 'Organizer';
363
            $jsonLD->organizer = $organizer;
364
        }
365
    }
366
367
    /**
368
     * @param \CultureFeed_Cdb_Data_EventDetail $detail
369
     * @param \stdClass $jsonLD
370
     */
371
    private function importPriceInfo(
372
        \CultureFeed_Cdb_Data_EventDetail $detail,
373
        $jsonLD
374
    ) {
375
        $prices = array();
376
377
        $price = $detail->getPrice();
378
379
        if ($price) {
380
            $description = $price->getDescription();
381
382
            if ($description) {
383
                $prices = $this->priceDescriptionParser->parse($description);
384
            }
385
386
            // If price description was not interpretable, fall back to
387
            // price title and value.
388
            if (empty($prices) && $price->getValue() !== null) {
389
                $prices['Basistarief'] = floatval($price->getValue());
390
            }
391
        }
392
393
        if (!empty($prices)) {
394
            $priceInfo = array();
395
396
            /** @var \CultureFeed_Cdb_Data_Price $price */
397
            foreach ($prices as $title => $value) {
398
                $priceInfoItem = array(
399
                    'name' => $title,
400
                    'priceCurrency' => 'EUR',
401
                    'price' => $value,
402
                );
403
404
                $priceInfoItem['category'] = 'tariff';
405
406
                if ($priceInfoItem['name'] === 'Basistarief') {
407
                    $priceInfoItem['category'] = 'base';
408
                }
409
410
                $priceInfo[] = $priceInfoItem;
411
            }
412
413
            if (!empty($priceInfo)) {
414
                $jsonLD->priceInfo = $priceInfo;
415
            }
416
        }
417
    }
418
419
    /**
420
     * @param \CultureFeed_Cdb_Data_EventDetail $detail
421
     * @param \stdClass $jsonLD
422
     */
423
    private function importBookingInfo(
424
        \CultureFeed_Cdb_Item_Event $event,
425
        \CultureFeed_Cdb_Data_EventDetail $detail,
426
        $jsonLD
427
    ) {
428
        $bookingInfo = array();
429
430
        $price = $detail->getPrice();
431
        if ($price) {
432
433
            if ($price->getDescription()) {
434
                $bookingInfo['description'] = $price->getDescription();
435
            }
436
            if ($price->getTitle()) {
437
                $bookingInfo['name'] = $price->getTitle();
438
            }
439
            if ($price->getValue() !== null) {
440
                $bookingInfo['priceCurrency'] = 'EUR';
441
                $bookingInfo['price'] = floatval($price->getValue());
442
            }
443
            if ($bookingPeriod = $event->getBookingPeriod()) {
444
                $startDate = $this->dateFromUdb2UnixTime($bookingPeriod->getDateFrom());
445
                $endDate = $this->dateFromUdb2UnixTime($bookingPeriod->getDateTill());
446
447
                $bookingInfo['availabilityStarts'] = $startDate->format('c');
448
                $bookingInfo['availabilityEnds'] = $endDate->format('c');
449
            }
450
        }
451
452
        // Add reservation contact data.
453
        $contactInfo = $event->getContactInfo();
454
        if ($contactInfo) {
455
            foreach ($contactInfo->getUrls() as $url) {
456
                if ($url->isForReservations()) {
457
                    $bookingInfo['url'] = $url->getUrl();
458
                    break;
459
                }
460
            }
461
462
            if (array_key_exists('url', $bookingInfo)) {
463
                $bookingInfo['urlLabel'] = 'Reserveer plaatsen';
464
            }
465
466
            foreach ($contactInfo->getPhones() as $phone) {
467
                if ($phone->isForReservations()) {
468
                    $bookingInfo['phone'] = $phone->getNumber();
469
                    break;
470
                }
471
            }
472
473
            foreach ($contactInfo->getMails() as $mail) {
474
                if ($mail->isForReservations()) {
475
                    $bookingInfo['email'] = $mail->getMailAddress();
476
                    break;
477
                }
478
            }
479
        }
480
481
        if (!empty($bookingInfo)) {
482
            $jsonLD->bookingInfo = $bookingInfo;
483
        }
484
    }
485
486
    /**
487
     * @param \CultureFeed_Cdb_Item_Event $event
488
     * @param \stdClass $jsonLD
489
     */
490
    private function importContactPoint(
491
        \CultureFeed_Cdb_Item_Event $event,
492
        \stdClass $jsonLD
493
    ) {
494
        $contactInfo = $event->getContactInfo();
495
496
        $notForReservations = function (\CultureFeed_Cdb_Data_UseableForReservations $item) {
497
            return !$item->isForReservations();
498
        };
499
500
        if ($contactInfo) {
501
            $contactPoint = array();
502
503
            $emails = array_filter($contactInfo->getMails(), $notForReservations);
504
505 View Code Duplication
            if (!empty($emails)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
506
                $contactPoint['email'] = array_map(
507
                    function (\CultureFeed_Cdb_Data_Mail $email) {
508
                        return $email->getMailAddress();
509
                    },
510
                    $emails
511
                );
512
                $contactPoint['email'] = array_values($contactPoint['email']);
513
            }
514
515
            $phones = array_filter($contactInfo->getPhones(), $notForReservations);
516
517 View Code Duplication
            if (!empty($phones)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
518
                $contactPoint['phone'] = array_map(
519
                    function (\CultureFeed_Cdb_Data_phone $phone) {
520
                        return $phone->getNumber();
521
                    },
522
                    $phones
523
                );
524
                $contactPoint['phone'] = array_values($contactPoint['phone']);
525
            }
526
527
            $urls = array_filter($contactInfo->getUrls(), $notForReservations);
528
529 View Code Duplication
            if (!empty($urls)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
530
                $contactPoint['url'] = array_map(
531
                    function (\CultureFeed_Cdb_Data_Url $url) {
532
                        return $url->getUrl();
533
                    },
534
                    $urls
535
                );
536
                $contactPoint['url'] = array_values($contactPoint['url']);
537
            }
538
539
            array_filter($contactPoint);
540
            if (count($contactPoint) > 0) {
541
                $contactPoint['type'] = '';
542
                $jsonLD->contactPoint[] = $contactPoint;
543
            }
544
        }
545
    }
546
547
    /**
548
     * @param \CultureFeed_Cdb_Item_Event $event
549
     * @param \stdClass $jsonLD
550
     */
551
    private function importTerms(\CultureFeed_Cdb_Item_Event $event, $jsonLD)
552
    {
553
        $themeBlacklist = [
554
            'Thema onbepaald',
555
            'Meerder kunstvormen',
556
            'Meerdere filmgenres'
557
        ];
558
        $categories = array();
559 View Code Duplication
        foreach ($event->getCategories() as $category) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
560
            /* @var \Culturefeed_Cdb_Data_Category $category */
561
            if ($category && !in_array($category->getName(), $themeBlacklist)) {
562
                $categories[] = array(
563
                    'label' => $category->getName(),
564
                    'domain' => $category->getType(),
565
                    'id' => $category->getId(),
566
                );
567
            }
568
        }
569
        $jsonLD->terms = $categories;
570
    }
571
572
    /**
573
     * @param \CultureFeed_Cdb_Item_Event $event
574
     * @param \stdClass $jsonLD
575
     */
576
    private function importCalendar(\CultureFeed_Cdb_Item_Event $event, $jsonLD)
577
    {
578
        // To render the front-end we make a distinction between 4 calendar types
579
        // Permanent and Periodic map directly to the Cdb calendar classes
580
        // Simple timestamps are divided into single and multiple
581
        $calendarType = 'unknown';
582
        $calendar = $event->getCalendar();
583
584
        if ($calendar instanceof \CultureFeed_Cdb_Data_Calendar_Permanent) {
585
            $calendarType = 'permanent';
586
        } elseif ($calendar instanceof \CultureFeed_Cdb_Data_Calendar_PeriodList) {
587
            $calendarType = 'periodic';
588
            $calendar->rewind();
589
            $firstCalendarItem = $calendar->current();
590
            $startDateString = $firstCalendarItem->getDateFrom() . 'T00:00:00';
591
            $startDate = DateTimeFactory::dateTimeFromDateString($startDateString);
592
593 View Code Duplication
            if (iterator_count($calendar) > 1) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
594
                $periodArray = iterator_to_array($calendar);
595
                $lastCalendarItem = end($periodArray);
596
            } else {
597
                $lastCalendarItem = $firstCalendarItem;
598
            }
599
600
            $endDateString = $lastCalendarItem->getDateTo() . 'T00:00:00';
601
            $endDate = DateTimeFactory::dateTimeFromDateString($endDateString);
602
603
            $jsonLD->startDate = $startDate->format('c');
604
            $jsonLD->endDate = $endDate->format('c');
605
        } elseif ($calendar instanceof \CultureFeed_Cdb_Data_Calendar_TimestampList) {
606
            $calendarType = 'single';
607
            $calendar->rewind();
608
            /** @var \CultureFeed_Cdb_Data_Calendar_Timestamp $firstCalendarItem */
609
            $firstCalendarItem = $calendar->current();
610
            if ($firstCalendarItem->getStartTime()) {
611
                $dateString =
612
                    $firstCalendarItem->getDate() . 'T' . $firstCalendarItem->getStartTime();
613
            } else {
614
                $dateString = $firstCalendarItem->getDate() . 'T00:00:00';
615
            }
616
617
            $startDate = DateTimeFactory::dateTimeFromDateString($dateString);
618
619 View Code Duplication
            if (iterator_count($calendar) > 1) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
620
                $periodArray = iterator_to_array($calendar);
621
                $lastCalendarItem = end($periodArray);
622
            } else {
623
                $lastCalendarItem = $firstCalendarItem;
624
            }
625
626
            $endDateString = null;
627
            if ($lastCalendarItem->getEndTime()) {
628
                $endDateString =
629
                    $lastCalendarItem->getDate() . 'T' . $lastCalendarItem->getEndTime();
630
            } else {
631
                if (iterator_count($calendar) > 1) {
632
                    $endDateString = $lastCalendarItem->getDate() . 'T00:00:00';
633
                }
634
            }
635
636
            if ($endDateString) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $endDateString of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
637
                $endDate = DateTimeFactory::dateTimeFromDateString($endDateString);
638
                $jsonLD->endDate = $endDate->format('c');
639
640
                if ($startDate->format('Ymd') != $endDate->format('Ymd')) {
641
                    $calendarType = 'multiple';
642
                }
643
            }
644
645
            $jsonLD->startDate = $startDate->format('c');
646
        }
647
648
        $jsonLD->calendarType = $calendarType;
649
    }
650
651
    /**
652
     * @param \CultureFeed_Cdb_Item_Event $event
653
     * @param \stdClass $jsonLD
654
     */
655
    private function importTypicalAgeRange(\CultureFeed_Cdb_Item_Event $event, $jsonLD)
656
    {
657
        $ageFrom = $event->getAgeFrom();
658
        if ($ageFrom) {
659
            $jsonLD->typicalAgeRange = "{$ageFrom}-";
660
        }
661
    }
662
663
    /**
664
     * @param \CultureFeed_Cdb_Data_EventDetail $detail
665
     * @param \stdClass $jsonLD
666
     */
667
    private function importPerformers(\CultureFeed_Cdb_Data_EventDetail $detail, $jsonLD)
668
    {
669
        /** @var \CultureFeed_Cdb_Data_Performer $performer */
670
        $performers = $detail->getPerformers();
671
        if ($performers) {
672
            foreach ($performers as $performer) {
673
                if ($performer->getLabel()) {
674
                    $performerData = new \stdClass();
675
                    $performerData->name = $performer->getLabel();
676
                    $jsonLD->performer[] = $performerData;
677
                }
678
            }
679
        }
680
    }
681
682
    /**
683
     * @param \CultureFeed_Cdb_Item_Event $event
684
     * @param \stdClass $jsonLD
685
     */
686
    private function importLanguages(\CultureFeed_Cdb_Item_Event $event, $jsonLD)
687
    {
688
        /** @var \CultureFeed_Cdb_Data_Language $udb2Language */
689
        $languages = $event->getLanguages();
690
        if ($languages) {
691
            $jsonLD->language = [];
692
            foreach ($languages as $udb2Language) {
693
                $jsonLD->language[] = $udb2Language->getLanguage();
694
            }
695
            $jsonLD->language = array_unique($jsonLD->language);
696
        }
697
    }
698
699
    /**
700
     * @param \CultureFeed_Cdb_Item_Event $event
701
     * @param \stdClass $jsonLD
702
     */
703
    private function importSeeAlso(
704
        \CultureFeed_Cdb_Item_Event $event,
705
        \stdClass $jsonLD
706
    ) {
707
        if (!property_exists($jsonLD, 'seeAlso')) {
708
            $jsonLD->seeAlso = [];
709
        }
710
711
        // Add contact info url, if it's not for reservations.
712
        if ($contactInfo = $event->getContactInfo()) {
713
            /** @var \CultureFeed_Cdb_Data_Url[] $contactUrls */
714
            $contactUrls = $contactInfo->getUrls();
715
            if (is_array($contactUrls) && count($contactUrls) > 0) {
716
                foreach ($contactUrls as $contactUrl) {
717
                    if (!$contactUrl->isForReservations()) {
718
                        $jsonLD->seeAlso[] = $contactUrl->getUrl();
719
                    }
720
                }
721
            }
722
        }
723
    }
724
725
    /**
726
     * @param \CultureFeed_Cdb_Item_Event $event
727
     * @param SluggerInterface $slugger
728
     * @param \stdClass $jsonLD
729
     */
730
    private function importUitInVlaanderenReference(
731
        \CultureFeed_Cdb_Item_Event $event,
732
        SluggerInterface $slugger,
733
        $jsonLD
734
    ) {
735
736
        // Some events seem to not have a Dutch name, even though this is
737
        // required. If there's no Dutch name, we just leave the slug empty as
738
        // that seems to be the behaviour on http://m.uitinvlaanderen.be
739
        if (isset($jsonLD->name['nl'])) {
740
            $name = $jsonLD->name['nl'];
741
            $slug = $slugger->slug($name);
742
        } else {
743
            $slug = '';
744
        }
745
746
        $reference = 'http://www.uitinvlaanderen.be/agenda/e/' . $slug . '/' . $event->getCdbId();
747
748
749
        if (!property_exists($jsonLD, 'sameAs')) {
750
            $jsonLD->sameAs = [];
751
        }
752
753
        if (!in_array($reference, $jsonLD->sameAs)) {
754
            array_push($jsonLD->sameAs, $reference);
755
        }
756
    }
757
}
758