Passed
Push — master ( 912003...33dd84 )
by Christian
13:09 queued 11s
created

TextCmsElementResolver::enrich()   A

Complexity

Conditions 6
Paths 7

Size

Total Lines 23
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 14
nc 7
nop 3
dl 0
loc 23
rs 9.2222
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace Shopware\Core\Content\Cms\DataResolver\Element;
4
5
use Shopware\Core\Content\Cms\Aggregate\CmsSlot\CmsSlotEntity;
6
use Shopware\Core\Content\Cms\DataResolver\CriteriaCollection;
7
use Shopware\Core\Content\Cms\DataResolver\ResolverContext\EntityResolverContext;
8
use Shopware\Core\Content\Cms\DataResolver\ResolverContext\ResolverContext;
9
use Shopware\Core\Content\Cms\SalesChannel\Struct\TextStruct;
10
11
class TextCmsElementResolver extends AbstractCmsElementResolver
12
{
13
    public function getType(): string
14
    {
15
        return 'text';
16
    }
17
18
    public function collect(CmsSlotEntity $slot, ResolverContext $resolverContext): ?CriteriaCollection
19
    {
20
        return null;
21
    }
22
23
    public function enrich(CmsSlotEntity $slot, ResolverContext $resolverContext, ElementDataCollection $result): void
24
    {
25
        $text = new TextStruct();
26
        $slot->setData($text);
27
28
        $config = $slot->getFieldConfig()->get('content');
29
        if (!$config) {
30
            return;
31
        }
32
33
        if ($config->isMapped() && $resolverContext instanceof EntityResolverContext) {
34
            $content = $this->resolveEntityValue($resolverContext->getEntity(), $config->getValue());
35
36
            $text->setContent((string) $content);
37
        }
38
39
        if ($config->isStatic()) {
40
            if ($resolverContext instanceof EntityResolverContext) {
41
                $content = $this->resolveEntityValues($resolverContext, $config->getValue());
42
43
                $text->setContent((string) $content);
44
            } else {
45
                $text->setContent((string) $config->getValue());
46
            }
47
        }
48
    }
49
50
    private function resolveEntityValues(EntityResolverContext $resolverContext, string $content): ?string
51
    {
52
        // https://regex101.com/r/idIfbk/1
53
        $content = preg_replace_callback(
54
            '/{{\s*(?<property>[\w.\d]+)\s*}}/',
55
            function ($matches) use ($resolverContext) {
56
                try {
57
                    return $this->resolveEntityValue($resolverContext->getEntity(), $matches['property']);
58
                } catch (\InvalidArgumentException $e) {
59
                    return $matches[0];
60
                }
61
            },
62
            $content
63
        );
64
65
        return $content;
66
    }
67
}
68