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

Modular   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Test Coverage

Coverage 25%

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 53
ccs 2
cts 8
cp 0.25
rs 10
c 0
b 0
f 0
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A isApplicable() 0 4 1
A createNotFoundException() 0 4 1
A createRules() 0 15 3
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 string $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 string $moduleId;
29
30
    /**
31
     * @inheritdoc
32
     */
33 44
    protected function isApplicable(string $route): bool
34
    {
35
        // only parse rules which start with the module id
36 44
        return 0 === strpos($route, $this->moduleId);
37
    }
38
39
    /**
40
     * @inheritdoc
41
     */
42
    protected function createRules()
43
    {
44
        $this->moduleId ?: throw new InvalidConfigException(
45
            $this::class . '::$moduleId must be set.'
46
        );
47
48
        $module = Yii::$app->getModule($this->moduleId);
49
        if (!$module instanceof UrlRuleCreator) {
50
            throw new InvalidConfigException(
51
                "Module `{$this->moduleId}` must implement "
52
                    . UrlRuleCreator::class
53
            );
54
        }
55
56
        return $module->createUrlRules($this);
57
    }
58
59
    /**
60
     * @inheritdoc
61
     */
62
    protected function createNotFoundException(): NotFoundHttpException
63
    {
64
        return new NotFoundHttpException(
65
            strtr($this->notFoundMessage, ['{moduleId}' => $this->moduleId])
66
        );
67
    }
68
}
69