Completed
Pull Request — master (#239)
by Luc
04:52
created

LabelImporter::importLabels()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 29
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 29
rs 8.8571
c 0
b 0
f 0
cc 1
eloc 16
nc 1
nop 2
1
<?php
2
3
namespace CultuurNet\UDB3;
4
5
use CultureFeed_Cdb_Data_Keyword;
6
7
class LabelImporter
8
{
9
    /**
10
     * @param \CultureFeed_Cdb_Item_Base $item
11
     * @param $jsonLD
12
     */
13
    public function importLabels(\CultureFeed_Cdb_Item_Base $item, $jsonLD)
14
    {
15
        /** @var CultureFeed_Cdb_Data_Keyword[] $keywords */
16
        $keywords = array_values($item->getKeywords(true));
17
18
        $validKeywords = array_filter(
19
            $keywords,
20
            function (CultureFeed_Cdb_Data_Keyword $keyword) {
21
                return strlen(trim($keyword->getValue())) > 0;
22
            }
23
        );
24
25
        $visibleKeywords = array_filter(
26
            $validKeywords,
27
            function (CultureFeed_Cdb_Data_Keyword $keyword) {
28
                return $keyword->isVisible();
29
            }
30
        );
31
32
        $hiddenKeywords = array_filter(
33
            $validKeywords,
34
            function (CultureFeed_Cdb_Data_Keyword $keyword) {
35
                return !$keyword->isVisible();
36
            }
37
        );
38
39
        $this->addKeywordsAsLabelsProperty($jsonLD, 'labels', $visibleKeywords);
40
        $this->addKeywordsAsLabelsProperty($jsonLD, 'hiddenLabels', $hiddenKeywords);
41
    }
42
43
    /**
44
     * @param object $jsonLD
45
     * @param string $labelsPropertyName
46
     *  The property where the labels should be listed. Used the differentiate between visible and hidden labels.
47
     * @param CultureFeed_Cdb_Data_Keyword[] $keywords
48
     */
49
    private function addKeywordsAsLabelsProperty($jsonLD, $labelsPropertyName, array $keywords)
50
    {
51
        $labels = array_map(
52
            function ($keyword) {
53
                /** @var CultureFeed_Cdb_Data_Keyword $keyword */
54
                return $keyword->getValue();
55
            },
56
            $keywords
57
        );
58
59
        // Create a label collection to get rid of duplicates.
60
        $labelCollection = LabelCollection::fromStrings($labels);
61
62
        if (count($labelCollection) > 0) {
63
            $jsonLD->{$labelsPropertyName} = $labelCollection->toStrings();
64
        }
65
    }
66
}
67