Passed
Push — master ( 4b3582...7f619e )
by Julien
06:12
created

Maintenance::beforeDispatch()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 20
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 4
eloc 14
c 1
b 1
f 0
nc 5
nop 2
dl 0
loc 20
ccs 0
cts 14
cp 0
crap 20
rs 9.7998
1
<?php
2
3
/**
4
 * This file is part of the Zemit Framework.
5
 *
6
 * (c) Zemit Team <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE.txt
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Zemit\Mvc\Dispatcher;
13
14
use Phalcon\Dispatcher\Exception;
15
use Phalcon\Dispatcher\AbstractDispatcher;
16
use Phalcon\Events\Event;
17
use Zemit\Config\ConfigInterface;
18
use Zemit\Di\Injectable;
19
use Zemit\Mvc\Dispatcher;
20
21
/**
22
 * Maintenance Dispatcher Plugin
23
 * Redirect to the maintenance module/controller/action
24
 */
25
class Maintenance extends Injectable
26
{
27
    public const ?string DEFAULT_MAINTENANCE_MODULE = null;
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected '?' on line 27 at column 17
Loading history...
28
    public const ?string DEFAULT_MAINTENANCE_CONTROLLER = 'error';
29
    public const ?string DEFAULT_MAINTENANCE_ACTION = 'maintenance';
30
    
31
    /**
32
     * Executed before dispatching a request.
33
     *
34
     * @param Event $event The event object.
35
     * @param AbstractDispatcher $dispatcher The dispatcher object.
36
     *
37
     * @return void
38
     *
39
     * @throws Exception If an error happened during the dispatch forwarding to the maintenance route
40
     */
41
    public function beforeDispatch(Event $event, AbstractDispatcher $dispatcher): void
42
    {
43
        $config = $this->getDI()->get('config');
44
        assert($config instanceof ConfigInterface);
45
        
46
        $maintenance = $config->path('app.maintenance', false);
47
        if ($maintenance) {
48
            $route = $config->pathToArray('router.maintenance') ?? [];
49
            $route['module'] ??= self::DEFAULT_MAINTENANCE_MODULE;
50
            $route['controller'] ??= self::DEFAULT_MAINTENANCE_CONTROLLER;
51
            $route['action'] ??= self::DEFAULT_MAINTENANCE_ACTION;
52
            
53
            if ($dispatcher instanceof Dispatcher) {
54
                $dispatcher->forward($route, true);
55
            } else {
56
                $dispatcher->forward($route);
57
            }
58
            
59
            if ($event->isCancelable()) {
60
                $event->stop();
61
            }
62
        }
63
    }
64
}
65