Completed
Pull Request — master (#241)
by Kristof
04:36
created

CdbXMLImporter::importContactPoint()   B

Complexity

Conditions 6
Paths 17

Size

Total Lines 56
Code Lines 32

Duplication

Lines 27
Ratio 48.21 %

Importance

Changes 0
Metric Value
dl 27
loc 56
rs 8.7592
c 0
b 0
f 0
cc 6
eloc 32
nc 17
nop 2

How to fix   Long Method   

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
            if ($price->getDescription()) {
433
                $bookingInfo['description'] = $price->getDescription();
434
            }
435
            if ($price->getTitle()) {
436
                $bookingInfo['name'] = $price->getTitle();
437
            }
438
            if ($price->getValue() !== null) {
439
                $bookingInfo['priceCurrency'] = 'EUR';
440
                $bookingInfo['price'] = floatval($price->getValue());
441
            }
442
            if ($bookingPeriod = $event->getBookingPeriod()) {
443
                $startDate = $this->dateFromUdb2UnixTime($bookingPeriod->getDateFrom());
444
                $endDate = $this->dateFromUdb2UnixTime($bookingPeriod->getDateTill());
445
446
                $bookingInfo['availabilityStarts'] = $startDate->format('c');
447
                $bookingInfo['availabilityEnds'] = $endDate->format('c');
448
            }
449
        }
450
451
        // Add reservation contact data.
452
        $contactInfo = $event->getContactInfo();
453
        if ($contactInfo) {
454
            foreach ($contactInfo->getUrls() as $url) {
455
                if ($url->isForReservations()) {
456
                    $bookingInfo['url'] = $url->getUrl();
457
                    break;
458
                }
459
            }
460
461
            if (array_key_exists('url', $bookingInfo)) {
462
                $bookingInfo['urlLabel'] = 'Reserveer plaatsen';
463
            }
464
465
            foreach ($contactInfo->getPhones() as $phone) {
466
                if ($phone->isForReservations()) {
467
                    $bookingInfo['phone'] = $phone->getNumber();
468
                    break;
469
                }
470
            }
471
472
            foreach ($contactInfo->getMails() as $mail) {
473
                if ($mail->isForReservations()) {
474
                    $bookingInfo['email'] = $mail->getMailAddress();
475
                    break;
476
                }
477
            }
478
        }
479
480
        if (!empty($bookingInfo)) {
481
            $jsonLD->bookingInfo = $bookingInfo;
482
        }
483
    }
484
485
    /**
486
     * @param \CultureFeed_Cdb_Item_Event $event
487
     * @param \stdClass $jsonLD
488
     */
