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

CdbXMLImporter::importContactPoint()   B

Complexity

Conditions 6
Paths 17

Size

Total Lines 56
Code Lines 33

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