Completed
Pull Request — master (#47)
by
unknown
01:10
created

SiteProcess::addEnvVars()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
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
        $envArgs = ['env'];
154
        foreach ($envVars as $key => $value) {
155
            $envArgs[] = Escape::forSite($this->siteAlias, $key) . '='
156
            . Escape::forSite($this->siteAlias, $value);
157
        }
158
        return array_merge($envArgs, $args);
159
    }
160
161
    public function setTransport($transport)
162
    {
163
        $this->transport = $transport;
164
    }
165
166
    /**
167
     * Ask the transport manager for the correct transport for the
168
     * provided alias.
169
     */
170
    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...
171
    {
172
        return $this->transport;
173
    }
174
175
    /**
176
     * @inheritDoc
177
     */
178
    public function getCommandLine()
179
    {
180
        $commandLine = parent::getCommandLine();
181
        if (empty($commandLine)) {
182
            $processedArgs = $this->processArgs();
183
            $commandLine = Escape::argsForSite($this->siteAlias, $processedArgs);
184
            $commandLine = implode(' ', $commandLine);
185
            $this->setCommandLine($commandLine);
186
        }
187
        return $commandLine;
188
    }
189
190
    /**
191
     * @inheritDoc
192
     */
193
    public function start(callable $callback = null, $env = array())
194
    {
195
        $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...
196
        parent::start($callback, $env);
197
    }
198
199
    /**
200
     * @inheritDoc
201
     */
202
    public function wait(callable $callback = null)
203
    {
204
        $return = parent::wait($callback);
205
        return $return;
206
    }
207
208
    /**
209
     * interpolate examines each of the arguments in the provided argument list
210
     * and replaces any token found therein with the value for that key as
211
     * pulled from the given site alias.
212
     *
213
     * Example: "git -C {{root}} status"
214
     *
215
     * The token "{{root}}" will be converted to a value via $siteAlias->get('root').
216
     * The result will replace the token.
217
     *
218
     * It is possible to use dot notation in the keys to access nested elements
219
     * within the site alias record.
220
     *
221
     * @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...
222
     * @param type $args
223
     * @return type
224
     */
225
    protected function interpolate($args)
226
    {
227
        $interpolator = new Interpolator();
228
        return array_map(
229
            function ($arg) use ($interpolator) {
230
                if ($arg instanceof ShellOperatorInterface) {
231
                    return $arg;
232
                }
233
                return $interpolator->interpolate($this->siteAlias, $arg, false);
234
            },
235
            $args
236
        );
237
    }
238
}
239