Completed
Push — master ( 44a12f...3116f6 )
by Greg
01:35
created

SiteProcess::addEnvVars()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.9666
c 0
b 0
f 0
cc 2
nc 2
nop 2
1
<?php
2
namespace Consolidation\SiteProcess;
3
4
use Consolidation\SiteAlias\SiteAliasInterface;
5
use Consolidation\SiteProcess\Transport\DockerComposeTransport;
6
use Consolidation\SiteProcess\Util\ArgumentProcessor;
7
use Consolidation\SiteProcess\Transport\LocalTransport;
8
use Consolidation\SiteProcess\Transport\SshTransport;
9
use Consolidation\SiteProcess\Transport\TransportInterface;
10
use Consolidation\Config\Util\Interpolator;
11
use Consolidation\SiteProcess\Util\Shell;
12
use Consolidation\SiteProcess\Util\ShellOperatorInterface;
13
use Consolidation\SiteProcess\Util\Escape;
14
15
/**
16
 * A wrapper around Symfony Process that uses site aliases
17
 * (https://github.com/consolidation/site-alias)
18
 *
19
 * - Interpolate arguments using values from the alias
20
 *   e.g. `$process = new SiteProcess($alias, ['git', '-C', '{{root}}']);`
21
 * - Make remote calls via ssh as if they were local.
22
 */
