Lines
100.00%
18 / 18
Functions and Methods
100.00%
1 / 1
Classes and Traits
100.00%
1 / 1
| Name | Lines | Functions and Methods | CRAP | Classes and Traits | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| TrailingSlash | 100.00% | 18 / 18 | 100.00% | 1 / 1 | 6 | 100.00% | 1 / 1 | |||
| __invoke | 100.00% | 18 / 18 | 100.00% | 1 / 1 | 6 | |||||
| 1 | <?php | |
| 2 | ||
| 3 | /** | |
| 4 | * @copyright BerlinOnline Stadtportal GmbH & Co. KG | |
| 5 | **/ | |
| 6 | ||
| 7 | namespace BO\Slim\Middleware; | |
| 8 | ||
| 9 | use Fig\Http\Message\StatusCodeInterface; | |
| 10 | use Psr\Http\Message\ServerRequestInterface as Request; | |
| 11 | use Psr\Http\Server\RequestHandlerInterface; | |
| 12 | ||
| 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 | } |