AddLibrarySubscriber::getSubscribedEvents()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 3
c 1
b 0
f 1
nc 1
nop 0
dl 0
loc 5
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Setono\SyliusStrandsPlugin\EventListener;
6
7
use Setono\SyliusStrandsPlugin\Tag\Tags;
8
use Setono\TagBag\Tag\ScriptTag;
9
use Setono\TagBag\Tag\TagInterface;
10
use Setono\TagBag\Tag\TwigTag;
11
use Setono\TagBag\TagBagInterface;
12
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
13
use Symfony\Component\HttpKernel\KernelEvents;
14
15
final class AddLibrarySubscriber extends TagSubscriber
16
{
17
    /** @var string */
18
    private $apiId;
19
20
    public function __construct(TagBagInterface $tagBag, string $apiId)
21
    {
22
        parent::__construct($tagBag);
23
24
        $this->apiId = $apiId;
25
    }
26
27
    public static function getSubscribedEvents(): array
28
    {
29
        return [
30
            KernelEvents::REQUEST => [
31
                'addLibrary',
32
            ],
33
        ];
34
    }
35
36
    public function addLibrary(GetResponseEvent $event): void
37
    {
38
        if (!$event->isMasterRequest()) {
39
            return;
40
        }
41
42
        // Only add the library on 'real' page loads, not AJAX requests like add to cart
43
        if ($event->getRequest()->isXmlHttpRequest()) {
44
            return;
45
        }
46
47
        $this->tagBag->addTag(
48
            (new ScriptTag('var StrandsTrack = window.StrandsTrack || [];'))
49
                ->setSection(TagInterface::SECTION_BODY_END)
50
                ->setPriority(100)
51
        );
52
        $this->tagBag->addTag(
53
            (new TwigTag('@SetonoSyliusStrandsPlugin/Tag/library.html.twig', ['api_id' => $this->apiId]))
54
                ->setSection(TagInterface::SECTION_BODY_END)
55
                ->setName(Tags::TAG_LIBRARY)
56
                ->setPriority(-100)
57
        );
58
    }
59
}
60