3 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
6 * Galette Slim middleware to handle trailing slash in URLs
10 * Copyright © 2020 The Galette Team
12 * This file is part of Galette (http://galette.tuxfamily.org).
14 * Galette is free software: you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation, either version 3 of the License, or
17 * (at your option) any later version.
19 * Galette is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
24 * You should have received a copy of the GNU General Public License
25 * along with Galette. If not, see <http://www.gnu.org/licenses/>.
30 * @author Johan Cwiklinski <johan@x-tnd.be>
31 * @copyright 2020 The Galette Team
32 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
33 * @link http://galette.tuxfamily.org
34 * @since Available since 0.9.4dev - 2020-05-06
37 namespace Galette\Middleware
;
39 use Psr\Http\Message\ServerRequestInterface
as Request
;
40 use Psr\Http\Message\ResponseInterface
as Response
;
43 * Galette Slim middleware to handle trailing slash in URLs
45 * @category Middleware
48 * @author Johan Cwiklinski <johan@x-tnd.be>
49 * @copyright 2020 The Galette Team
50 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
51 * @link http://galette.tuxfamily.org
52 * @since Available since 0.9.4dev - 2020-05-06
57 * Middleware invokable class
59 * @param \Psr\Http\Message\ServerRequestInterface $request PSR7 request
60 * @param \Psr\Http\Message\ResponseInterface $response PSR7 response
61 * @param callable $next Next middleware
63 * @return \Psr\Http\Message\ResponseInterface
65 public function __invoke(Request
$request, Response
$response, $next): Response
67 $uri = $request->getUri();
68 $path = $uri->getPath();
69 if ($path != '/' && substr($path, -1) == '/') {
70 // permanently redirect paths with a trailing slash
71 // to their non-trailing counterpart
72 $uri = $uri->withPath(substr($path, 0, -1));
74 if ($request->getMethod() == 'GET') {
75 return $response->withRedirect((string)$uri, 301);
77 return $next($request->withUri($uri), $response);
81 return $next($request, $response);