|
1
|
|
|
<?php |
|
2
|
|
|
namespace Nubs\Which; |
|
3
|
|
|
|
|
4
|
|
|
use Nubs\Which\PathBuilder\PathBuilderInterface; |
|
5
|
|
|
|
|
6
|
|
|
/** |
|
7
|
|
|
* Provides the ability to locate commands in the user's PATH. |
|
8
|
|
|
*/ |
|
9
|
|
|
class Locator |
|
10
|
|
|
{ |
|
11
|
|
|
/** @type \Nubs\Which\PathBuilder\PathBuilderInterface The path builder. */ |
|
12
|
|
|
private $_pathBuilder; |
|
13
|
|
|
|
|
14
|
|
|
/** @type callable The executable tester. */ |
|
15
|
|
|
private $_executableTester; |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* Initialize the locator. |
|
19
|
|
|
* |
|
20
|
|
|
* @api |
|
21
|
|
|
* @param \Nubs\Which\PathBuilder\PathBuilderInterface $pathBuilder The path |
|
22
|
|
|
* builder. |
|
23
|
|
|
* @param callable $executableTester The executable tester, a callable that |
|
24
|
|
|
* is passed a file path and should return true for an executable |
|
25
|
|
|
* command, false otherwise. Defaults to the invokable |
|
26
|
|
|
* \Nubs\Which\ExecutableTester. |
|
27
|
|
|
*/ |
|
28
|
|
|
public function __construct(PathBuilderInterface $pathBuilder, callable $executableTester = null) |
|
29
|
|
|
{ |
|
30
|
|
|
$this->_pathBuilder = $pathBuilder; |
|
31
|
|
|
$this->_executableTester = $executableTester ?: new ExecutableTester(); |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* Locates the given command in the user's path. |
|
36
|
|
|
* |
|
37
|
|
|
* @api |
|
38
|
|
|
* @param string $command The command to locate. |
|
39
|
|
|
* @return string|null The full path to the command or null if not path |
|
40
|
|
|
* found. |
|
41
|
|
|
*/ |
|
42
|
|
|
public function locate($command) |
|
43
|
|
|
{ |
|
44
|
|
|
$paths = $this->locateAll($command); |
|
45
|
|
|
|
|
46
|
|
|
return empty($paths) ? null : $paths[0]; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
/** |
|
50
|
|
|
* Locates all versions of the given command in the user's path. |
|
51
|
|
|
* |
|
52
|
|
|
* @api |
|
53
|
|
|
* @param string $command The command to locate. |
|
54
|
|
|
* @return array The locations where the command exists. |
|
55
|
|
|
*/ |
|
56
|
|
|
public function locateAll($command) |
|
57
|
|
|
{ |
|
58
|
|
|
return array_values(array_filter($this->_pathBuilder->getPermutations($command), $this->_executableTester)); |
|
59
|
|
|
} |
|
60
|
|
|
} |
|
61
|
|
|
|