Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
46.67% covered (danger)
46.67%
7 / 15
0.00% covered (danger)
0.00%
0 / 5
CRAP
0.00% covered (danger)
0.00%
0 / 1
PathPrefixer
46.67% covered (danger)
46.67%
7 / 15
0.00% covered (danger)
0.00%
0 / 5
29.36
0.00% covered (danger)
0.00%
0 / 1
 __construct
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
4.07
 prefixPath
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 stripPrefix
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 stripDirectoryPrefix
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 prefixDirectoryPath
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
1<?php
2
3declare(strict_types=1);
4
5namespace BrianHenryIE\Strauss\Helpers;
6
7use function rtrim;
8use function strlen;
9use function substr;
10
11class PathPrefixer
12{
13    /**
14     * @var string
15     */
16    private $prefix = '';
17
18    /**
19     * @var string
20     */
21    private string $separator = '/';
22
23    public function __construct(string $prefix, string $separator = '/')
24    {
25        $this->prefix = in_array(substr($prefix, -1), ['\\','/'])
26            ? substr($prefix, 0, -1)
27            : $prefix;
28
29        if ($this->prefix !== '' || $prefix === $separator) {
30            $this->prefix .= $separator;
31        }
32
33        $this->separator = $separator;
34    }
35
36    public function prefixPath(string $path): string
37    {
38        return str_starts_with($path, $this->prefix)
39            ? $path
40            : $this->prefix . ltrim($path, '\\/');
41    }
42
43    public function stripPrefix(string $path): string
44    {
45        /* @var string */
46        return substr($path, strlen($this->prefix));
47    }
48
49    public function stripDirectoryPrefix(string $path): string
50    {
51        return rtrim($this->stripPrefix($path), '\\/');
52    }
53
54    public function prefixDirectoryPath(string $path): string
55    {
56        $prefixedPath = $this->prefixPath(rtrim($path, '\\/'));
57
58        if ((substr($prefixedPath, -1) === $this->separator) || $prefixedPath === '') {
59            return $prefixedPath;
60        }
61
62        return $prefixedPath . $this->separator;
63    }
64}