Completed
Pull Request — stable (#365)
by
unknown
04:50
created

BuildCommand::getBinary()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * This file is part of Laravel Zero.
7
 *
8
 * (c) Nuno Maduro <[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 LaravelZero\Framework\Commands;
15
16
use Illuminate\Console\Application as Artisan;
17
use Illuminate\Support\Facades\File;
18
use Symfony\Component\Console\Helper\ProgressBar;
19
use Symfony\Component\Console\Input\InputInterface;
20
use Symfony\Component\Console\Output\NullOutput;
21
use Symfony\Component\Console\Output\OutputInterface;
22
use Symfony\Component\Process\Process;
23
24
final class BuildCommand extends Command
25
{
26
    /**
27
     * {@inheritdoc}
28
     */
29
    protected $signature = 'app:build
30
                            {name? : The build name}
31
                            {--build-version= : The build version, if not provided it will be asked}
32
                            {--timeout=300 : The timeout in seconds or 0 to disable}';
33
34
    /**
35
     * {@inheritdoc}
36
     */
37
    protected $description = 'Build a single file executable';
38
39
    /**
40
     * Holds the configuration on is original state.
41
     *
42
     * @var string|null
43
     */
44
    private static $config;
45
46
    /**
47
     * Holds the box.json on is original state.
48
     *
49
     * @var string|null
50
     */
51
    private static $box;
52
53
    /**
54
     * Holds the command original output.
55
     *
56
     * @var \Symfony\Component\Console\Output\OutputInterface
57
     */
58
    private $originalOutput;
59
60
    /**
61
     * {@inheritdoc}
62
     */
63 2
    public function handle()
64
    {
65 2
        pcntl_async_signals(true);
66
67
        pcntl_signal(SIGINT, function () {
68
            if (static::$config !== null) {
0 ignored issues
show
Bug introduced by
Since $config is declared private, accessing it with static will lead to errors in possible sub-classes; you can either use self, or increase the visibility of $config to at least protected.
Loading history...
69
                $this->clear();
70
            }
71
72
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
73 2
        });
74
75 2
        $this->title('Building process');
76
77 2
        $this->build($this->input->getArgument('name') ?? $this->getBinary());
0 ignored issues
show
Bug introduced by
It seems like $this->input->getArgumen...) ?? $this->getBinary() can also be of type string[]; however, parameter $name of LaravelZero\Framework\Co...s\BuildCommand::build() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

77
        $this->build(/** @scrutinizer ignore-type */ $this->input->getArgument('name') ?? $this->getBinary());
Loading history...
78 1
    }
79
80
    /**
81
     * {@inheritdoc}
82
     */
83 2
    public function run(InputInterface $input, OutputInterface $output)
84
    {
85 2
        parent::run($input, $this->originalOutput = $output);
86 1
    }
87
88
    /**
89
     * Builds the application into a single file.
90
     */
91 2
    private function build(string $name): BuildCommand
92
    {
93
        /*
94
         * We prepare the application for a build, moving it to production. Then,
95
         * after compile all the code to a single file, we move the built file
96
         * to the builds folder with the correct permissions.
97
         */
98 2
        $this->prepare()
99 2
            ->compile($name)
100 1
            ->clear();
101
102 1
        $this->output->writeln(
103 1
            sprintf('    Compiled successfully: <fg=green>%s</>', $this->app->buildsPath($name))
104
        );
105
106 1
        return $this;
107
    }
108
109 2
    private function compile(string $name): BuildCommand
110
    {
111 2
        if (! File::exists($this->app->buildsPath())) {
112 2
            File::makeDirectory($this->app->buildsPath());
113
        }
114
115 2
        $process = new Process(
116 2
            './box compile --working-dir="'.base_path().'" --config="'.base_path('box.json').'"',
0 ignored issues
show
Bug introduced by
'./box compile --working..._path('box.json') . '"' of type string is incompatible with the type array expected by parameter $command of Symfony\Component\Process\Process::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

116
            /** @scrutinizer ignore-type */ './box compile --working-dir="'.base_path().'" --config="'.base_path('box.json').'"',
Loading history...
117 2
            dirname(dirname(__DIR__)).'/bin',
118 2
            null,
119 2
            null,
120 2
            $this->getTimeout()
121
        );
122
123 2
        $section = tap($this->originalOutput->section())->write('');
0 ignored issues
show
Bug introduced by
The method section() does not exist on Symfony\Component\Console\Output\OutputInterface. It seems like you code against a sub-type of Symfony\Component\Console\Output\OutputInterface such as Symfony\Component\Console\Style\OutputStyle or Symfony\Component\Console\Output\ConsoleOutput or anonymous//tests/BuildCommandTest.php$1 or anonymous//tests/BuildCommandTest.php$3 or Symfony\Component\Console\Output\ConsoleOutput. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

123
        $section = tap($this->originalOutput->/** @scrutinizer ignore-call */ section())->write('');
Loading history...
124
125 2
        $progressBar = tap(
126 2
            new ProgressBar(
127 2
                $this->output->getVerbosity() > OutputInterface::VERBOSITY_NORMAL ? new NullOutput() : $section, 25
128
            )
129 2
        )->setProgressCharacter("\xF0\x9F\x8D\xBA");
130
131 2
        foreach (tap($process)->start() as $type => $data) {
132 2
            $progressBar->advance();
133
134 2
            if ($this->output->getVerbosity() > OutputInterface::VERBOSITY_NORMAL) {
135 2
                $process::OUT === $type ? $this->info("$data") : $this->error("$data");
136
            }
137
        }
138
139 2
        $progressBar->finish();
140
141 2
        $section->clear();
142
143 1
        $this->task('   2. <fg=yellow>Compile</> into a single file');
144
145 1
        $this->output->newLine();
146
147 1
        File::move($this->app->basePath($this->getBinary()).'.phar', $this->app->buildsPath($name));
148
149 1
        return $this;
150
    }
151
152 2
    private function prepare(): BuildCommand
153
    {
154 2
        $configFile = $this->app->configPath('app.php');
155 2
        static::$config = File::get($configFile);
0 ignored issues
show
Bug introduced by
Since $config is declared private, accessing it with static will lead to errors in possible sub-classes; you can either use self, or increase the visibility of $config to at least protected.
Loading history...
156
157 2
        $config = include $configFile;
158
159 2
        $config['production'] = true;
160 2
        $version = $this->option('build-version') ?: $this->ask('Build version?', $config['version']);
161 2
        $config['version'] = $version;
162
163 2
        $boxFile = $this->app->basePath('box.json');
164 2
        static::$box = File::get($boxFile);
0 ignored issues
show
Bug introduced by
Since $box is declared private, accessing it with static will lead to errors in possible sub-classes; you can either use self, or increase the visibility of $box to at least protected.
Loading history...
165
166 2
        $this->task(
167 2
            '   1. Moving application to <fg=yellow>production mode</>',
168
            function () use ($configFile, $config) {
169 2
                File::put($configFile, '<?php return '.var_export($config, true).';'.PHP_EOL);
170 2
            }
171
        );
172
173 2
        $boxContents = json_decode(static::$box, true);
174 2
        $boxContents['main'] = $this->getBinary();
175 2
        File::put($boxFile, json_encode($boxContents));
176
177 2
        File::put($configFile, '<?php return '.var_export($config, true).';'.PHP_EOL);
178
179 2
        return $this;
180
    }
181
182 2
    private function clear(): BuildCommand
183
    {
184 2
        File::put($this->app->configPath('app.php'), static::$config);
0 ignored issues
show
Bug introduced by
Since $config is declared private, accessing it with static will lead to errors in possible sub-classes; you can either use self, or increase the visibility of $config to at least protected.
Loading history...
185
186 2
        File::put($this->app->basePath('box.json'), static::$box);
0 ignored issues
show
Bug introduced by
Since $box is declared private, accessing it with static will lead to errors in possible sub-classes; you can either use self, or increase the visibility of $box to at least protected.
Loading history...
187
188 2
        static::$config = null;
189
190 2
        static::$box = null;
191
192 2
        return $this;
193
    }
194
195
    /**
196
     * Returns the artisan binary.
197
     */
198 2
    private function getBinary(): string
199
    {
200 2
        return str_replace(["'", '"'], '', Artisan::artisanBinary());
201
    }
202
203
    /**
204
     * Returns a valid timeout value. Non positive values are converted to null,
205
     * meaning no timeout.
206
     *
207
     * @return float|null
208
     * @throws \InvalidArgumentException
209
     */
210 2
    private function getTimeout(): ?float
211
    {
212 2
        if (! is_numeric($this->option('timeout'))) {
0 ignored issues
show
introduced by
The condition is_numeric($this->option('timeout')) is always true.
Loading history...
213
            throw new \InvalidArgumentException('The timeout value must be a number.');
214
        }
215
216 2
        $timeout = (float) $this->option('timeout');
217
218 2
        return $timeout > 0 ? $timeout : null;
219
    }
220
221
    /**
222
     * Makes sure that the `clear` is performed even
223
     * if the command fails.
224
     *
225
     * @return void
226
     */
227 36
    public function __destruct()
228
    {
229 36
        if (static::$config !== null) {
0 ignored issues
show
Bug introduced by
Since $config is declared private, accessing it with static will lead to errors in possible sub-classes; you can either use self, or increase the visibility of $config to at least protected.
Loading history...
230 1
            $this->clear();
231
        }
232 36
    }
233
}
234