Passed
Pull Request — master (#134)
by Rustam
02:17
created

Group::hasDispatcher()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Router;
6
7
use InvalidArgumentException;
8
use Psr\Http\Message\ServerRequestInterface;
9
use Psr\Http\Server\RequestHandlerInterface;
10
use RuntimeException;
11
use Yiisoft\Http\Method;
12
use Yiisoft\Middleware\Dispatcher\MiddlewareDispatcher;
13
14
use function get_class;
15
use function in_array;
16
use function is_object;
17
18
final class Group implements GroupInterface
19
{
20
    /**
21
     * @var Group[]|Route[]
22
     */
23
    private array $items = [];
24
    private ?string $prefix;
25
    private array $middlewareDefinitions = [];
26
    private ?string $host = null;
27
    private ?string $namePrefix = null;
28
    private bool $routesAdded = false;
29
    private bool $middlewareAdded = false;
30
    private array $disabledMiddlewareDefinitions = [];
31
    private ?MiddlewareDispatcher $dispatcher;
32
33 23
    private function __construct(?string $prefix = null, MiddlewareDispatcher $dispatcher = null)
34
    {
35 23
        $this->dispatcher = $dispatcher;
36 23
        $this->prefix = $prefix;
37 23
    }
38
39
    /**
40
     * Create a new group instance.
41
     *
42
     * @param string|null $prefix URL prefix to prepend to all routes of the group.
43
     * @param MiddlewareDispatcher|null $dispatcher Middleware dispatcher to use for the group.
44
     *
45
     * @return GroupInterface
46
     */
47 23
    public static function create(
48
        ?string $prefix = null,
49
        MiddlewareDispatcher $dispatcher = null
50
    ): GroupInterface {
51 23
        return new self($prefix, $dispatcher);
52
    }
53
54 20
    public function routes(...$routes): GroupInterface
55
    {
56 20
        if ($this->middlewareAdded) {
57 1
            throw new RuntimeException('routes() can not be used after prependMiddleware().');
58
        }
59 19
        $new = clone $this;
60 19
        foreach ($routes as $route) {
61 19
            if ($route instanceof Route || $route instanceof self) {
62 18
                if (!$route->hasDispatcher() && $new->hasDispatcher()) {
63 5
                    $route = $route->withDispatcher($new->dispatcher);
64
                }
65 18
                $new->items[] = $route;
66
            } else {
67 1
                $type = is_object($route) ? get_class($route) : gettype($route);
68 1
                throw new InvalidArgumentException(
69 1
                    sprintf('Route should be either an instance of Route or Group, %s given.', $type)
70
                );
71
            }
72
        }
73
74 18
        $new->routesAdded = true;
75
76 18
        return $new;
77
    }
78
79 2
    public function withDispatcher(MiddlewareDispatcher $dispatcher): GroupInterface
80
    {
81 2
        $group = clone $this;
82 2
        $group->dispatcher = $dispatcher;
83 2
        foreach ($group->items as $index => $item) {
84 2
            if (!$item->hasDispatcher()) {
85 2
                $item = $item->withDispatcher($dispatcher);
86 2
                $group->items[$index] = $item;
87
            }
88
        }
89
90 2
        return $group;
91
    }
92
93 2
    public function withAutoOptions(): GroupInterface
94
    {
95 2
        if (!$this->routesAdded) {
96
            throw new RuntimeException('withAutoOptions() can not be used before routes().');
97
        }
98 2
        $group = clone $this;
99 2
        $pattern = null;
100 2
        foreach ($group->items as $index => $item) {
101 2
            if ($item instanceof self) {
102 1
                $item = $item->withAutoOptions();
103 1
                $group->items[$index] = $item;
104
            } else {
105
                // Avoid duplicates
106 2
                if ($pattern === $item->getPattern() || in_array(Method::OPTIONS, $item->getMethods(), true)) {
107 2
                    continue;
108
                }
109 2
                $pattern = $item->getPattern();
110 2
                $route = Route::options($pattern);
111 2
                $group->items[] = $route->action(
112 2
                    static fn (ServerRequestInterface $request, RequestHandlerInterface $handler) => $handler->handle(
113
                        $request
114
                    )
115 2
                );
116
            }
117
        }
118
119 2
        return $group;
120
    }
121
122 18
    public function hasDispatcher(): bool
123
    {
124 18
        return $this->dispatcher !== null;
125
    }
126
127 7
    public function middleware($middlewareDefinition): GroupInterface
128
    {
129 7
        if ($this->routesAdded) {
130
            throw new RuntimeException('middleware() can not be used after routes().');
131
        }
132 7
        $new = clone $this;
133 7
        array_unshift($new->middlewareDefinitions, $middlewareDefinition);
134 7
        return $new;
135
    }
136
137 3
    public function prependMiddleware($middlewareDefinition): GroupInterface
138
    {
139 3
        $new = clone $this;
140 3
        $new->middlewareDefinitions[] = $middlewareDefinition;
141 3
        $new->middlewareAdded = true;
142 3
        return $new;
143
    }
144
145 3
    public function namePrefix(string $namePrefix): GroupInterface
146
    {
147 3
        $new = clone $this;
148 3
        $new->namePrefix = $namePrefix;
149 3
        return $new;
150
    }
151
152 2
    public function host(string $host): GroupInterface
153
    {
154 2
        $new = clone $this;
155 2
        $new->host = rtrim($host, '/');
156 2
        return $new;
157
    }
158
159
    public function disableMiddleware($middlewareDefinition): GroupInterface
160
    {
161
        $new = clone $this;
162
        $new->disabledMiddlewareDefinitions[] = $middlewareDefinition;
163
        return $new;
164
    }
165
166
    /**
167
     * @return Group[]|Route[]
168
     */
169 17
    public function getItems(): array
170
    {
171 17
        return $this->items;
172
    }
173
174 15
    public function getPrefix(): ?string
175
    {
176 15
        return $this->prefix;
177
    }
178
179 15
    public function getNamePrefix(): ?string
180
    {
181 15
        return $this->namePrefix;
182
    }
183
184 15
    public function getHost(): ?string
185
    {
186 15
        return $this->host;
187
    }
188
189 12
    public function getMiddlewareDefinitions(): array
190
    {
191 12
        foreach ($this->middlewareDefinitions as $index => $definition) {
192 8
            if (in_array($definition, $this->disabledMiddlewareDefinitions, true)) {
193
                unset($this->middlewareDefinitions[$index]);
194
            }
195
        }
196
197 12
        return $this->middlewareDefinitions;
198
    }
199
}
200