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

RestGroupFactory   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 32
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
eloc 19
c 1
b 0
f 0
dl 0
loc 32
ccs 0
cts 10
cp 0
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A createDefaultRoutes() 0 12 4
A create() 0 3 1
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