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