Completed
Push — master ( c5dda7...d1c05d )
by Joao
24s queued 10s
created

SwaggerWrapper::__construct()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.8333
c 0
b 0
f 0
cc 3
nc 3
nop 2
1
<?php
2
3
namespace ByJG\RestServer;
4
5
use ByJG\RestServer\Exception\OperationIdInvalidException;
6
use ByJG\RestServer\Exception\SchemaInvalidException;
7
use ByJG\RestServer\Exception\SchemaNotFoundException;
8
use ByJG\Util\Uri;
9
10
class SwaggerWrapper
11
{
12
    protected $schema;
13
14
    /**
15
     * @var ServerRequestHandler
16
     */
17
    protected $handler;
18
19
    /**
20
     * SwaggerWrapper constructor.
21
     * @param $swaggerJson
22
     * @param ServerRequestHandler $handler
23
     * @throws SchemaInvalidException
24
     * @throws SchemaNotFoundException
25
     */
26
    public function __construct($swaggerJson, $handler)
27
    {
28
        $this->handler = $handler;
29
        
30
        if (!file_exists($swaggerJson)) {
31
            throw new SchemaNotFoundException("Schema '$swaggerJson' not found");
32
        }
33
34
        $this->schema = json_decode(file_get_contents($swaggerJson), true);
35
        if (!isset($this->schema['paths'])) {
36
            throw new SchemaInvalidException("Schema '$swaggerJson' is invalid");
37
        }
38
    }
39
40
    /**
41
     * @return array
42
     * @throws OperationIdInvalidException
43
     */
44
    public function generateRoutes()
45
    {
46
        $basePath = isset($this->schema["basePath"]) ? $this->schema["basePath"] : "";
47
        if (empty($basePath) && isset($this->schema["servers"])) {
48
            $uri = new Uri($this->schema["servers"][0]["url"]);
49
            $basePath = $uri->getPath();
50
        }
51
52
        $pathList = $this->sortPaths(array_keys($this->schema['paths']));
53
54
        $routes = [];
55
        foreach ($pathList as $path) {
56
            foreach ($this->schema['paths'][$path] as $method => $properties) {
57
                $handler = $this->handler->getMethodHandler($method, $basePath . $path, $properties);
58
                if (!isset($properties['operationId'])) {
59
                    throw new OperationIdInvalidException('OperationId was not found');
60
                }
61
62
                $parts = explode('::', $properties['operationId']);
63
                if (count($parts) !== 2) {
64
                    throw new OperationIdInvalidException(
65
                        'OperationId needs to be in the format Namespace\\class::method'
66
                    );
67
                }
68
69
                $routes[] = new RoutePattern(
70
                    strtoupper($method),
71
                    $basePath . $path,
72
                    $handler,
73
                    $parts[1],
74
                    $parts[0]
75
                );
76
            }
77
        }
78
79
        return $routes;
80
    }
81
82
    protected function sortPaths($pathList)
83
    {
84
        usort($pathList, function ($left, $right) {
85 View Code Duplication
            if (strpos($left, '{') === false && strpos($right, '{') !== false) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
86
                return -16384;
87
            }
88 View Code Duplication
            if (strpos($left, '{') !== false && strpos($right, '{') === false) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
89
                return 16384;
90
            }
91
            if (strpos($left, $right) !== false) {
92
                return -16384;
93
            }
94
            if (strpos($right, $left) !== false) {
95
                return 16384;
96
            }
97
            return strcmp($left, $right);
98
        });
99
100
        return $pathList;
101
    }
102
}