1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* This file is part of the "php-ipfs" package. |
7
|
|
|
* |
8
|
|
|
* (c) Robert Schönthal <[email protected]> |
9
|
|
|
* |
10
|
|
|
* For the full copyright and license information, please view the LICENSE |
11
|
|
|
* file that was distributed with this source code. |
12
|
|
|
*/ |
13
|
|
|
|
14
|
|
|
namespace IPFS\Driver; |
15
|
|
|
|
16
|
|
|
use IPFS\Command\Command; |
17
|
|
|
use IPFS\Utils\AnnotationReader; |
18
|
|
|
use IPFS\Utils\CaseFormatter; |
19
|
|
|
use Symfony\Component\Process\ProcessBuilder; |
20
|
|
|
|
21
|
|
|
class Cli implements Driver |
22
|
|
|
{ |
23
|
|
|
/** |
24
|
|
|
* @var ProcessBuilder |
25
|
|
|
*/ |
26
|
|
|
private $builder; |
27
|
|
|
/** |
28
|
|
|
* @var string |
29
|
|
|
*/ |
30
|
|
|
private $binary; |
31
|
|
|
/** |
32
|
|
|
* @var AnnotationReader |
33
|
|
|
*/ |
34
|
|
|
private $reader; |
35
|
|
|
|
36
|
2 |
|
public function __construct(ProcessBuilder $builder, AnnotationReader $reader, $binary = 'ipfs') |
37
|
|
|
{ |
38
|
2 |
|
$this->builder = $builder; |
39
|
2 |
|
$this->binary = $binary; |
40
|
2 |
|
$this->reader = $reader; |
41
|
2 |
|
} |
42
|
|
|
|
43
|
1 |
|
public function execute(Command $command) |
44
|
|
|
{ |
45
|
1 |
|
$process = $this->builder |
46
|
1 |
|
->setArguments($this->buildCommand($command)) |
47
|
1 |
|
->enableOutput() |
48
|
1 |
|
->inheritEnvironmentVariables() |
49
|
1 |
|
->setWorkingDirectory(getenv('CWD')) |
50
|
1 |
|
->getProcess() |
51
|
|
|
; |
52
|
|
|
|
53
|
1 |
|
$process->start(); |
54
|
1 |
|
$process->wait(); |
55
|
|
|
|
56
|
1 |
|
return $process->getOutput() ?: $process->getErrorOutput(); |
57
|
|
|
} |
58
|
|
|
|
59
|
1 |
|
private function buildCommand(Command $command): array |
60
|
|
|
{ |
61
|
1 |
|
return array_merge( |
62
|
1 |
|
[$this->binary], |
63
|
1 |
|
explode(':', str_replace('basics:', '', $command->getAction())), |
64
|
1 |
|
$this->parseParameters($command) |
65
|
|
|
); |
66
|
|
|
} |
67
|
|
|
|
68
|
1 |
|
private function parseParameters(Command $command): array |
69
|
|
|
{ |
70
|
1 |
|
$parameters = $this->reader->getParameters($command->getMethod()); |
71
|
|
|
|
72
|
1 |
|
$parsedParameters = []; |
73
|
|
|
|
74
|
1 |
|
foreach ($command->getArguments() as $name => $value) { |
75
|
1 |
|
if ($parameters[$name]->hasDefault() && $parameters[$name]->getDefault() !== $value) { |
76
|
1 |
|
$parsedParameters[] = sprintf('--%s=%s', CaseFormatter::camelToDash($name), var_export($value, true)); |
77
|
1 |
|
continue; |
78
|
|
|
} |
79
|
|
|
|
80
|
1 |
|
if (!$parameters[$name]->hasDefault()) { |
81
|
1 |
|
$parsedParameters[] = $value; |
82
|
1 |
|
continue; |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
throw new \LogicException(sprintf('"%s" is neither an option nor an argument', $name)); |
86
|
|
|
} |
87
|
|
|
|
88
|
1 |
|
return $parsedParameters; |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|