Passed
Push — master ( 813742...26b3f4 )
by Théo
02:16
created

Box::replacePlaceholders()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 2
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 Assert\Assertion;
18
use BadMethodCallException;
19
use Closure;
20
use Countable;
21
use KevinGH\Box\Compactor\PhpScoper;
22
use KevinGH\Box\Composer\ComposerOrchestrator;
23
use KevinGH\Box\PhpScoper\NullScoper;
24
use KevinGH\Box\PhpScoper\Scoper;
25
use Phar;
26
use RecursiveDirectoryIterator;
27
use RuntimeException;
28
use SplFileInfo;
29
use function Amp\ParallelFunctions\parallelMap;
30
use function Amp\Promise\wait;
31
use function array_flip;
32
use function array_map;
33
use function chdir;
34
use function extension_loaded;
35
use function file_exists;
36
use function getcwd;
37
use function KevinGH\Box\FileSystem\dump_file;
38
use function KevinGH\Box\FileSystem\file_contents;
39
use function KevinGH\Box\FileSystem\make_path_relative;
40
use function KevinGH\Box\FileSystem\make_tmp_dir;
41
use function KevinGH\Box\FileSystem\mkdir;
42
use function KevinGH\Box\FileSystem\remove;
43
use function sprintf;
44
45
/**
46
 * Box is a utility class to generate a PHAR.
47
 *
48
 * @private
49
 */
