Completed
Push — master ( 124fed...6caa0a )
by Tomáš
12s
created

ProxySourceTaxonomyDataProvider::beforeRun()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 19
ccs 0
cts 17
cp 0
rs 9.2
c 0
b 0
f 0
cc 4
eloc 12
nc 4
nop 0
crap 20
1
<?php
2
3
/*
4
 * This file is a part of Sculpin.
5
 *
6
 * (c) Dragonfly Development Inc.
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Symplify\PHP7_Sculpin\PostsBundle\Taxonomy;
13
14
use Symplify\PHP7_Sculpin\DataProvider\DataProviderInterface;
15
use Symplify\PHP7_Sculpin\DataProvider\DataProviderManager;
16
use Symplify\PHP7_Sculpin\Event\SculpinEvents;
17
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
18
19
final class ProxySourceTaxonomyDataProvider implements DataProviderInterface, EventSubscriberInterface
20
{
21
    private $taxons = [];
22
    private $dataProviderManager;
23
    private $dataProviderName;
24
    private $taxonomyKey;
25
26
    public function __construct(
27
        DataProviderManager $dataProviderManager,
28
        string $dataProviderName,
29
        string $taxonomyKey
30
    ) {
31
        $this->dataProviderManager = $dataProviderManager;
32
        $this->dataProviderName = $dataProviderName;
33
        $this->taxonomyKey = $taxonomyKey;
34
    }
35
36
    public function provideData() : array
37
    {
38
        return $this->taxons;
39
    }
40
41
    public static function getSubscribedEvents()
42
    {
43
        return [
44
            SculpinEvents::BEFORE_RUN => 'beforeRun',
45
        ];
46
    }
47
48
    public function beforeRun()
49
    {
50
        $taxons = [];
51
        $dataProvider = $this->dataProviderManager->dataProvider($this->dataProviderName);
52
53
        foreach ($dataProvider->provideData() as $item) {
54
            if ($itemTaxons = $item->data()->get($this->taxonomyKey)) {
55
                $normalizedItemTaxons = [];
56
                foreach ((array) $itemTaxons as $itemTaxon) {
57
                    $normalizedItemTaxon = trim($itemTaxon);
58
                    $taxons[$normalizedItemTaxon][] = $item;
59
                    $normalizedItemTaxons[] = $normalizedItemTaxon;
60
                }
61
                $item->data()->set($this->taxonomyKey, $normalizedItemTaxons);
62
            }
63
        }
64
65
        $this->taxons = $taxons;
66
    }
67
}
68