Passed
Push — master ( a54d29...9106cd )
by Alexander
02:52
created

SubFolderMiddleware   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 27
c 1
b 0
f 0
dl 0
loc 45
rs 10
wmc 8

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B process() 0 33 7
1
<?php
2
3
namespace Yiisoft\Yii\Web\Middleware;
4
5
use Psr\Http\Message\ResponseInterface;
6
use Psr\Http\Message\ServerRequestInterface;
7
use Psr\Http\Server\MiddlewareInterface;
8
use Psr\Http\Server\RequestHandlerInterface;
9
use Yiisoft\Aliases\Aliases;
10
use Yiisoft\Router\UrlGeneratorInterface;
11
use Yiisoft\Yii\Web\Exception\BadUriPrefixException;
12
13
/**
14
 * This middleware supports routing when webroot is not the same folder as public
15
 */
16
final class SubFolderMiddleware implements MiddlewareInterface
17
{
18
    public ?string $prefix = null;
19
    private UrlGeneratorInterface $uriGenerator;
20
    private Aliases $aliases;
21
22
    public function __construct(UrlGeneratorInterface $uriGenerator, Aliases $aliases)
23
    {
24
        $this->uriGenerator = $uriGenerator;
25
        $this->aliases = $aliases;
26
    }
27
28
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
29
    {
30
        $uri = $request->getUri();
31
        $path = $uri->getPath();
32
33
        if ($this->prefix === null) {
34
            // automatically check that the project is in a subfolder
35
            // and uri contain a prefix
36
            $scriptName = $request->getServerParams()['SCRIPT_NAME'];
37
            if (strpos($scriptName, '/', 1) !== false) {
38
                $length = strrpos($scriptName, '/');
39
                $prefix = substr($scriptName, 0, $length);
40
                if (strpos($path, $prefix) === 0) {
41
                    $this->prefix = $prefix;
42
                    $this->uriGenerator->setUriPrefix($prefix);
43
                    $request = $request->withUri($uri->withPath(substr($path, $length)));
44
                }
45
            }
46
        } elseif ($this->prefix !== '') {
47
            if ($this->prefix[-1] === '/') {
48
                throw new BadUriPrefixException('Wrong URI prefix value');
49
            }
50
            $length = strlen($this->prefix);
51
            if (strpos($path, $this->prefix) !== 0) {
52
                throw new BadUriPrefixException('URI prefix does not match');
53
            }
54
            $this->uriGenerator->setUriPrefix($this->prefix);
55
            $request = $request->withUri($uri->withPath(substr($path, $length)));
56
        }
57
        // rewrite alias
58
        $this->aliases->set('@web', $this->prefix . '/');
59
60
        return $handler->handle($request);
61
    }
62
}
63