RestGroupFactory::createDefaultRoutes()   A
last analyzed

Complexity

Conditions 6
Paths 12

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 6

Importance

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