SiteProcess::addEnvVars()   A
last analyzed

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
        // Symfony 4 REQUIRES that there be a directory set, and defaults
86
        // it to the cwd if it is not set. We will maintain that pattern here.
87
        if (!$cd) {
88
            $cd = getcwd();
89
        }
90
        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...
91
    }
92
93
    /**
94
     * Get the starting directory for the initial/local process.
95
     *
96
     * @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...
97
     */
98
    public function getWorkingDirectoryLocal()
99
    {
100
        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...
101
    }
102
103
    /**
104
     *
105
     * @param bool $shouldUseSiteRoot
106
     * @return $this|\Symfony\Component\Process\Process
107
     * @throws \Exception
108
     */
109
    public function chdirToSiteRoot($shouldUseSiteRoot = true)
110
    {
111
        if (!$shouldUseSiteRoot || !$this->siteAlias->hasRoot()) {
112
            return $this;
113
        }
114
115
        return $this->setWorkingDirectory($this->siteAlias->root());
116
    }
117
118
    /**
119
     * Take all of our individual arguments and process them for use.
120
     */
121
    protected function processArgs()
122
    {
123
        $transport = $this->getTransport($this->siteAlias);
124
        $transport->configure($this);
125
126
        $processor = new ArgumentProcessor();
127
        $selectedArgs = $processor->selectArgs(
128
            $this->siteAlias,
129
            $this->args,
130
            $this->options,
131
            $this->optionsPassedAsArgs
132
        );
133
134
        // Set environment variables if needed.
135
        if ($this->siteAlias->has('env-vars')) {
136
            $selectedArgs = $this->addEnvVars($this->siteAlias->get('env-vars'), $selectedArgs);
137
        }
138
139
        // Ask the transport to drop in a 'cd' if needed.
140
        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...
141
            $selectedArgs = $transport->addChdir($this->getWorkingDirectory(), $selectedArgs);
142
        }
143
144
        // Do any necessary interpolation on the selected arguments.
145
        $processedArgs = $this->interpolate($selectedArgs);
146
147
        // Wrap the command with 'ssh' or some other transport if this is
148
        // a remote command; otherwise, leave it as-is.
149
        return $transport->wrap($processedArgs);
150
    }
151
152
    /**
153
     * Wrap the command/args in an env call.
154
     * @todo Check if this needs to depend on linux/win.
155
     * @todo Check if this needs to be delegated to transport.
156
     */
157
    public function addEnvVars($envVars, $args)
158
    {
159
        $envArgs = ['env'];
160
        foreach ($envVars as $key => $value) {
161
            $envArgs[] = Escape::forSite($this->siteAlias, $key) . '='
162
            . Escape::forSite($this->siteAlias, $value);
163
        }
164
        return array_merge($envArgs, $args);
165
    }
166
167
    public function setTransport($transport)
168
    {
169
        $this->transport = $transport;
170
    }
171
172
    /**
173
     * Ask the transport manager for the correct transport for the
174
     * provided alias.
175
     */
176
    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...
177
    {
178
        return $this->transport;
179
    }
180
181
    /**
182
     * @inheritDoc
183
     */
184
    public function getCommandLine()
185
    {
186
        $commandLine = parent::getCommandLine();
187
        if (empty($commandLine)) {
188
            $processedArgs = $this->processArgs();
189
            $commandLine = Escape::argsForSite($this->siteAlias, $processedArgs);
190
            $commandLine = implode(' ', $commandLine);
191
            $this->setCommandLine($commandLine);
0 ignored issues
show
Deprecated Code introduced by
The method Symfony\Component\Proces...ocess::setCommandLine() has been deprecated with message: since Symfony 4.2.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
192
        }
193
        return $commandLine;
194
    }
195
196
    /**
197
     * @inheritDoc
198
     */
199
    public function start(callable $callback = null, array $env = [])
200
    {
201
        $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...
202
        parent::start($callback, $env);
203
    }
204
205
    /**
206
     * @inheritDoc
207
     */
208
    public function wait(callable $callback = null)
209
    {
210
        $return = parent::wait($callback);
211
        return $return;
212
    }
213
214
    /**
215
     * interpolate examines each of the arguments in the provided argument list
216
     * and replaces any token found therein with the value for that key as
217
     * pulled from the given site alias.
218
     *
219
     * Example: "git -C {{root}} status"
220
     *
221
     * The token "{{root}}" will be converted to a value via $siteAlias->get('root').
222
     * The result will replace the token.
223
     *
224
     * It is possible to use dot notation in the keys to access nested elements
225
     * within the site alias record.
226
     *
227
     * @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...
228
     * @param type $args
229
     * @return type
230
     */
231
    protected function interpolate($args)
232
    {
233
        $interpolator = new Interpolator();
234
        return array_map(
235
            function ($arg) use ($interpolator) {
236
                if ($arg instanceof ShellOperatorInterface) {
237
                    return $arg;
238
                }
239
                return $interpolator->interpolate($this->siteAlias, $arg, false);
240
            },
241
            $args
242
        );
243
    }
244
}
245