From 5cae8255137cc7260d00f9481ad7028e2b8a45bf Mon Sep 17 00:00:00 2001 From: Yannoff Date: Sat, 2 Mar 2024 16:39:16 +0100 Subject: [PATCH] Refactor: Phar stub entrypoint initialization - Inclusion of the entrypoint script contents is now handled by the compile command --- src/Command/Compile.php | 2 ++ src/Phar.php | 12 ++++++++++++ src/PharBuilder.php | 9 +++++++-- 3 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src/Command/Compile.php b/src/Command/Compile.php index bec97f9..24100a8 100644 --- a/src/Command/Compile.php +++ b/src/Command/Compile.php @@ -72,6 +72,8 @@ protected function initBuilder(string $main): self { $this->info('Initializing Phar builder...'); $this->builder = PharBuilder::create($main); + $this->info('Adding stub entrypoint script contents...'); + $this->addFile($main); return $this; } diff --git a/src/Phar.php b/src/Phar.php index eca7181..216b02d 100644 --- a/src/Phar.php +++ b/src/Phar.php @@ -37,4 +37,16 @@ public function addFileContents(string $filename, string $localName = null, bool $contents = $minify ? php_strip_whitespace($filename) : file_get_contents($filename); $this[$key] = $contents; } + + /** + * Check whether the given file exists in archive + * + * @param string $file + * + * @return bool + */ + public function has(string $file): bool + { + return $this->offsetExists($file); + } } diff --git a/src/PharBuilder.php b/src/PharBuilder.php index 346fb59..569c3c5 100644 --- a/src/PharBuilder.php +++ b/src/PharBuilder.php @@ -15,6 +15,8 @@ namespace Yannoff\PhpCodeCompiler; +use LogicException; + /** * Phar archive builder class */ @@ -91,8 +93,6 @@ public function init(): self $this->archive = new Phar($this->pharname); $this->archive->startBuffering(); - $this->archive->addFileContents($this->main); - return $this; } @@ -118,6 +118,11 @@ public function setBanner(string $banner): self */ public function compile(string $output, string $compression = 'GZ') { + // Check that entrypoint script contents has been added to the archive before proceeding + if (!$this->archive->has($this->main)) { + throw new LogicException("Main script {$this->main} contents must be added to the archive"); + } + $c = constant('Phar::' . $compression); $this->archive->compressFiles($c);