Lines
100.00%
18 / 18
Methods
100.00%
1 / 1
Classes
100.00%
1 / 1
| Name | Lines | Methods | CRAP | ||||
|---|---|---|---|---|---|---|---|
| __invoke | 100.00% | 18 / 18 | 100.00% | 1 / 1 | 6 | ||
| 13 | class TrailingSlash | |
| 14 | { | |
| 15 | public function __invoke(Request $request, RequestHandlerInterface $next) | |
| 16 | { | |
| 17 | $uri = $request->getUri(); | |
| 18 | $path = $uri->getPath(); | |
| 19 | ||
| 20 | $needsTrailingSlash = substr($path, -1) !== '/' && !pathinfo($path, PATHINFO_EXTENSION); | |
| 21 | if (!$needsTrailingSlash) { | |
| 22 | return $next->handle($request); | |
| 23 | } | |
| 24 | ||
| 25 | // API paths: rewrite in-place so slashless URLs match routes defined with a trailing slash. | |
| 26 | // Do not 301 — redirects break POST and are awkward for API clients. | |
| 27 | if (strpos($path, '/api/') !== false) { | |
| 28 | return $next->handle($request->withUri($uri->withPath($path . '/'))); | |
| 29 | } | |
| 30 | ||
| 31 | // Non-API (HTML apps): permanently redirect to the trailing-slash URL. | |
| 32 | $uri = $uri->withPath($path . '/'); | |
| 33 | if ($request->hasHeader('X-Ssl') && 'no' !== $request->getHeaderLine('X-Ssl')) { | |
| 34 | $uri = $uri->withScheme('https'); | |
| 35 | $uriString = (string)$uri; | |
| 36 | } else { | |
| 37 | $uriString = preg_replace('#^https?:#', '', (string)$uri) ?? (string)$uri; //Do not force protocol | |
| 38 | } | |
| 39 | ||
| 40 | $redirects = \App::$slim->redirect( | |
| 41 | (string) $request->getUri(), | |
| 42 | $uriString, | |
| 43 | StatusCodeInterface::STATUS_MOVED_PERMANENTLY | |
| 44 | )->getCallable(); | |
| 45 | ||
| 46 | return $redirects(); | |
| 47 | } | |
| 48 | } |