BuildCommand::exec()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 25
rs 9.52
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
namespace App\Satis;
4
5
use App\Satis\Context\AsyncCommand;
6
use App\Satis\Context\SyncCommand;
7
use App\Satis\Exceptions\PackageBuildFailedException;
8
use App\Satis\Model\Repository;
9
use Illuminate\Support\Collection;
10
use Monolog\Logger;
11
12
/**
13
 * @author Lukas Homza <[email protected]>
14
 */
15
class BuildCommand {
16
    /** @var BuildContext $buildContext */
17
    protected $buildContext;
18
19
    /** @var string $executable */
20
    protected $executable = 'bin%ssatis';
21
22
    /** @var string $command */
23
    protected $command = 'build';
24
25
    /** @var string $configPath */
26
    protected $configPath;
27
28
    /** @var string $configPath */
29
    protected $buildDirectory;
30
31
    /** @var \Illuminate\Support\Collection $proxySettings */
32
    protected $proxySettings;
33
34
    /** @var string $item */
35
    protected $item;
36
37
    /** @var string $directory */
38
    protected $directory;
39
40
    /** @var string $currentDirectory */
41
    protected $currentDirectory;
42
43
    /** @var \Monolog\Logger $logger */
44
    protected $logger;
45
46
    /** @var string $logFile */
47
    protected $logFile;
48
49
    /** @var array $commandOutput */
50
    protected $commandOutput = [];
51
52
    /**
53
     * @param CommandContextInterface $commandContext
54
     * @return Collection
55
     */
56
    protected function compile(CommandContextInterface $commandContext) {
57
        $this->logFile = storage_path('logs/async/' . (string) round(microtime(true) * 1000) .
58
            mt_rand(1, 10000) . '.log');
59
60
        $memoryLimit = config('satis.memory_limit');
61
        $buildVerbosity = config('satis.build_verbosity');
62
63
        $chunks = new Collection([
64
            'php' . ($memoryLimit !== null ? ' -dmemory_limit=' . $memoryLimit : ''),
65
            sprintf($this->executable, DIRECTORY_SEPARATOR),
66
            $this->command . ($buildVerbosity !== null ? ' -' . $buildVerbosity : ''),
67
            $this->configPath,
68
            $this->buildDirectory
69
        ]);
70
71
        if($this->item !== null) {
72
            $chunks->push($this->item);
73
        }
74
75
        $chunks->push($commandContext->getOutputRedirection($this->logFile));
76
        $chunks->push($commandContext->getShouldUnlockOnCompletion());
77
78
        foreach(['http', 'https'] as $protocol) {
79
            $proxy = $this->proxySettings->get($protocol);
80
            if($proxy !== null) {
81
                $chunks->prepend(strtoupper($protocol) . '_PROXY=' . $proxy);
82
            }
83
        }
84
85
        $chunks->reject(function($commandChunk) {
86
            return trim($commandChunk) === '';
87
        });
88
89
        return $chunks;
90
    }
91
92
    /**
93
     * @return \Monolog\Logger
94
     */
95
    protected function getLogger() {
96
        return \Log::getMonolog();
97
    }
98
99
    /**
100
     * @return bool
101
     */
102
    protected function isWindows() {
103
        return PHP_OS === 'WINNT' || PHP_OS === 'WIN32';
104
    }
105
106
    /**
107
     * @param CommandContextInterface $commandContext
108
     * @return mixed
109
     */
110
    protected function exec(CommandContextInterface $commandContext) {
111
        $commandChunks = $this->compile($commandContext);
112
        $logger = $commandContext->getLogger();
113
114
        $logger->info(str_repeat('=', 30));
115
        $logger->info('Running command => ' . PHP_EOL . $commandChunks->implode(' '));
116
117
        chdir($this->directory);
118
119
        exec($commandChunks->implode(' '), $output, $result);
120
121
        chdir($this->currentDirectory);
122
123
        if($commandContext instanceof SyncCommand) {
124
            $logger->info('Command output => ' . implode(PHP_EOL, $output));
125
        } else {
126
            $logger->notice('Command output can be found in "' . $this->logFile . '".');
127
        }
128
129
        $this->setCommandOutput($output);
130
131
        $logger->info(str_repeat('=', 30));
132
133
        return $result;
134
    }
135
136
    /**
137
     * @param mixed $commandOutput
138
     * @return BuildCommand
139
     */
140
    protected function setCommandOutput($commandOutput) {
141
        $this->commandOutput = $commandOutput;
0 ignored issues
show
Documentation Bug introduced by
It seems like $commandOutput of type * is incompatible with the declared type array of property $commandOutput.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
142
143
        return $this;
144
    }
145
146
    /**
147
     * BuildCommand constructor.
148
     * @param string $configPath
149
     * @param string $buildDirectory
150
     * @param array $proxySettings
151
     */
152
    public function __construct($configPath, $buildDirectory, array $proxySettings = array()) {
153
        $this->configPath = escapeshellarg($configPath);
154
        $this->buildDirectory = escapeshellarg($buildDirectory);
155
        $this->proxySettings = new Collection($proxySettings);
156
    }
157
158
    /**
159
     * @param \App\Satis\BuildContext $buildContext
160
     * @return $this
161
     */
162
    public function setContext(BuildContext $buildContext) {
163
        $this->buildContext = $buildContext;
164
165
        return $this;
166
    }
167
168
    /**
169
     * @param string $item
170
     */
171
    public function setItem($item) {
172
        if($item === null) {
173
            return;
174
        }
175
176
        if(preg_match(Repository::REGEX, $item)) {
177
            $this->item = '--repository-url ' . escapeshellarg($item);
178
        } else {
179
            $this->item = escapeshellarg($item);
180
        }
181
    }
182
183
    /**
184
     * @param \Monolog\Logger $logger
185
     * @return BuildCommand
186
     */
187
    public function setLogger(Logger $logger) {
188
        $this->logger = $logger;
189
190
        return $this;
191
    }
192
193
    /**
194
     * @param string $directory
195
     * @return BuildCommand
196
     */
197
    public function withCd($directory) {
198
        $this->directory = $directory;
199
        $this->currentDirectory = getcwd();
200
201
        return $this;
202
    }
203
204
    /**
205
     * @param bool $asyncMode
206
     * @return bool
207
     * @throws PackageBuildFailedException
208
     */
209
    public function run($asyncMode = true) {
210
        # -- force sync
211
        #if(true) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
84% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
212
        if($asyncMode === false || $this->isWindows() === true) {
213
            if($this->isWindows() === true) {
214
                $this->getLogger()
215
                    ->warn('OS does not support async mode, forcing sync.');
216
            }
217
218
            return $this->runSync();
219
        }
220
221
        $this->exec(new AsyncCommand());
222
223
        return true;
224
    }
225
226
    /**
227
     * @return bool
228
     * @throws PackageBuildFailedException
229
     */
230
    public function runSync() {
231
        set_time_limit(config('satis.sync_timeout'));
232
233
        $result = $this->exec(new SyncCommand());
234
235
        if($result !== 0) {
236
            throw new PackageBuildFailedException('Package build failed. Check build log for details.');
237
        }
238
239
        return $this->commandOutput;
240
    }
241
}
242