Completed
Pull Request — master (#4205)
by Craig
09:54 queued 03:35
created

EventDispatcherExtension   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 43
rs 10
c 0
b 0
f 0
wmc 5

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A dispatchGenericEvent() 0 6 1
A getFunctions() 0 5 1
A dispatchEvent() 0 10 2
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Zikula package.
7
 *
8
 * Copyright Zikula Foundation - https://ziku.la/
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Zikula\Bundle\CoreBundle\Twig\Extension;
15
16
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
17
use Twig\Extension\AbstractExtension;
18
use Twig\TwigFunction;
19
use Zikula\Bundle\CoreBundle\Event\GenericEvent;
20
21
class EventDispatcherExtension extends AbstractExtension
22
{
23
    /**
24
     * @var EventDispatcherInterface
25
     */
26
    private $eventDispatcher;
27
28
    public function __construct(
29
        EventDispatcherInterface $eventDispatcher
30
    ) {
31
        $this->eventDispatcher = $eventDispatcher;
32
    }
33
34
    public function getFunctions()
35
    {
36
        return [
37
            new TwigFunction('dispatchEvent', [$this, 'dispatchEvent']),
38
            new TwigFunction('dispatchGenericEvent', [$this, 'dispatchGenericEvent'])
39
        ];
40
    }
41
42
    /**
43
     * @param string $name
44
     * @param array $arguments the arguments, MUST be values only and in the correct order
45
     */
46
    public function dispatchEvent(string $name, $arguments = [])
47
    {
48
        if (class_exists($name)) {
49
            $event = new $name(...$arguments);
50
            $this->eventDispatcher->dispatch($event);
51
52
            return $event;
53
        }
54
55
        return null;
56
    }
57
58
    public function dispatchGenericEvent(string $name, GenericEvent $providedEvent = null, $subject = null, array $arguments = [], $data = null)
59
    {
60
        $event = $providedEvent ?? new GenericEvent($subject, $arguments, $data);
61
        $this->eventDispatcher->dispatch($event, $name);
62
63
        return $event->getData();
64
    }
65
}
66