489
    private function importContactPoint(
490
        \CultureFeed_Cdb_Item_Event $event,
491
        \stdClass $jsonLD
492
    ) {
493
        $contactInfo = $event->getContactInfo();
494
495
        $notForReservations = function ($item) {
496
            /** @var \CultureFeed_Cdb_Data_Url|\CultureFeed_Cdb_Data_Phone|\CultureFeed_Cdb_Data_Mail $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 (!empty($contactPoint)) {
541
                $jsonLD->contactPoint = $contactPoint;
542
            }
543
        }
544
    }
545
546
    /**
547
     * @param \CultureFeed_Cdb_Item_Event $event
548
     * @param \stdClass $jsonLD
549
     */
550
    private function importTerms(\CultureFeed_Cdb_Item_Event $event, $jsonLD)
551
    {
552
        $themeBlacklist = [
553
            'Thema onbepaald',
554
            'Meerder kunstvormen',
555
            'Meerdere filmgenres'
556
        ];
557
        $categories = array();
558 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...
559
            /* @var \Culturefeed_Cdb_Data_Category $category */
560
            if ($category && !in_array($category->getName(), $themeBlacklist)) {
561
                $categories[] = array(
562
                    'label' => $category->getName(),
563
                    'domain' => $category->getType(),
564
                    'id' => $category->getId(),
565
                );
566
            }
567
        }
568
        $jsonLD->terms = $categories;
569
    }
570
571
    /**
572
     * @param \CultureFeed_Cdb_Item_Event $event
573
     * @param \stdClass $jsonLD
574
     */
575
    private function importCalendar(\CultureFeed_Cdb_Item_Event $event, $jsonLD)
576
    {
577
        // To render the front-end we make a distinction between 4 calendar types
578
        // Permanent and Periodic map directly to the Cdb calendar classes
579
        // Simple timestamps are divided into single and multiple
580
        $calendarType = 'unknown';
581
        $calendar = $event->getCalendar();
582
583
        if ($calendar instanceof \CultureFeed_Cdb_Data_Calendar_Permanent) {
584
            $calendarType = 'permanent';
585
        } elseif ($calendar instanceof \CultureFeed_Cdb_Data_Calendar_PeriodList) {
586
            $calendarType = 'periodic';
587
            $calendar->rewind();
588
            $firstCalendarItem = $calendar->current();
589
            $startDateString = $firstCalendarItem->getDateFrom() . 'T00:00:00';
590
            $startDate = DateTimeFactory::dateTimeFromDateString($startDateString);
591
592 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...
593
                $periodArray = iterator_to_array($calendar);
594
                $lastCalendarItem = end($periodArray);
595
            } else {
596
                $lastCalendarItem = $firstCalendarItem;
597
            }
598
599
            $endDateString = $lastCalendarItem->getDateTo() . 'T00:00:00';
600
            $endDate = DateTimeFactory::dateTimeFromDateString($endDateString);
601
602
            $jsonLD->startDate = $startDate->format('c');
603
            $jsonLD->endDate = $endDate->format('c');
604
        } elseif ($calendar instanceof \CultureFeed_Cdb_Data_Calendar_TimestampList) {
605
            $calendarType = 'single';
606
            $calendar->rewind();
607
            /** @var \CultureFeed_Cdb_Data_Calendar_Timestamp $firstCalendarItem */
608
            $firstCalendarItem = $calendar->current();
609
            if ($firstCalendarItem->getStartTime()) {
610
                $dateString =
611
                    $firstCalendarItem->getDate() . 'T' . $firstCalendarItem->getStartTime();
612
            } else {
613
                $dateString = $firstCalendarItem->getDate() . 'T00:00:00';
614
            }
615
616
            $startDate = DateTimeFactory::dateTimeFromDateString($dateString);
617
618 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...
619
                $periodArray = iterator_to_array($calendar);
620
                $lastCalendarItem = end($periodArray);
621
            } else {
622
                $lastCalendarItem = $firstCalendarItem;
623
            }
624
625
            $endDateString = null;
626
            if ($lastCalendarItem->getEndTime()) {
627
                $endDateString =
628
                    $lastCalendarItem->getDate() . 'T' . $lastCalendarItem->getEndTime();
629
            } else {
630
                if (iterator_count($calendar) > 1) {
631
                    $endDateString = $lastCalendarItem->getDate() . 'T00:00:00';
632
                }
633
            }
634
635
            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...
636
                $endDate = DateTimeFactory::dateTimeFromDateString($endDateString);
637
                $jsonLD->endDate = $endDate->format('c');
638
639
                if ($startDate->format('Ymd') != $endDate->format('Ymd')) {
640
                    $calendarType = 'multiple';
641
                }
642
            }
643
644
            $jsonLD->startDate = $startDate->format('c');
645
        }
646
647
        $jsonLD->calendarType = $calendarType;
648
    }
649
650
    /**
651
     * @param \CultureFeed_Cdb_Item_Event $event
652
     * @param \stdClass $jsonLD
653
     */
654
    private function importTypicalAgeRange(\CultureFeed_Cdb_Item_Event $event, $jsonLD)
