Completed
Push — master ( 665429...116aa7 )
by Adam
07:10
created

PathResolver::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
/**
3
 * PathResolver.php
4
 *
5
 * @copyright      More in license.md
6
 * @license        http://www.ipublikuj.eu
7
 * @author         Adam Kadlec http://www.ipublikuj.eu
8
 * @package        iPublikuj:Packages!
9
 * @subpackage     Helpers
10
 * @since          1.0.0
11
 *
12
 * @date           19.06.16
13
 */
14
15
declare(strict_types = 1);
16
17
namespace IPub\Packages\Helpers;
18
19
use Nette;
20
use Nette\Utils;
21
22
use IPub;
23
use IPub\Packages;
24
use IPub\Packages\Exceptions;
25
use IPub\Packages\Repository;
26
27
/**
28
 * Package path resolver
29
 *
30
 * @package        iPublikuj:Packages!
31
 * @subpackage     Helpers
32
 *
33
 * @author         Adam Kadlec <[email protected]>
34
 */
35 1
final class PathResolver extends Nette\Object
36
{
37
	/**
38
	 * @var Repository\IRepository
39
	 */
40
	private $repository;
41
42
	/**
43
	 * @param Repository\IRepository $repository
44
	 */
45
	public function __construct(Repository\IRepository $repository)
46
	{
47 1
		$this->repository = $repository;
48 1
	}
49
50
	/**
51
	 * Expands @foo/path/....
52
	 *
53
	 * @param string $path
54
	 * @param string|NULL $localPrefix
55
	 *
56
	 * @return string
57
	 */
58
	public function expandPath(string $path, string $localPrefix = NULL) : string
59
	{
60
		$path = Utils\Strings::replace($path, '~\\\~', '/');
61
62
		if (substr($path, 0, 1) !== '@') {
63
			return $path;
64
		}
65
66
		$pos = strpos($path, '/');
67
68
		if ($pos) {
69
			$package = substr($path, 1, $pos - 1);
70
71
		} else {
72
			$package = substr($path, 1);
73
		}
74
75
		$package = str_replace('.', '/', $package);
76
77
		if (!$this->repository->findPackage($package)) {
78
			throw new Exceptions\InvalidArgumentException(sprintf('Package \'%s\' does not exist.', $package));
79
		}
80
81
		$path = $this->repository->findPackage($package)->getPath() . ($localPrefix ? '/' . $localPrefix : '') . ($pos ? substr($path, $pos) : '');
82
83
		return Utils\Strings::replace($path, '~\\\~', '/');
84
	}
85
}
86