Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
82.35% covered (warning)
82.35%
14 / 17
0.00% covered (danger)
0.00%
0 / 1
CRAP
0.00% covered (danger)
0.00%
0 / 1
TrailingSlash
82.35% covered (warning)
82.35%
14 / 17
0.00% covered (danger)
0.00%
0 / 1
6.20
0.00% covered (danger)
0.00%
0 / 1
 __invoke
82.35% covered (warning)
82.35%
14 / 17
0.00% covered (danger)
0.00%
0 / 1
6.20
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        if (strpos($path, '/api/') !== false) {
21            return $next->handle($request);
22        }
23
24        if (substr($path, -1) !== '/' && !pathinfo($path, PATHINFO_EXTENSION)) {
25            // permanently redirect paths without a trailing slash
26            // to their trailing counterpart
27            $uri = $uri->withPath($path . '/');
28            if ($request->getHeader('X-Ssl') && 'no' != $request->getHeader('X-Ssl')) {
29                $uri = $uri->withScheme('https');
30                $uriString = (string)$uri;
31            } else {
32                $uriString = preg_replace('#^https?:#', '', (string)$uri); //Do not force protocol
33            }
34
35            $redirects = \App::$slim->redirect(
36                (string) $request->getUri(),
37                $uriString,
38                StatusCodeInterface::STATUS_MOVED_PERMANENTLY
39            )->getCallable();
40
41            return $redirects();
42        }
43
44        return $next->handle($request);
45    }
46}