Passed
Push — master ( c6d404...885f37 )
by Théo
02:15
created

Box::startBuffering()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 7
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the box project.
7
 *
8
 * (c) Kevin Herrera <[email protected]>
9
 *     Théo Fidry <[email protected]>
10
 *
11
 * This source file is subject to the MIT license that is bundled
12
 * with this source code in the file LICENSE.
13
 */
14
15
namespace KevinGH\Box;
16
17
use Amp\MultiReasonException;
18
use Humbug\PhpScoper\Symbol\SymbolsRegistry;
19
use function Amp\ParallelFunctions\parallelMap;
20
use function Amp\Promise\wait;
21
use function array_filter;
22
use function array_flip;
23
use function array_map;
24
use function array_unshift;
25
use BadMethodCallException;
26
use function chdir;
27
use Closure;
28
use Countable;
29
use function dirname;
30
use function extension_loaded;
31
use function file_exists;
32
use function getcwd;
33
use function is_object;
34
use KevinGH\Box\Compactor\Compactors;
35
use KevinGH\Box\Compactor\PhpScoper;
36
use KevinGH\Box\Compactor\Placeholder;
37
use function KevinGH\Box\FileSystem\dump_file;
38
use function KevinGH\Box\FileSystem\file_contents;
39
use function KevinGH\Box\FileSystem\make_tmp_dir;
40
use function KevinGH\Box\FileSystem\mkdir;
41
use function KevinGH\Box\FileSystem\remove;
42
use KevinGH\Box\PhpScoper\NullScoper;
43
use KevinGH\Box\PhpScoper\WhitelistManipulator;
44
use function openssl_pkey_export;
45
use function openssl_pkey_get_details;
46
use function openssl_pkey_get_private;
47
use Phar;
48
use RecursiveDirectoryIterator;
49
use RuntimeException;
50
use SplFileInfo;
51
use function sprintf;
52
use Webmozart\Assert\Assert;
53
54
/**
55
 * Box is a utility class to generate a PHAR.
56
 *
57
 * @private
58
 */
