Completed
Pull Request — master (#2)
by Angel
03:03
created

Modular   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 5
dl 0
loc 55
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A isApplicable() 0 5 1
A createRules() 0 15 3
A createNotFoundException() 0 6 1
1
<?php
2
3
namespace roaresearch\yii2\roa\urlRules;
4
5
use Yii;
6
use yii\{base\InvalidConfigException, web\NotFoundHttpException};
7
8
/**
9
 * Url Rule to handle modules implementing the `UrlRuleCreator` interface.
10
 *
11
 * @author Angel (Faryshta) Guevara <[email protected]>
12
 */
13
class Modular extends Composite
14
{
15
    /**
16
     * @inheritdoc
17
     *
18
     * can accept parameters.
19
     *
20
     * - {moduleId}: the unique module id associated to this rule.
21
     */
22
    public $notFoundMessage = 'Unknown route for module `{moduleId}`.';
23
24
    /**
25
     * @var string unique id to grab the module from the application that will
26
     * parse the rules.
27
     */
28
    public $moduleId;
29
30
    /**
31
     * @inheritdoc
32
     */
33
    protected function isApplicable(string $route): bool
34
    {
35
        // only parse rules which start with the module id
36
        return 0 === strpos($route, $this->moduleId);
37
    }
38
39
    /**
40
     * @inheritdoc
41
     */
42
    protected function createRules()
43
    {
44
        if (empty($this->moduleId)) {
45
            throw new InvalidConfigException('`moduleId` must be set.');
46
        }
47
        $module = Yii::$app->getModule($this->moduleId);
48
        if (!$module instanceof UrlRuleCreator) {
49
            throw new InvalidConfigException(
50
                "Module `{$this->moduleId}` must implement "
51
                    . UrlRuleCreator::class
52
            );
53
        }
54
55
        return $module->createUrlRules($this);
56
    }
57
58
    /**
59
     * @inheritdoc
60
     */
61
    protected function createNotFoundException(): NotFoundHttpException
62
    {
63
        return new NotFoundHttpException(
64
            strtr($this->notFoundMessage, ['{moduleId}' => $this->moduleId])
65
        );
66
    }
67
}
68