23
class SiteProcess extends ProcessBase
24
{
25
    /** @var SiteAliasInterface */
26
    protected $siteAlias;
27
    /** @var string[] */
28
    protected $args;
29
    /** @var string[] */
30
    protected $options;
31
    /** @var string[] */
32
    protected $optionsPassedAsArgs;
33
    /** @var string */
34
    protected $cd_remote;
35
    /** @var TransportInterface */
36
    protected $transport;
37
38
    /**
39
     * Process arguments and options per the site alias and build the
40
     * actual command to run.
41
     */
42
    public function __construct(SiteAliasInterface $siteAlias, TransportInterface $transport, $args, $options = [], $optionsPassedAsArgs = [])
43
    {
44
        $this->siteAlias = $siteAlias;
45
        $this->transport = $transport;
46
        $this->args = $args;
47
        $this->options = $options;
48
        $this->optionsPassedAsArgs = $optionsPassedAsArgs;
49
50
        parent::__construct([]);
51
    }
52
53
    /**
54
     * Get a starting directory for the remote process.
55
     *
56
     * @return string|null
57
     */
58
    public function getWorkingDirectory()
59
    {
60
        return $this->cd_remote;
61
    }
62
63
    /**
64
     * Set a starting directory for the remote process.
65
     *
66
     * @param string $cd_remote
67
     *
68
     * @return \Consolidation\SiteProcess\SiteProcess
69
     */
70
    public function setWorkingDirectory($cd_remote)
71
    {
72
        $this->cd_remote = $cd_remote;
73
        return $this;
74
    }
75
76
    /**
77
     * Set a starting directory for the initial/local process.
78
     *
79
     * @param string $cd
80
     *
81
     * @return \Consolidation\SiteProcess\SiteProcess
82
     */
83
    public function setWorkingDirectoryLocal($cd)
84
    {
85
        return parent::setWorkingDirectory($cd);
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (setWorkingDirectory() instead of setWorkingDirectoryLocal()). Are you sure this is correct? If so, you might want to change this to $this->setWorkingDirectory().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
86
    }
87
88
    /**
89
     * Get the starting directory for the initial/local process.
90
     *
91
     * @return string|null;
0 ignored issues
show
Documentation introduced by
The doc-type string|null; could not be parsed: Expected "|" or "end of type", but got ";" at position 11. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
92
     */
93
    public function getWorkingDirectoryLocal()
94
    {
95
        return parent::getWorkingDirectory();
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (getWorkingDirectory() instead of getWorkingDirectoryLocal()). Are you sure this is correct? If so, you might want to change this to $this->getWorkingDirectory().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
96
    }
97
98
    /**
99
     *
100
     * @param bool $shouldUseSiteRoot
101
     * @return $this|\Symfony\Component\Process\Process
102
     * @throws \Exception
103
     */
104
    public function chdirToSiteRoot($shouldUseSiteRoot = true)
105
    {
106
        if (!$shouldUseSiteRoot || !$this->siteAlias->hasRoot()) {
107
            return $this;
108
        }
109
110
        return $this->setWorkingDirectory($this->siteAlias->root());
111
    }
112
113
    /**
114
     * Take all of our individual arguments and process them for use.
115
     */
116
    protected function processArgs()
117
    {
118
        $transport = $this->getTransport($this->siteAlias);
119
        $transport->configure($this);
120
121
        $processor = new ArgumentProcessor();
122
        $selectedArgs = $processor->selectArgs(
123
            $this->siteAlias,
124
            $this->args,
125
            $this->options,
126
            $this->optionsPassedAsArgs
127
        );
128
129
        // Set environment variables if needed.
130
        if ($this->siteAlias->has('env-vars')) {
131
            $selectedArgs = $this->addEnvVars($this->siteAlias->get('env-vars'), $selectedArgs);
132
        }
133
134
        // Ask the transport to drop in a 'cd' if needed.
135
        if ($this->getWorkingDirectory()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->getWorkingDirectory() of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
136
            $selectedArgs = $transport->addChdir($this->getWorkingDirectory(), $selectedArgs);
137
        }
138
139
        // Do any necessary interpolation on the selected arguments.
140
        $processedArgs = $this->interpolate($selectedArgs);
141
142
        // Wrap the command with 'ssh' or some other transport if this is
143
        // a remote command; otherwise, leave it as-is.
144
        return $transport->wrap($processedArgs);
145
    }
146
147
    /**
148
     * Wrap the command/args in an env call.
149
     * @todo Check if this needs to depend on linux/win.
150
     * @todo Check if this needs to be delegated to transport.
151
     */
152
    public function addEnvVars($envVars, $args)
153
    {
154
        $envArgs = ['env'];
155
        foreach ($envVars as $key => $value) {
156
            $envArgs[] = Escape::forSite($this->siteAlias, $key) . '='
157
            . Escape::forSite($this->siteAlias, $value);
158
        }
159
        return array_merge($envArgs, $args);
160
    }
161
162
    public function setTransport($transport)
163
    {
164
        $this->transport = $transport;
165
    }
166
167
    /**
168
     * Ask the transport manager for the correct transport for the
169
     * provided alias.
170
     */
171
    protected function getTransport(SiteAliasInterface $siteAlias)
0 ignored issues
show
Unused Code introduced by
The parameter $siteAlias is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
172
    {
173
        return $this->transport;
174
    }
175
176
    /**
177
     * @inheritDoc
178
     */
179
    public function getCommandLine()
180
    {
181
        $commandLine = parent::getCommandLine();
182
        if (empty($commandLine)) {
183
            $processedArgs = $this->processArgs();
184
            $commandLine = Escape::argsForSite($this->siteAlias, $processedArgs);
185
            $commandLine = implode(' ', $commandLine);
186
            $this->setCommandLine($commandLine);
187
        }
188
        return $commandLine;
189
    }
190
191
    /**
192
     * @inheritDoc
193
     */
194
    public function start(callable $callback = null, $env = array())
195
    {
196
        $cmd = $this->getCommandLine();
0 ignored issues
show
Unused Code introduced by
$cmd is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
197
        parent::start($callback, $env);
198
    }
199
200
    /**
201
     * @inheritDoc
202
     */
203
    public function wait(callable $callback = null)
204
    {
205
        $return = parent::wait($callback);
206
        return $return;
207
    }
208
209
    /**
210
     * interpolate examines each of the arguments in the provided argument list
211
     * and replaces any token found therein with the value for that key as
212
     * pulled from the given site alias.
213
     *
214
     * Example: "git -C {{root}} status"
215
     *
216
     * The token "{{root}}" will be converted to a value via $siteAlias->get('root').
217
     * The result will replace the token.
218
     *
219
     * It is possible to use dot notation in the keys to access nested elements
220
     * within the site alias record.
221
     *
222
     * @param SiteAliasInterface $siteAlias
0 ignored issues
show
Bug introduced by
There is no parameter named $siteAlias. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
223
     * @param type $args
224
     * @return type
225
     */
226
    protected function interpolate($args)
227
    {
228
        $interpolator = new Interpolator();
229
        return array_map(
230
            function ($arg) use ($interpolator) {
231
                if ($arg instanceof ShellOperatorInterface) {
232
                    return $arg;
233
                }
234
                return $interpolator->interpolate($this->siteAlias, $arg, false);
235
            },
236
            $args
237
        );
238
    }
239
}
240