Passed
Push — master ( 2c3696...c338c9 )
by Alexander
03:12
created

RestGroupFactory::createDefaultRoutes()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 7
c 1
b 0
f 0
dl 0
loc 12
ccs 0
cts 8
cp 0
rs 10
cc 4
nc 4
nop 1
crap 20
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Factory;
6
7
use Yiisoft\Http\Method;
8
use Yiisoft\Router\Group;
9
use Yiisoft\Router\Route;
10
use Yiisoft\Router\RouteCollectorInterface;
11
use ReflectionClass;
12
13
final class RestGroupFactory
14
{
15
    private const ENTITY_PATTERN = '{id:\d+}';
16
17
    private const METHODS = [
18
        'get' => Method::GET,
19
        'list' => Method::GET,
20
        'post' => Method::POST,
21
        'put' => Method::PUT,
22
        'delete' => Method::DELETE,
23
        'patch' => Method::PATCH,
24
        'head' => Method::HEAD,
25
        'options' => Method::OPTIONS,
26
    ];
27
28
    public static function create(string $prefix, string $controller): RouteCollectorInterface
29
    {
30
        return Group::create($prefix, self::createDefaultRoutes($controller));
31
    }
32
33
    private static function createDefaultRoutes(string $controller): array
34
    {
35
        $routes = [];
36
        $reflection = new ReflectionClass($controller);
37
        foreach (self::METHODS as $methodName => $httpMethod) {
38
            if ($reflection->hasMethod($methodName)) {
39
                $pattern = $methodName === 'list' ? '' : self::ENTITY_PATTERN;
40
                $routes[] = Route::methods([$httpMethod], $pattern, [$controller, $methodName]);
41
            }
42
        }
43
44
        return $routes;
45
    }
46
}
47