Last active 1729620032

Details how to remove a path prefix within PSR-15 middleware

RemoveDevPrefixMiddleware.php Raw
1<?php
2
3use Interop\Http\ServerMiddleware\DelegateInterface;
4use Interop\Http\ServerMiddleware\MiddlewareInterface;
5use Psr\Http\Message\ServerRequestInterface;
6
7class RemoveDevPrefixMiddleware implements MiddlewareInterface
8{
9 private $prefix;
10
11 public function __construct(string $prefix = '/extra_directory')
12 {
13 $this->prefix = $prefix;
14 }
15
16 public function process(ServerRequestInterface $request, DelegateInterface $delegate)
17 {
18 $uri = $request->getUri();
19 $path = $uri->getPath();
20 $path = preg_replace('#^' . $this->prefix . '#', '', $path);
21
22 $uri = $uri->withPath($path);
23 return $delegate->process($request->withUri($uri));
24 }
25}
pipeline.php Raw
1<?php
2
3// Do this before piping the routing middleware
4$app->pipe('/extra_path', new RemoveDevPrefixMiddleware('/extra_path'));