Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
94.29% covered (success)
94.29%
33 / 35
0.00% covered (danger)
0.00%
0 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
StripFsRootPathNormalizer
94.29% covered (success)
94.29%
33 / 35
0.00% covered (danger)
0.00%
0 / 2
5.00
0.00% covered (danger)
0.00%
0 / 1
 __construct
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
3.07
 normalizePath
96.67% covered (success)
96.67%
29 / 30
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2
3namespace BrianHenryIE\Strauss\Helpers\Flysystem;
4
5use Composer\Util\Platform;
6use League\Flysystem\PathNormalizer;
7use League\Flysystem\WhitespacePathNormalizer;
8
9class StripFsRootPathNormalizer implements PathNormalizer
10{
11    /**
12     * @var string[]|null
13     */
14    private ?array $fsRoots;
15
16    private ?PathNormalizer $delegateNormalizer;
17
18    /**
19     * @param string|string[]|null $fsRoots
20     */
21    public function __construct(
22        $fsRoots = null,
23        ?PathNormalizer $delegateNormalizer = null
24    ) {
25        $this->fsRoots = is_string($fsRoots)
26            ? [ $fsRoots ]
27            : $fsRoots;
28        $this->delegateNormalizer = $delegateNormalizer
29            ?: new WhitespacePathNormalizer();
30    }
31
32    public function normalizePath(string $path): string
33    {
34        $fsRoots = array_unique(
35            $this->fsRoots ??
36                  [
37                      FileSystem::getFsRoot(Platform::getCwd()),
38                      FileSystem::normalizeDirSeparator(FileSystem::getFsRoot(Platform::getCwd())),
39                      'c:\\',
40                      'c:/',
41                   ]
42        );
43
44        $pattern = '^(' . implode(
45            '|',
46            array_map(
47                fn($str) => str_replace(
48                    '\\',
49                    '\\\\',
50                    str_replace(
51                        '\/',
52                        '\\\/',
53                        $str
54                    )
55                ),
56                $fsRoots
57            )
58        ) . ')';
59        $path   = preg_replace("#" . $pattern . "#i", '', $path)
60                  ?? (function () {
61                    throw new \Exception(preg_last_error_msg(), preg_last_error());
62                  })();
63
64        if ($this->delegateNormalizer !== null) {
65            $path = $this->delegateNormalizer->normalizePath($path);
66        }
67
68        return $path;
69    }
70}