Passed
Push — master ( 035a69...ef3bdc )
by Kirill
03:22
created

Namespaced   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
eloc 19
c 1
b 0
f 0
dl 0
loc 58
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A resolveAction() 0 3 1
A __construct() 0 16 1
A resolveController() 0 11 2
1
<?php
2
3
/**
4
 * Spiral Framework.
5
 *
6
 * @license   MIT
7
 * @author    Anton Titov (Wolfy-J)
8
 */
9
10
declare(strict_types=1);
11
12
namespace Spiral\Router\Target;
13
14
use Spiral\Router\Exception\TargetException;
15
16
/**
17
 * Provides ability to invoke any controller from given namespace.
18
 *
19
 * Example: new Namespaced("App\Controllers");
20
 */
21
final class Namespaced extends AbstractTarget
22
{
23
    /** @var string */
24
    private $namespace;
25
26
    /** @var string */
27
    private $postfix;
28
29
    /** @var \Doctrine\Inflector\Inflector */
30
    private $inflector;
31
32
    /**
33
     * @param string $namespace
34
     * @param string $postfix
35
     * @param int    $options
36
     * @param string $defaultAction
37
     */
38
    public function __construct(
39
        string $namespace,
40
        string $postfix = 'Controller',
41
        int $options = 0,
42
        string $defaultAction = 'index'
43
    ) {
44
        $this->namespace = rtrim($namespace, '\\');
45
        $this->postfix = ucfirst($postfix);
46
47
        parent::__construct(
48
            ['controller' => null, 'action' => null],
49
            ['controller' => null, 'action' => null],
50
            $options
51
        );
52
53
        $this->inflector = (new \Doctrine\Inflector\Rules\English\InflectorFactory())->build();
54
    }
55
56
    /**
57
     * @inheritdoc
58
     */
59
    protected function resolveController(array $matches): string
60
    {
61
        if (preg_match('/[^a-z_0-9\-]/i', $matches['controller'])) {
62
            throw new TargetException('Invalid namespace target, controller name not allowed.');
63
        }
64
65
        return sprintf(
66
            '%s\\%s%s',
67
            $this->namespace,
68
            $this->inflector->classify($matches['controller']),
69
            $this->postfix
70
        );
71
    }
72
73
    /**
74
     * @inheritdoc
75
     */
76
    protected function resolveAction(array $matches): ?string
77
    {
78
        return $matches['action'];
79
    }
80
}
81