655
    {
656
        $ageFrom = $event->getAgeFrom();
657
        if ($ageFrom) {
658
            $jsonLD->typicalAgeRange = "{$ageFrom}-";
659
        }
660
    }
661
662
    /**
663
     * @param \CultureFeed_Cdb_Data_EventDetail $detail
664
     * @param \stdClass $jsonLD
665
     */
666
    private function importPerformers(\CultureFeed_Cdb_Data_EventDetail $detail, $jsonLD)
667
    {
668
        /** @var \CultureFeed_Cdb_Data_Performer $performer */
669
        $performers = $detail->getPerformers();
670
        if ($performers) {
671
            foreach ($performers as $performer) {
672
                if ($performer->getLabel()) {
673
                    $performerData = new \stdClass();
674
                    $performerData->name = $performer->getLabel();
675
                    $jsonLD->performer[] = $performerData;
676
                }
677
            }
678
        }
679
    }
680
681
    /**
682
     * @param \CultureFeed_Cdb_Item_Event $event
683
     * @param \stdClass $jsonLD
684
     */
685
    private function importLanguages(\CultureFeed_Cdb_Item_Event $event, $jsonLD)
686
    {
687
        /** @var \CultureFeed_Cdb_Data_Language $udb2Language */
688
        $languages = $event->getLanguages();
689
        if ($languages) {
690
            $jsonLD->language = [];
691
            foreach ($languages as $udb2Language) {
692
                $jsonLD->language[] = $udb2Language->getLanguage();
693
            }
694
            $jsonLD->language = array_unique($jsonLD->language);
695
        }
696
    }
697
698
    /**
699
     * @param \CultureFeed_Cdb_Item_Event $event
700
     * @param \stdClass $jsonLD
701
     */
702
    private function importSeeAlso(
703
        \CultureFeed_Cdb_Item_Event $event,
704
        \stdClass $jsonLD
705
    ) {
706
        if (!property_exists($jsonLD, 'seeAlso')) {
707
            $jsonLD->seeAlso = [];
708
        }
709
710
        // Add contact info url, if it's not for reservations.
711
        if ($contactInfo = $event->getContactInfo()) {
712
            /** @var \CultureFeed_Cdb_Data_Url[] $contactUrls */
713
            $contactUrls = $contactInfo->getUrls();
714
            if (is_array($contactUrls) && count($contactUrls) > 0) {
715
                foreach ($contactUrls as $contactUrl) {
716
                    if (!$contactUrl->isForReservations()) {
717
                        $jsonLD->seeAlso[] = $contactUrl->getUrl();
718
                    }
719
                }
720
            }
721
        }
722
    }
723
724
    /**
725
     * @param \CultureFeed_Cdb_Item_Event $event
726
     * @param SluggerInterface $slugger
727
     * @param \stdClass $jsonLD
728
     */
729
    private function importUitInVlaanderenReference(
730
        \CultureFeed_Cdb_Item_Event $event,
731
        SluggerInterface $slugger,
732
        $jsonLD
733
    ) {
734
735
        // Some events seem to not have a Dutch name, even though this is
736
        // required. If there's no Dutch name, we just leave the slug empty as
737
        // that seems to be the behaviour on http://m.uitinvlaanderen.be
738
        if (isset($jsonLD->name['nl'])) {
739
            $name = $jsonLD->name['nl'];
740
            $slug = $slugger->slug($name);
741
        } else {
742
            $slug = '';
743
        }
744
745
        $reference = 'http://www.uitinvlaanderen.be/agenda/e/' . $slug . '/' . $event->getCdbId();
746
747
748
        if (!property_exists($jsonLD, 'sameAs')) {
749
            $jsonLD->sameAs = [];
750
        }
751
752
        if (!in_array($reference, $jsonLD->sameAs)) {
753
            array_push($jsonLD->sameAs, $reference);
754
        }
755
    }
756
}
757