50
final class Box implements Countable
51
{
52
    public const DEBUG_DIR = '.box_dump';
53
54
    /**
55
     * @var Compactor[]
56
     */
57
    private $compactors = [];
58
59
    /**
60
     * @var string The path to the PHAR file
61
     */
62
    private $file;
63
64
    /**
65
     * @var Phar The PHAR instance
66
     */
67
    private $phar;
68
69
    /**
70
     * @var scalar[] The placeholders with their values
71
     */
72
    private $placeholders = [];
73
74
    /**
75
     * @var string
76
     */
77
    private $basePath;
78
79
    /**
80
     * @var Closure|MapFile
81
     */
82
    private $mapFile;
83
84
    /**
85
     * @var Scoper
86
     */
87
    private $scoper;
88
89
    private $buffering = false;
90
91
    private $bufferedFiles = [];
92
93
    private function __construct(Phar $phar, string $file)
94
    {
95
        $this->phar = $phar;
96
        $this->file = $file;
97
98
        $this->basePath = getcwd();
99
        $this->mapFile = function (): void { };
100
        $this->scoper = new NullScoper();
101
    }
102
103
    /**
104
     * Creates a new PHAR and Box instance.
105
     *
106
     * @param string $file  The PHAR file name
107
     * @param int    $flags Flags to pass to the Phar parent class RecursiveDirectoryIterator
108
     * @param string $alias Alias with which the Phar archive should be referred to in calls to stream functionality
109
     *
110
     * @return Box
111
     *
112
     * @see RecursiveDirectoryIterator
113
     */
114
    public static function create(string $file, int $flags = null, string $alias = null): self
115
    {
116
        // Ensure the parent directory of the PHAR file exists as `new \Phar()` does not create it and would fail
117
        // otherwise.
118
        mkdir(dirname($file));
119
120
        return new self(new Phar($file, (int) $flags, $alias), $file);
121
    }
122
123
    public function startBuffering(): void
124
    {
125
        Assertion::false($this->buffering, 'The buffering must be ended before starting it again');
126
127
        $this->buffering = true;
128
129
        $this->phar->startBuffering();
130
    }
131
132
    public function endBuffering(bool $dumpAutoload): void
133
    {
134
        Assertion::true($this->buffering, 'The buffering must be started before ending it');
135
136
        $cwd = getcwd();
137
138
        $tmp = make_tmp_dir('box', __CLASS__);
139
        chdir($tmp);
140
141
        try {
142
            foreach ($this->bufferedFiles as $file => $contents) {
143
                dump_file($file, $contents);
144
            }
145
146
            if ($dumpAutoload) {
147
                // Dump autoload without dev dependencies
148
                ComposerOrchestrator::dumpAutoload($this->scoper->getWhitelist(), $this->scoper->getPrefix());
149
            }
150
151
            chdir($cwd);
152
153
            $this->phar->buildFromDirectory($tmp);
154
        } finally {
155
            remove($tmp);
156
        }
157
158
        $this->buffering = false;
159
160
        $this->phar->stopBuffering();
161
    }
162
163
    /**
164
     * @return null|string The required extension to execute the PHAR now that it is compressed
165
     */
166
    public function compress(int $compressionAlgorithm): ?string
167
    {
168
        Assertion::false($this->buffering, 'Cannot compress files while buffering.');
169
        Assertion::inArray($compressionAlgorithm, get_phar_compression_algorithms());
170
171
        $extensionRequired = get_phar_compression_algorithm_extension($compressionAlgorithm);
172
173
        if (null !== $extensionRequired && false === extension_loaded($extensionRequired)) {
174
            throw new RuntimeException(
175
                sprintf(
176
                    'Cannot compress the PHAR with the compression algorithm "%s": the extension "%s" is required but appear to not '
177
                    .'be loaded',
178
                    array_flip(get_phar_compression_algorithms())[$compressionAlgorithm],
179
                    $extensionRequired
180
                )
181
            );
182
        }
183
184
        try {
185
            if (Phar::NONE === $compressionAlgorithm) {
186
                $this->getPhar()->decompressFiles();
187
            } else {
188
                $this->phar->compressFiles($compressionAlgorithm);
189
            }
190
        } catch (BadMethodCallException $exception) {
191
            $exceptionMessage = 'unable to create temporary file' !== $exception->getMessage()
192
                ? 'Could not compress the PHAR: '.$exception->getMessage()
193
                : sprintf(
194
                    'Could not compress the PHAR: the compression requires too many file descriptors to be opened (%s). Check '
195
                    .'your system limits or install the posix extension to allow Box to automatically configure it during the compression',
196
                    $this->phar->count()
197
                )
198
            ;
199
200
            throw new RuntimeException($exceptionMessage, $exception->getCode(), $exception);
201
        }
202
203
        return $extensionRequired;
204
    }
205
206
    /**
207
     * @param Compactor[] $compactors
208
     */
209
    public function registerCompactors(array $compactors): void
210
    {
211
        Assertion::allIsInstanceOf($compactors, Compactor::class);
212
213
        $this->compactors = $compactors;
214
215
        foreach ($this->compactors as $compactor) {
216
            if ($compactor instanceof PhpScoper) {
217
                $this->scoper = $compactor->getScoper();
218
219
                break;
220
            }
221
        }
222
    }
223
224
    /**
225
     * @param scalar[] $placeholders
226
     */
227
    public function registerPlaceholders(array $placeholders): void
228
    {
229
        $message = 'Expected value "%s" to be a scalar or stringable object.';
230
231
        foreach ($placeholders as $i => $placeholder) {
232
            if (is_object($placeholder)) {
233
                Assertion::methodExists('__toString', $placeholder, $message);
234
235
                $placeholders[$i] = (string) $placeholder;
236
237
                break;
238
            }
239
240
            Assertion::scalar($placeholder, $message);
241
        }
242
243
        $this->placeholders = $placeholders;
244
    }
245
246
    public function registerFileMapping(string $basePath, MapFile $fileMapper): void
247
    {
248
        $this->basePath = $basePath;
249
        $this->mapFile = $fileMapper;
250
    }
251
252
    public function registerStub(string $file): void
253
    {
254
        $contents = self::replacePlaceholders(
255
            $this->placeholders,
256
            file_contents($file)
257
        );
258
259
        $this->phar->setStub($contents);
260
    }
261
262
    /**
263
     * @param SplFileInfo[]|string[] $files
264
     */
265
    public function addFiles(array $files, bool $binary): void
266
    {
267
        Assertion::true($this->buffering, 'Cannot add files if the buffering has not started.');
268
269
        $files = array_map(
270
            function ($file): string {
271
                // Convert files to string as SplFileInfo is not serializable
272
                return (string) $file;
273
            },
274
            $files
275
        );
276
277
        if ($binary) {
278
            foreach ($files as $file) {
279
                $this->addFile($file, null, $binary);
280
            }
281
282
            return;
283
        }
284
285
        $filesWithContents = $this->processContents($files);
286
287
        foreach ($filesWithContents as $fileWithContents) {
288
            [$file, $contents] = $fileWithContents;
289
290
            $this->bufferedFiles[$file] = $contents;
291
        }
292
    }
293
294
    /**
295
     * Adds the a file to the PHAR. The contents will first be compacted and have its placeholders
296
     * replaced.
297
     *
298
     * @param string      $file
299
     * @param null|string $contents If null the content of the file will be used
300
     * @param bool        $binary   When true means the file content shouldn't be processed
301
     *
302
     * @return string File local path
303
     */
304
    public function addFile(string $file, string $contents = null, bool $binary = false): string
305
    {
306
        Assertion::true($this->buffering, 'Cannot add files if the buffering has not started.');
307
308
        if (null === $contents) {
309
            $contents = file_contents($file);
310
        }
311
312
        $relativePath = make_path_relative($file, $this->basePath);
313
        $local = ($this->mapFile)($relativePath);
314
315
        if (null === $local) {
316
            $local = $relativePath;
317
        }
318
319
        if ($binary) {
320
            $this->bufferedFiles[$local] = $contents;
321
        } else {
322
            $processedContents = self::compactContents(
323
                $this->compactors,
324
                $local,
325
                self::replacePlaceholders($this->placeholders, $contents)
326
            );
327
328
            $this->bufferedFiles[$local] = $processedContents;
329
        }
330
331
        return $local;
332
    }
333
334
    public function getPhar(): Phar
335
    {
336
        return $this->phar;
337
    }
338
339
    /**
340
     * Signs the PHAR using a private key file.
341
     *
342
     * @param string $file     the private key file name
343
     * @param string $password the private key password
344
     */
345
    public function signUsingFile(string $file, string $password = null): void
346
    {
347
        $this->sign(file_contents($file), $password);
348
    }
349
350
    /**
351
     * Signs the PHAR using a private key.
352
     *
353
     * @param string $key      The private key
354
     * @param string $password The private key password
355
     */
356
    public function sign(string $key, ?string $password): void
357
    {
358
        $pubKey = $this->file.'.pubkey';
359
360
        Assertion::writeable(dirname($pubKey));
361
        Assertion::extensionLoaded('openssl');
362
363
        if (file_exists($pubKey)) {
364
            Assertion::file(
365
                $pubKey,
366
                'Cannot create public key: "%s" already exists and is not a file.'
367
            );
368
        }
369
370
        $resource = openssl_pkey_get_private($key, (string) $password);
371
372
        openssl_pkey_export($resource, $private);
373
374
        $details = openssl_pkey_get_details($resource);
0 ignored issues
show
Bug introduced by
It seems like $resource can also be of type false; however, parameter $key of openssl_pkey_get_details() does only seem to accept resource, 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

374
        $details = openssl_pkey_get_details(/** @scrutinizer ignore-type */ $resource);
Loading history...
375
376
        $this->phar->setSignatureAlgorithm(Phar::OPENSSL, $private);
377
378
        dump_file($pubKey, $details['key']);
379
    }
380
381
    /**
382
     * @param string[] $files
383
     *
384
     * @return array array of tuples where the first element is the local file path (path inside the PHAR) and the
385
     *               second element is the processed contents
386
     */
387
    private function processContents(array $files): array
388
    {
389
        $basePath = $this->basePath;
390
        $mapFile = $this->mapFile;
391
        $placeholders = $this->placeholders;
392
        $compactors = $this->compactors;
393
        $bootstrap = $GLOBALS['_BOX_BOOTSTRAP'] ?? function (): void {};
394
        $cwd = getcwd();
395
396
        $processFile = function (string $file) use ($cwd, $basePath, $mapFile, $placeholders, $compactors, $bootstrap): array {
397
            chdir($cwd);
398
            $bootstrap();
399
400
            $contents = file_contents($file);
401
402
            $relativePath = make_path_relative($file, $basePath);
403
            $local = $mapFile($relativePath);
404
405
            if (null === $local) {
406
                $local = $relativePath;
407
            }
408
409
            $processedContents = self::compactContents(
410
                $compactors,
411
                $local,
412
                self::replacePlaceholders($placeholders, $contents)
413
            );
414
415
            return [$local, $processedContents];
416
        };
417
418
        return is_parallel_processing_enabled() && false === ($this->scoper instanceof NullScoper)
419
            ? wait(parallelMap($files, $processFile))
420
            : array_map($processFile, $files)
421
        ;
422
    }
423
424
    /**
425
     * Replaces the placeholders with their values.
426
     *
427
     * @param array  $placeholders
428
     * @param string $contents     the contents
429
     *
430
     * @return string the replaced contents
431
     */
432
    private static function replacePlaceholders(array $placeholders, string $contents): string
433
    {
434
        return str_replace(
435
            array_keys($placeholders),
436
            array_values($placeholders),
437
            $contents
438
        );
439
    }
440
441
    private static function compactContents(array $compactors, string $file, string $contents): string
442
    {
443
        return array_reduce(
444
            $compactors,
445
            function (string $contents, Compactor $compactor) use ($file): string {
446
                return $compactor->compact($file, $contents);
447
            },
448
            $contents
449
        );
450
    }
451
452
    /**
453
     * {@inheritdoc}
454
     */
455
    public function count(): int
456
    {
457
        Assertion::false($this->buffering, 'Cannot count the number of files in the PHAR when buffering');
458
459
        return $this->phar->count();
460
    }
461
}
462