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