Completed
Push — master ( 00cc1c...3873f0 )
by Alex
01:35
created

RoutesSet.php (1 issue)

1
<?php
2
namespace Mezon\Router;
3
4
trait RoutesSet
5
{
6
7
    /**
8
     * List off routes for all supported request methods
9
     */
10
    protected $routes = [
11
        'GET' => [],
12
        'POST' => [],
13
        'PUT' => [],
14
        'DELETE' => [],
15
        'OPTION' => []
16
    ];
17
18
    /**
19
     * Route names
20
     *
21
     * @var array
22
     */
23
    private $routeNames = [];
24
25
    /**
26
     * This flag rises when we add route / * /
27
     *
28
     * @var bool
29
     */
30
    protected $universalRouteWasAdded = false;
31
32
    /**
33
     * Method validates request method
34
     *
35
     * @param string $requestMethod
36
     *            HTTP request method
37
     */
38
    protected function validateRequestMethod(string $requestMethod): void
39
    {
40
        if (isset($this->routes[$requestMethod]) === false) {
41
            throw (new \Exception('Unsupported request method'));
42
        }
43
    }
44
45
    /**
46
     * Method returns list of routes for the HTTP method.
47
     *
48
     * @param string $requestMethod
49
     *            HTTP request method
50
     * @return array Routes
51
     */
52
    protected function &getRoutesForMethod(string $requestMethod): array
53
    {
54
        return $this->routes[$requestMethod];
55
    }
56
57
    /**
58
     * Method returns a list of supported request methods
59
     *
60
     * @return array list of supported request methods
61
     */
62
    public static function getListOfSupportedRequestMethods(): array
63
    {
64
        return [
65
            'GET',
66
            'POST',
67
            'PUT',
68
            'DELETE',
69
            'OPTION'
70
        ];
71
    }
72
73
    /**
74
     * Method clears router data.
75
     */
76
    public function clear()
77
    {
78
        $this->universalRouteWasAdded = false;
79
80
        $this->routeNames = [];
81
82
        foreach (self::getListOfSupportedRequestMethods() as $requestMethod) {
83
            $this->routes[$requestMethod] = [];
84
        }
85
86
        $this->cachedRegExps = [];
87
88
        $this->middleware = [];
0 ignored issues
show
Bug Best Practice introduced by
The property middleware does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
89
    }
90
91
    /**
92
     * Method returns true if the router exists
93
     *
94
     * @param string $route
95
     *            checking route
96
     * @return bool true if the router exists, false otherwise
97
     */
98
    public function routeExists(string $route): bool
99
    {
100
        $route = trim($route, '/');
101
102
        foreach (self::getListOfSupportedRequestMethods() as $requestMethod) {
103
            if (isset($this->routes[$requestMethod][$route])) {
104
                return true;
105
            }
106
        }
107
108
        return false;
109
    }
110
111
    /**
112
     * Method rturns all available routes
113
     */
114
    public function getAllRoutesTrace()
115
    {
116
        $trace = [];
117
118
        foreach (self::getListOfSupportedRequestMethods() as $requestMethod) {
119
            if (count($this->routes[$requestMethod]) > 0) {
120
                $trace[] = $requestMethod . ':' . implode(', ', array_keys($this->routes[$requestMethod]));
121
            }
122
        }
123
124
        return implode('; ', $trace);
125
    }
126
127
    /**
128
     * Additing route for GET request
129
     *
130
     * @param string $route
131
     *            route
132
     * @param object $object
133
     *            callback object
134
     * @param string $method
135
     *            callback method
136
     */
137
    public function addGetRoute(string $route, object $object, string $method): void
138
    {
139
        $this->routes['GET'][trim($route, '/')] = [
140
            $object,
141
            $method
142
        ];
143
    }
144
145
    /**
146
     * Additing route for GET request
147
     *
148
     * @param string $route
149
     *            route
150
     * @param object $object
151
     *            callback object
152
     * @param string $method
153
     *            callback method
154
     */
155
    public function addPostRoute(string $route, object $object, string $method): void
156
    {
157
        $this->routes['POST'][trim($route, '/')] = [
158
            $object,
159
            $method
160
        ];
161
    }
162
163
    /**
164
     * Method registers name of the route
165
     *
166
     * @param string $routeName
167
     *            route's name
168
     * @param string $route
169
     *            route
170
     */
171
    protected function registerRouteName(string $routeName, string $route): void
172
    {
173
        if ($routeName != '') {
174
            $this->routeNames[$routeName] = $route;
175
        }
176
    }
177
178
    /**
179
     * Validating that route name exists
180
     *
181
     * @param string $routeName
182
     * @return bool
183
     */
184
    protected function routeNameExists(string $routeName): bool
185
    {
186
        return isset($this->routeNames[$routeName]);
187
    }
188
189
    /**
190
     * Getting route by name
191
     *
192
     * @param string $routeName
193
     *            route's name
194
     * @return string route
195
     */
196
    public function getRouteByName(string $routeName): string
197
    {
198
        if ($this->routeNameExists($routeName) === false) {
199
            throw (new \Exception('Route with name ' . $routeName . ' does not exist'));
200
        }
201
202
        return $this->routeNames[$routeName];
203
    }
204
205
    /**
206
     * Method dumps all routes and their names on disk
207
     *
208
     * @param string $filePath
209
     *            file path to cache
210
     * @codeCoverageIgnore
211
     */
212
    public function dumpOnDisk(string $filePath = './cache/cache.php'): void
213
    {
214
        file_put_contents(
215
            $filePath,
216
            '<?php return ' .
217
            var_export(
218
                [
219
                    0 => $this->routes,
220
                    1 => $this->routeNames,
221
                    2 => $this->cachedRegExps,
222
                    3 => $this->cachedParameters
223
                ],
224
                true) . ';');
225
    }
226
227
    /**
228
     * Method loads routes from disk
229
     *
230
     * @param string $filePath
231
     *            file path to cache
232
     * @codeCoverageIgnore
233
     */
234
    public function loadFromDisk(string $filePath = './cache/cache.php'): void
235
    {
236
        list ($this->routes, $this->routeNames, $this->cachedRegExps, $this->cachedParameters) = require ($filePath);
237
    }
238
}
239