Passed
Push — master ( d1c5a6...bac8bf )
by Fabian
03:36 queued 12s
created

Listener   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 7
eloc 27
dl 0
loc 60
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A attach() 0 11 1
A renderAssets() 0 37 6
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Fabiang\AsseticBundle;
6
7
use Laminas\EventManager\EventManagerInterface;
8
use Laminas\EventManager\AbstractListenerAggregate;
9
use Laminas\Http\PhpEnvironment\Response;
10
use Laminas\Mvc\MvcEvent;
11
12
class Listener extends AbstractListenerAggregate
13
{
14
15
    /**
16
     * Attach one or more listeners
17
     *
18
     * Implementors may add an optional $priority argument; the EventManager
19
     * implementation will pass this to the aggregate.
20
     */
21
    public function attach(EventManagerInterface $events, $priority = 32): void
22
    {
23
        $this->listeners[] = $events->attach(
24
            MvcEvent::EVENT_DISPATCH,
25
            [$this, 'renderAssets'],
26
            $priority
27
        );
28
        $this->listeners[] = $events->attach(
29
            MvcEvent::EVENT_DISPATCH_ERROR,
30
            [$this, 'renderAssets'],
31
            $priority
32
        );
33
    }
34
35
    public function renderAssets(MvcEvent $e): void
36
    {
37
        $sm = $e->getApplication()->getServiceManager();
38
39
        /** @var Configuration $config */
40
        $config = $sm->get('AsseticConfiguration');
41
        if ($e->getName() === MvcEvent::EVENT_DISPATCH_ERROR) {
42
            $error = $e->getError();
43
            if ($error && !in_array($error, $config->getAcceptableErrors())) {
44
                // break if not an acceptable error
45
                return;
46
            }
47
        }
48
49
        /** @var \Laminas\Stdlib\ResponseInterface|null $response */
50
        $response = $e->getResponse();
51
        if (!$response) {
0 ignored issues
show
introduced by
$response is of type Laminas\Stdlib\ResponseInterface, thus it always evaluated to true.
Loading history...
52
            $response = new Response();
53
            $e->setResponse($response);
54
        }
55
56
        /** @var Service $asseticService */
57
        $asseticService = $sm->get('AsseticService');
58
59
        // setup service if a matched route exist
60
        $router = $e->getRouteMatch();
61
        if ($router) {
62
            $asseticService->setRouteName($router->getMatchedRouteName());
63
            $asseticService->setControllerName($router->getParam('controller'));
64
            $asseticService->setActionName($router->getParam('action'));
65
        }
66
67
        // Create all objects
68
        $asseticService->build();
69
70
        // Init assets for modules
71
        $asseticService->setupRenderer($sm->get('ViewRenderer'));
72
    }
73
74
}
75