59
final class Box implements Countable
60
{
61
    /** @var string The path to the PHAR file */
62
    private $file;
63
64
    /** @var Phar The PHAR instance */
65
    private $phar;
66
67
    private $compactors;
68
    private $placeholderCompactor;
69
    private $mapFile;
70
    private $scoper;
71
    private $buffering = false;
72
    private $bufferedFiles = [];
73
74
    private function __construct(Phar $phar, string $file)
75
    {
76
        $this->phar = $phar;
77
        $this->file = $file;
78
79
        $this->compactors = new Compactors();
80
        $this->placeholderCompactor = new Placeholder([]);
81
        $this->mapFile = new MapFile(getcwd(), []);
82
        $this->scoper = new NullScoper();
83
    }
84
85
    /**
86
     * Creates a new PHAR and Box instance.
87
     *
88
     * @param string $file  The PHAR file name
89
     * @param int    $flags Flags to pass to the Phar parent class RecursiveDirectoryIterator
90
     * @param string $alias Alias with which the Phar archive should be referred to in calls to stream functionality
91
     *
92
     * @return Box
93
     *
94
     * @see RecursiveDirectoryIterator
95
     */
96
    public static function create(string $file, ?int $flags = null, ?string $alias = null): self
97
    {
98
        // Ensure the parent directory of the PHAR file exists as `new \Phar()` does not create it and would fail
99
        // otherwise.
100
        mkdir(dirname($file));
101
102
        return new self(new Phar($file, (int) $flags, $alias), $file);
103
    }
104
105
    public function startBuffering(): void
106
    {
107
        Assert::false($this->buffering, 'The buffering must be ended before starting it again');
108
109
        $this->buffering = true;
110
111
        $this->phar->startBuffering();
112
    }
113
114
    public function endBuffering(?Closure $dumpAutoload): void
115
    {
116
        Assert::true($this->buffering, 'The buffering must be started before ending it');
117
118
        $cwd = getcwd();
119
120
        $tmp = make_tmp_dir('box', self::class);
121
        chdir($tmp);
122
123
        if ([] === $this->bufferedFiles) {
124
            $this->bufferedFiles = [
125
                '.box_empty' => 'A PHAR cannot be empty so Box adds this file to ensure the PHAR is created still.',
126
            ];
127
        }
128
129
        try {
130
            foreach ($this->bufferedFiles as $file => $contents) {
131
                dump_file($file, $contents);
132
            }
133
134
            if (null !== $dumpAutoload) {
135
                $dumpAutoload(
136
                    $this->scoper->getSymbolsRegistry(),
137
                    $this->scoper->getPrefix()
138
                );
139
            }
140
141
            chdir($cwd);
142
143
            $this->phar->buildFromDirectory($tmp);
144
        } finally {
145
            remove($tmp);
146
        }
147
148
        $this->buffering = false;
149
150
        $this->phar->stopBuffering();
151
    }
152
153
    public function removeComposerArtefacts(string $vendorDir): void
154
    {
155
        Assert::false($this->buffering, 'The buffering must have ended before removing the Composer artefacts');
156
157
        $composerFiles = [
158
            'composer.json',
159
            'composer.lock',
160
            $vendorDir.'/composer/installed.json',
161
        ];
162
163
        $this->phar->startBuffering();
164
165
        foreach ($composerFiles as $composerFile) {
166
            $localComposerFile = ($this->mapFile)($composerFile);
167
168
            if (file_exists('phar://'.$this->phar->getPath().'/'.$localComposerFile)) {
169
                $this->phar->delete($localComposerFile);
170
            }
171
        }
172
173
        $this->phar->stopBuffering();
174
    }
175
176
    /**
177
     * @return null|string The required extension to execute the PHAR now that it is compressed
178
     */
179
    public function compress(int $compressionAlgorithm): ?string
180
    {
181
        Assert::false($this->buffering, 'Cannot compress files while buffering.');
182
        Assert::inArray($compressionAlgorithm, get_phar_compression_algorithms());
183
184
        $extensionRequired = get_phar_compression_algorithm_extension($compressionAlgorithm);
185
186
        if (null !== $extensionRequired && false === extension_loaded($extensionRequired)) {
187
            throw new RuntimeException(
188
                sprintf(
189
                    'Cannot compress the PHAR with the compression algorithm "%s": the extension "%s" is required but appear to not '
190
                    .'be loaded',
191
                    array_flip(get_phar_compression_algorithms())[$compressionAlgorithm],
192
                    $extensionRequired
193
                )
194
            );
195
        }
196
197
        try {
198
            if (Phar::NONE === $compressionAlgorithm) {
199
                $this->getPhar()->decompressFiles();
200
            } else {
201
                $this->phar->compressFiles($compressionAlgorithm);
202
            }
203
        } catch (BadMethodCallException $exception) {
204
            $exceptionMessage = 'unable to create temporary file' !== $exception->getMessage()
205
                ? 'Could not compress the PHAR: '.$exception->getMessage()
206
                : sprintf(
207
                    'Could not compress the PHAR: the compression requires too many file descriptors to be opened (%s). Check '
208
                    .'your system limits or install the posix extension to allow Box to automatically configure it during the compression',
209
                    $this->phar->count()
210
                )
211
            ;
212
213
            throw new RuntimeException($exceptionMessage, $exception->getCode(), $exception);
214
        }
215
216
        return $extensionRequired;
217
    }
218
219
    public function registerCompactors(Compactors $compactors): void
220
    {
221
        $compactorsArray = $compactors->toArray();
222
223
        foreach ($compactorsArray as $index => $compactor) {
224
            if ($compactor instanceof PhpScoper) {
225
                $this->scoper = $compactor->getScoper();
226
227
                continue;
228
            }
229
230
            if ($compactor instanceof Placeholder) {
231
                // Removes the known Placeholder compactors in favour of the Box one
232
                unset($compactorsArray[$index]);
233
            }
234
        }
235
236
        array_unshift($compactorsArray, $this->placeholderCompactor);
237
238
        $this->compactors = new Compactors(...$compactorsArray);
239
    }
240
241
    /**
242
     * @param scalar[] $placeholders
243
     */
244
    public function registerPlaceholders(array $placeholders): void
245
    {
246
        $message = 'Expected value "%s" to be a scalar or stringable object.';
247
248
        foreach ($placeholders as $index => $placeholder) {
249
            if (is_object($placeholder)) {
250
                Assert::methodExists($placeholder, '__toString', $message);
251
252
                $placeholders[$index] = (string) $placeholder;
253
254
                break;
255
            }
256
257
            Assert::scalar($placeholder, $message);
258
        }
259
260
        $this->placeholderCompactor = new Placeholder($placeholders);
261
262
        $this->registerCompactors($this->compactors);
263
    }
264
265
    public function registerFileMapping(MapFile $fileMapper): void
266
    {
267
        $this->mapFile = $fileMapper;
268
    }
269
270
    public function registerStub(string $file): void
271
    {
272
        $contents = $this->placeholderCompactor->compact(
273
            $file,
274
            file_contents($file)
275
        );
276
277
        $this->phar->setStub($contents);
278
    }
279
280
    /**
281
     * @param SplFileInfo[]|string[] $files
282
     *
283
     * @throws MultiReasonException
284
     */
285
    public function addFiles(array $files, bool $binary): void
286
    {
287
        Assert::true($this->buffering, 'Cannot add files if the buffering has not started.');
288
289
        $files = array_map('strval', $files);
290
291
        if ($binary) {
292
            foreach ($files as $file) {
293
                $this->addFile($file, null, $binary);
294
            }
295
296
            return;
297
        }
298
299
        foreach ($this->processContents($files) as [$file, $contents]) {
300
            $this->bufferedFiles[$file] = $contents;
301
        }
302
    }
303
304
    /**
305
     * Adds the a file to the PHAR. The contents will first be compacted and have its placeholders
306
     * replaced.
307
     *
308
     * @param null|string $contents If null the content of the file will be used
309
     * @param bool        $binary   When true means the file content shouldn't be processed
310
     *
311
     * @return string File local path
312
     */
313
    public function addFile(string $file, ?string $contents = null, bool $binary = false): string
314
    {
315
        Assert::true($this->buffering, 'Cannot add files if the buffering has not started.');
316
317
        if (null === $contents) {
318
            $contents = file_contents($file);
319
        }
320
321
        $local = ($this->mapFile)($file);
322
323
        $this->bufferedFiles[$local] = $binary ? $contents : $this->compactors->compact($local, $contents);
324
325
        return $local;
326
    }
327
328
    public function getPhar(): Phar
329
    {
330
        return $this->phar;
331
    }
332
333
    /**
334
     * Signs the PHAR using a private key file.
335
     *
336
     * @param string      $file     the private key file name
337
     * @param null|string $password the private key password
338
     */
339
    public function signUsingFile(string $file, ?string $password = null): void
340
    {
341
        $this->sign(file_contents($file), $password);
342
    }
343
344
    /**
345
     * Signs the PHAR using a private key.
346
     *
347
     * @param string      $key      The private key
348
     * @param null|string $password The private key password
349
     */
350
    public function sign(string $key, ?string $password): void
351
    {
352
        $pubKey = $this->file.'.pubkey';
353
354
        Assert::writable(dirname($pubKey));
355
        Assert::true(extension_loaded('openssl'));
356
357
        if (file_exists($pubKey)) {
358
            Assert::file(
359
                $pubKey,
360
                'Cannot create public key: %s already exists and is not a file.'
361
            );
362
        }
363
364
        $resource = openssl_pkey_get_private($key, (string) $password);
365
366
        Assert::notSame(false, $resource, 'Could not retrieve the private key, check that the password is correct.');
367
368
        openssl_pkey_export($resource, $private);
369
370
        $details = openssl_pkey_get_details($resource);
371
372
        $this->phar->setSignatureAlgorithm(Phar::OPENSSL, $private);
373
374
        dump_file($pubKey, $details['key']);
375
    }
376
377
    /**
378
     * @param string[] $files
379
     *
380
     * @return array array of tuples where the first element is the local file path (path inside the PHAR) and the
381
     *               second element is the processed contents
382
     */
383
    private function processContents(array $files): array
384
    {
385
        $mapFile = $this->mapFile;
386
        $compactors = $this->compactors;
387
        $cwd = getcwd();
388
389
        $processFile = static function (string $file) use ($cwd, $mapFile, $compactors): array {
390
            chdir($cwd);
391
392
            // Keep the fully qualified call here since this function may be executed without the right autoloading
393
            // mechanism
394
            \KevinGH\Box\register_aliases();
395
            if (true === \KevinGH\Box\is_parallel_processing_enabled()) {
396
                \KevinGH\Box\register_error_handler();
397
            }
398
399
            $contents = file_contents($file);
400
401
            $local = $mapFile($file);
402
403
            $processedContents = $compactors->compact($local, $contents);
404
405
            return [$local, $processedContents, $compactors->getScoperSymbolsRegistry()];
406
        };
407
408
        if ($this->scoper instanceof NullScoper || false === is_parallel_processing_enabled()) {
0 ignored issues
show
introduced by
$this->scoper is always a sub-type of KevinGH\Box\PhpScoper\NullScoper.
Loading history...
409
            return array_map($processFile, $files);
410
        }
411
412
        // In the case of parallel processing, an issue is caused due to the statefulness nature of the PhpScoper
413
        // whitelist.
414
        //
415
        // Indeed the PhpScoper Whitelist stores the records of whitelisted classes and functions. If nothing is done,
416
        // then the whitelisted retrieve in the end will here will be "blank" since the updated whitelists are the ones
417
        // from the workers used for the parallel processing.
418
        //
419
        // In order to avoid that, the whitelists will be returned as a result as well in order to be able to merge
420
        // all the whitelists into one.
421
        //
422
        // This process is allowed thanks to the nature of the state of the whitelists: having redundant classes or
423
        // functions registered can easily be deal with so merging all those different states is actually
424
        // straightforward.
425
        $tuples = wait(parallelMap($files, $processFile));
426
427
        if ([] === $tuples) {
428
            return [];
429
        }
430
431
        $filesWithContents = [];
432
        $symbolRegistries = [];
433
434
        foreach ($tuples as [$local, $processedContents, $symbolRegistry]) {
435
            $filesWithContents[] = [$local, $processedContents];
436
            $symbolRegistries[] = $symbolRegistry;
437
        }
438
439
        $this->compactors->registerSymbolsRegistry(
440
            SymbolsRegistry::createFromRegistries(array_filter($symbolRegistries)),
441
        );
442
443
        return $filesWithContents;
444
    }
445
446
    /**
447
     * {@inheritdoc}
448
     */
449
    public function count(): int
450
    {
451
        Assert::false($this->buffering, 'Cannot count the number of files in the PHAR when buffering');
452
453
        return $this->phar->count();
454
    }
455
}
456