/** * Execute the task * * @throws Exception * @return void */ public function execute() { $target = $this->getOption('target'); $sourceDirectory = $this->getOption('sourceDirectory'); $stubFile = $this->getOption('stubFile'); if (!extension_loaded('phar')) { throw new \Exception('Phar extension not loaded'); } if (!is_dir($sourceDirectory)) { throw new \Exception('Source directory not found: ' . $sourceDirectory); } // check to see if we can create phar files $readOnly = ini_get('phar.readonly'); if ($readOnly != 1) { $phar = new \Phar($target, 0, basename($target)); $phar->startBuffering(); $phar->buildFromDirectory($sourceDirectory); $stub = $phar->createDefaultStub(); $phar->setStub($stub); $phar->stopBuffering(); //$phar->compress(Phar::GZ); } else { throw new \Exception('Cannot create phar! (read-only enabled)'); } }
function build_pheanstalk_phar() { printf("- Building %s from %s\n", PHAR_FILENAME, BASE_DIR); $phar = new Phar(PHAR_FULLPATH); $phar->buildFromDirectory(BASE_DIR); $phar->setStub($phar->createDefaultStub("vendor/autoload.php")); }
public function testItExtractsIconFromPhar() { $key = uniqid(); $iconContent = $key; $rootPackage = dirname(dirname(__FILE__)); $iconRelativePath = 'Resources/notification/icon-' . $key . '.png'; $testDir = sys_get_temp_dir() . '/test-jolinotif'; $pharPath = $testDir . '/notification-extract-icon-' . $key . '.phar'; $extractedIconPath = sys_get_temp_dir() . '/jolinotif/' . $iconRelativePath; if (!is_dir($testDir)) { mkdir($testDir); } $bootstrap = <<<'PHAR_BOOTSTRAP' <?php require __DIR__.'/vendor/autoload.php'; $iconPath = THE_ICON; $notification = new \Joli\JoliNotif\Notification(); $notification->setBody('My notification'); $notification->setIcon(__DIR__.$iconPath); PHAR_BOOTSTRAP; $phar = new \Phar($pharPath); $phar->buildFromDirectory($rootPackage, '#(src|tests/fixtures|vendor/composer)#'); $phar->addFromString('bootstrap.php', str_replace('THE_ICON', '\'/' . $iconRelativePath . '\'', $bootstrap)); $phar->addFromString($iconRelativePath, $iconContent); $phar->addFile('vendor/autoload.php'); $phar->setStub($phar->createDefaultStub('bootstrap.php')); $this->assertTrue(is_file($pharPath)); exec('php ' . $pharPath); $this->assertTrue(is_file($extractedIconPath)); $this->assertSame($iconContent, file_get_contents($extractedIconPath)); }
/** * Method to run the application routines. Most likely you will want to instantiate a controller * and execute it, or perform some sort of task directly. * * @return void * * @since 2.0 */ protected function doExecute() { if ($this->io->getOption('h') || $this->io->getOption('help')) { $this->help(); return; } $dir = $this->io->getOption('d', '../../vaseman.phar'); $file = __DIR__ . '/' . $dir; if (is_file($file)) { unlink($file); } $this->out('Start generating...'); $phar = new Phar($file); $phar->setStub(<<<PHP #!/usr/bin/env php <?php Phar::mapPhar('vaseman.phar'); require 'phar://vaseman.phar/bin/vaseman'; __HALT_COMPILER(); PHP ); $phar->buildFromDirectory(__DIR__ . '/..'); $phar->stopBuffering(); $this->out('Phar generated: ' . $file)->out(); }
protected static function _build($conf) { $pathToPhar = $conf['path_to_phar']; $pharName = $conf['phar_name']; $srcPath = $conf['src_path']; $initModule = $conf['init_module']; $setup = $conf['setup']; $file = $pathToPhar . '/' . $pharName; if ($conf['delete_old_phar_onbuild'] && \file_exists($file)) { \unlink($file); } $falias = $pharName; $mapPhar = $pharName; $phar = new \Phar($file, 0, $falias); $phar->startBuffering(); $dir = $phar->buildFromDirectory($srcPath); $stub = '<?php ' . "\\Phar::mapPhar('{$falias}'); " . 'include ' . "'phar://{$falias}/{$initModule}'; " . "{$setup}" . '__HALT_COMPILER();'; $phar->setStub($stub); // // if (isset($conf['compress_pkg']) && $conf['compress_pkg'] == 'GZ') { $phar->compressFiles(\Phar::GZ); } // // $phar->stopBuffering(); }
function build_phar() { $phar = new Phar('build/bugsnag.phar'); $phar->buildFromDirectory(dirname(__FILE__) . '/src', '/\\.php$/'); $phar->compressFiles(Phar::GZ); $phar->stopBuffering(); $phar->setStub($phar->createDefaultStub('Bugsnag/Autoload.php')); }
static function create($phar_file, $php_dir, $default_stub) { $phar = new \Phar($phar_file); $phar->buildFromDirectory($php_dir, '/\\.php$/'); $phar->compressFiles(\Phar::GZ); $phar->stopBuffering(); $phar->setStub($phar->createDefaultStub($default_stub)); }
function build_pheanstalk_phar() { $classDir = BASE_DIR . '/classes'; printf("- Building %s from %s\n", PHAR_FILENAME, $classDir); $phar = new Phar(PHAR_PATH); $phar->buildFromDirectory($classDir); $phar->setStub(pheanstalk_phar_stub()); }
/** * Prepare environment before test. */ protected function setUp() { //Build phar archives $this->srcPharPath = dirname(dirname(dirname(__FILE__))) . '/Support/src/'; //namespace $this->pharFileNamespace = dirname(dirname(dirname(__FILE__))) . '/Support/pharFileNamespace.phar'; if (0 == ini_get('phar.readonly') && !file_exists($this->pharFileNamespace)) { $phar = new \Phar($this->pharFileNamespace, 0, 'pharFileNamespace.phar'); $phar->buildFromDirectory($this->srcPharPath . '/NamespaceLoader/'); } parent::setUp(); }
/** * Create the PHAR multiple.phar for the test if this file does not exist. */ protected function setUp() { $multiplePharPath = TK_STATES_TEST_PATH . DIRECTORY_SEPARATOR . 'Support' . DIRECTORY_SEPARATOR . 'multiple.phar'; if (!file_exists($multiplePharPath)) { //Compute Path for this Phar $multiplePath = TK_STATES_TEST_PATH . DIRECTORY_SEPARATOR . 'Support' . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . 'Multiple'; //Build phat $phar = new \Phar($multiplePharPath, 0, 'multiple.phar'); $phar->buildFromDirectory($multiplePath); } parent::setUp(); }
static function makePhar(array $dt) { //retornando com erro se o array estiver vazio if (count($dt) <= 0) { return false; } //aumentando a memoria e o tempo de execução - pode ser muito significante em sistemas lentos e diretórios muito grandes ini_set('memory_limit', '30M'); ini_set('max_execution_time', 180); //Array com os dados da execução $ok = array(); //lendo e executando as conversões indicadas foreach ($dt as $k => $lote) { $stub = '<?php Phar::interceptFileFuncs(); Phar::mungServer(array(\'REQUEST_URI\', \'PHP_SELF\', \'SCRIPT_NAME\', \'SCRIPT_FILENAME\')); Phar::webPhar(\'\', \'\', \'404.php\'); __HALT_COMPILER();'; if (is_dir($lote['o'])) { //criando arquivo PHAR $phar = new \Phar($lote['d']); //pegando o diretório (e sub-diretórios) e arquivos contidos $phar->buildFromDirectory($lote['o']); //criando o cabeçalho Stub $phar->setStub($stub); //carregando a assinatura if (is_file($lote['o'])) { $phar->setSignatureAlgorithm(\Phar::MD5, file_get_contents($lote['o'])); } //comprimindo os dados (exceto o Stub) $compactar = false; if (isset($lote['z'])) { $compactar = true; if (\Phar::canCompress(\Phar::GZ)) { $phar->compressFiles(\Phar::GZ); } elseif (\Phar::canCompress(\Phar::BZ2)) { $phar->compressFiles(\Phar::BZ2); } } //adicionando os dados de saída $ok[$k] = array('o' => $lote['o'], 'd' => $lote['d'], 'z' => $compactar, 'i' => $lote['i']); } else { $ok[$k] = array('e' => 'O diretório "' . $lote['o'] . '" não existe!'); } } if (count($ok) == 0) { return false; } return $ok; }
function __construct($pharName) { echo "<pre>"; $buildRoot = realpath(Ruth::getDOCUMENT_ROOT() . "/../build"); $srcRoot = realpath(Ruth::getDOCUMENT_ROOT()); echo "Building {$pharName}.phar to " . $buildRoot . "\n"; echo "Source: {$srcRoot} \n"; echo "Have you cleaned up the path yet ?"; //clean up things $phar = new Phar($buildRoot . "/" . $pharName . ".phar", FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::KEY_AS_FILENAME, $pharName . ".phar"); $phar["index.php"] = file_get_contents($srcRoot . "/index.php"); $phar->buildFromDirectory($srcRoot); $phar->setStub('<?php Phar::webPhar(); __HALT_COMPILER();'); echo "<pre>"; }
public static function convertVendorsToPhar(Event $event) { $vendorDir = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'vendor'; $phars = []; echo "Converting vendor package dirs to phar...\n"; foreach (new \DirectoryIterator($vendorDir) as $dir) { if (in_array($dir->getFilename(), ['..', '.', 'composer']) || !$dir->isDir()) { continue; } foreach (new \DirectoryIterator($dir->getRealPath()) as $subDir) { if (in_array($subDir->getFilename(), ['..', '.']) || !$subDir->isDir()) { continue; } echo "... " . $dir->getFilename() . '/' . $subDir->getFilename() . "\n"; $fName = $subDir->getRealPath() . '.phar'; $fNameTmp = $fName . '.tmp'; $phar = new \Phar($fNameTmp); $phar->buildFromDirectory($subDir->getRealPath(), '#\\.(?!git)#'); if (\Phar::canCompress(\Phar::GZ)) { $phar->compressFiles(\Phar::GZ); } else { if (\Phar::canCompress(\Phar::BZ2)) { $phar->compressFiles(\Phar::BZ2); } } if (file_exists($fName)) { unlink($fName); } unset($phar); rename($fNameTmp, $fName); //delDirTree($subDir->getRealPath()); $phars[$dir->getFilename() . '/' . $subDir->getFilename()] = str_replace(DIRECTORY_SEPARATOR, '/', str_replace($vendorDir, '', $fName)); } } echo "\nConverting autoload files: \n"; $autoloadFiles = ['composer/autoload_classmap.php', 'composer/autoload_files.php', 'composer/autoload_namespaces.php', 'composer/autoload_psr4.php']; foreach ($autoloadFiles as $file) { echo $file . "\n"; $filePath = $vendorDir . DIRECTORY_SEPARATOR . $file; $content = file_get_contents($filePath); $content = preg_replace('#(?<!\'phar://\' . )\\$vendorDir\\s+.\\s+\'(/[-\\w\\d_]+/[-\\w\\d_]+)#', '\'phar://\' . $vendorDir . \'$1.phar', $content); if ($content) { file_put_contents($filePath, $content); } } echo "\nComplete!\n"; }
public function build() { $this->prepareTemp(); /* Dateien ins Temp-Verzeichnis kopieren */ $class2path = array(); $relDir = $this->classPath->up(); // wir wollen ja den Namespace als erstes Verzeichnis haben foreach ($this->getClassFiles() as $file) { $class = $this->inferClassName($file); // $class2path[ $class ] = $fileURL; $class2path[ltrim($class, '\\')] = $url = $file->getURL($relDir); // statt hier Code::mapClassToFile() zu machen nehmen wir die url $targetFile = File::createFromURL($url, $this->tempSrc); $targetFile->getDirectory()->create(); $this->log(str_pad('Add: ' . $url, 80, ' ', STR_PAD_RIGHT) . " [" . $class . "]", 2); $file->copy($targetFile); } foreach ($this->additionalFiles as $list) { list($file, $fileInPhar) = $list; $targetFile = new File($this->tempSrc . $fileInPhar); $targetFile->getDirectory()->create(); $this->log('Add: ' . $fileInPhar); $file->copy($targetFile); } /* Bootstrapping */ $bootstrapCode = $this->getBootstrapCode($class2path); $bootstrapFile = new File($this->tempSrc, 'index.php'); $bootstrapFile->writeContents($bootstrapCode); /* Build */ try { $tmp = File::createTemporary(); $tmp->setExtension('phar.gz'); $this->phar = new PHPPhar((string) $tmp); $this->phar->compress(PHPPHAR::GZ); $this->phar->startBuffering(); $this->phar->buildFromDirectory($this->tempSrc); $this->phar->stopBuffering(); $this->tempSrc->delete(); $this->out->delete(); $tmp->copy($this->out); } catch (\Exception $e) { $this->tempSrc->delete(); throw $e; } }
<?php $defaults = array('cli' => 'src/cli.php', 'web' => 'src/web.php', 'bin' => 'application.phar'); $temp_file = 'application.phar'; $options = getopt('', array('cli::', 'web::', 'bin::')); $options = array_merge($defaults, $options); @unlink($options['bin']); @unlink($temp_file); $phar = new Phar($temp_file); $phar->buildFromDirectory(__DIR__, '/^((?!\\.git).)*$/'); $defaultStub = $phar->createDefaultStub($options['cli'], $options['web']); $defaultStub = "#!/usr/bin/env php\n" . $defaultStub; $phar->setStub($defaultStub); unset($phar); chmod($temp_file, 0755); rename($temp_file, $options['bin']);
<?php define('SRC_ROOT', dirname(__FILE__) . '/src'); define('BUILD_ROOT', dirname(__FILE__) . '/build'); try { $phar = new Phar(BUILD_ROOT . '/PeriscopeDownloader.phar', FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::KEY_AS_FILENAME, 'PeriscopeDownloader.phar'); $phar->buildFromDirectory(SRC_ROOT, '/.php$/'); $phar->setMetadata(array('version' => '1.0', 'author' => 'jColfej', 'description' => 'Easy download periscope replay !')); $phar->setStub('#!/usr/bin/env php' . PHP_EOL . $phar->createDefaultStub('index.php')); echo 'File created : build/PeriscopeDownloader.phar' . PHP_EOL; } catch (Exception $e) { echo '/!\\ Erreur on PHAR creation ...' . PHP_EOL; echo PHP_EOL; echo 'Error : ' . $e->getMessage() . PHP_EOL; echo 'File : ' . $e->getFile() . PHP_EOL; echo PHP_EOL; echo $e->getTraceAsString() . PHP_EOL; }
<?php mkdir(dirname(__FILE__) . '/testdir4'); foreach (range(1, 4) as $i) { file_put_contents(dirname(__FILE__) . "/testdir4/file{$i}.txt", "some content for file {$i}"); } try { $phar = new Phar(dirname(__FILE__) . '/buildfromdirectory4.phar'); $a = $phar->buildFromDirectory(dirname(__FILE__) . '/testdir4'); asort($a); var_dump($a); } catch (Exception $e) { var_dump(get_class($e)); echo $e->getMessage() . "\n"; } var_dump(file_exists(dirname(__FILE__) . '/buildfromdirectory4.phar')); ?> ===DONE=== <?php unlink(dirname(__FILE__) . '/buildfromdirectory4.phar'); foreach (range(1, 4) as $i) { unlink(dirname(__FILE__) . "/testdir4/file{$i}.txt"); } rmdir(dirname(__FILE__) . '/testdir4');
// Création de l'archive $lListeArchive = ' '; $d = dir($lPath); while (false !== ($entry = $d->read())) { if ($entry != '.' && $entry != '..') { $lListeArchive .= $entry . ' '; } } $d->close(); include $lPath . "/configuration/Version.php"; // Création de l'archive //$output = shell_exec('cd ' . $lPath . ' && tar -czvf zeybux-' . $lEnv . '-' . ZEYBUX_VERSION . '.tar.gz' . $lListeArchive . ' && chmod -R 777 .'); //echo $output; $lVersion = str_replace('.', '-', ZEYBUX_VERSION); $phar = new Phar($lPath . '/zeybux_' . $lEnv . '_' . $lVersion . '.phar', 0, 'zeybux_' . $lEnv . '_' . ZEYBUX_VERSION . '.phar'); $phar->buildFromDirectory($lPath); $phar->compress(Phar::BZ2); $phar->stopBuffering(); shell_exec('cd ' . $lPath . ' && chmod -R 777 .'); if ($lEnv == 'install') { copy($lDossierVersionSource . '/install/install.php', $lPath . '/install.php'); // Le script d'installation $output = shell_exec('cd ' . $lPath . ' && chmod -R 777 .'); } /*** Suppression des fichiers de travail ***/ /** CSS **/ unlink('./zeybu/css/zeybux-html-min.css'); unlink('./zeybu/css/zeybux-html.css'); unlink('./zeybu/css/zeybux-min.css'); unlink('./zeybu/css/zeybux.css'); /*** Js ***/
/** * Creates a PHAR (PHP Archive) file from an entire directory. * * @param string $dir The directory we want to create a PHAR file for. * * @param string $to The new PHAR file location; with a `.phar` extension. * * @param string $stub_file Stub file path. The contents of this stub file will be used as * the stub for the resulting PHAR file. Required for all PHARs created by this routine. * A final call to `__HALT_COMPILER();` is automatically appended by this routine. * * @param boolean $strip_ws Optional. Defaults to a TRUE value (highly recommended). * If this is TRUE; any PHP files in the archive will be further reduced in filesize by this routine. * This is made possible by the `php_strip_whitespace()` function. * * @param boolean $compress Optional. Defaults to a TRUE value (highly recommended). * If this is TRUE; any compressable files in the archive will be further reduced in filesize. * * @param string|array $compressable_extensions Optional. An array of GZIP-compressable extensions. * This will default to only those which are 100% webPhar-compatible: `array('php', 'phps')`. * Or, you can provide your own array of compressable extensions. * * @param string $is_phar_var_suffix Optional. Defaults to `stub`. * A global variable at the top of your PHAR stub file will be declared as follows. * `$GLOBALS['is_phar_'.$is_phar_var_suffix] = 'phar://'.__FILE__;` (just a helpful identifier). * * @return string The new PHAR file path; else an exception is thrown on any type of failure. * * @throws exception If invalid types are passed through arguments list. * @throws exception If `$dir` is empty, does NOT exist; or is NOT readable for any reason. * @throws exception If `$to` is empty, or is NOT specified with a `.phar` extension. * @throws exception If `$to` parent directory does NOT exist; or is not writable. * @throws exception If `$stub_file` is empty, does NOT exist; or is NOT readable for any reason. * @throws exception If `$compressable_extensions` or `$is_phar_var_suffix` is empty. * @throws \exception If any Phar class failures occur. The Phar class may throw exceptions. * @throws exception On any type of failure (e.g. NOT successful). * * @WARNING This routine can become resource intensive on large directories. * Mostly because of the compression routines applied here intuitively. It takes some time. * See: {@link env::maximize_time_memory_limits()} */ public function phar_to($dir, $to, $stub_file, $strip_ws = TRUE, $compress = TRUE, $compressable_extensions = array('php', 'phps'), $is_phar_var_suffix = 'stub') { $this->check_arg_types('string:!empty', 'string:!empty', 'string:!empty', 'boolean', 'boolean', 'array:!empty', 'string:!empty', func_get_args()); $dir = $this->n_seps($dir); $to = $this->n_seps($to); $to_dir = $this->n_seps_up($to); if (!is_dir($dir)) { throw $this->©exception($this->method(__FUNCTION__) . '#source_dir_missing', get_defined_vars(), $this->__('Unable to PHAR a directory (source `dir` missing).') . sprintf($this->__('Non-existent source directory: `%1$s`.'), $dir)); } if (!is_readable($dir)) { throw $this->©exception($this->method(__FUNCTION__) . '#read_write_issues', get_defined_vars(), $this->__('Unable to PHAR a directory; not readable, due to permission issues.') . ' ' . sprintf($this->__('Need this directory to be readable please: `%1$s`.'), $dir)); } if (file_exists($to)) { throw $this->©exception($this->method(__FUNCTION__) . '#existing_phar', get_defined_vars(), $this->__('Unable to PHAR a directory; destination PHAR file already exists.') . ' ' . sprintf($this->__('Please delete this file first: `%1$s`.'), $to)); } if ($this->extension($to) !== 'phar') { throw $this->©exception($this->method(__FUNCTION__) . '#invalid_phar_file', get_defined_vars(), $this->__('Unable to PHAR a directory; invalid destination PHAR file.') . ' ' . sprintf($this->__('Please use a `.phar` extension instead of: `%1$s`.'), $to)); } if (!is_dir($to_dir)) { throw $this->©exception($this->method(__FUNCTION__) . '#phar_to_dir_missing', get_defined_vars(), $this->__('Destination PHAR directory does NOT exist yet.') . ' ' . sprintf($this->__('Please check this directory: `%1$s`.'), $to_dir)); } if (!is_writable($to_dir)) { throw $this->©exception($this->method(__FUNCTION__) . '#read_write_issues', get_defined_vars(), $this->__('Unable to PHAR a directory; destination not writable due to permission issues.') . ' ' . sprintf($this->__('Need this directory to be writable please: `%1$s`.'), $to_dir)); } if (!\Phar::canWrite()) { throw $this->©exception($this->method(__FUNCTION__) . '#read_write_issues', get_defined_vars(), $this->__('Unable to PHAR a directory; PHP configuration does NOT allow write access.') . ' ' . $this->__('Need this INI setting please: `phar.readonly = 0`.')); } if (!is_file($stub_file)) { throw $this->©exception($this->method(__FUNCTION__) . '#missing_stub_file', get_defined_vars(), $this->__('Unable to PHAR a directory; missing stub file.') . ' ' . sprintf($this->__('File does NOT exist: `%1$s`.'), $stub_file)); } if (!is_readable($stub_file)) { throw $this->©exception($this->method(__FUNCTION__) . '#stub_file_issues', get_defined_vars(), $this->__('Unable to PHAR a directory; permission issues with stub file.') . ' ' . sprintf($this->__('Need this file to be writable please: `%1$s`.'), $stub_file)); } // Phar class throws exceptions on failure. $_stub_file_is_phar_var = '$GLOBALS[\'is_phar_' . $this->©string->esc_sq($is_phar_var_suffix) . '\'] = \'phar://\'.__FILE__;'; $_stub_file_contents = $strip_ws ? $this->©php->strip_whitespace($stub_file) : file_get_contents($stub_file); $_stub_file_contents = trim(preg_replace('/\\W\\?\\>\\s*$/', '', $_stub_file_contents, 1)); // No close tag & trim. $_stub_file_contents = preg_replace('/\\<\\?php|\\<\\?/i', '<?php ' . $_stub_file_is_phar_var, $_stub_file_contents, 1); $_stub_file_contents = preg_replace('/\\W__HALT_COMPILER\\s*\\(\\s*\\)\\s*;/i', '', $_stub_file_contents, 1) . ' __HALT_COMPILER();'; $_phar = new \Phar($to, $this->iteration_flags()); $_phar->startBuffering(); // Don't create file yet (wait until we're done here). $_phar->setStub($_stub_file_contents); // Defines the stub for this PHAR file. if (!$strip_ws && !$compress) { $_phar->buildFromDirectory($dir); } else { $_strippable_extensions = array('php'); $_regex_compressable_extensions = $this->©string->preg_quote_deep($compressable_extensions, '/'); $_regex_compressable_extensions = '/\\.(?:' . implode('|', $_regex_compressable_extensions) . ')$/i'; $_temp_dir = $this->temp() . '/' . $this->©string->unique_id() . '-' . basename($dir); $this->copy_to($dir, $_temp_dir); $_temp_dir_iteration = $this->iteration($_temp_dir); if ($strip_ws) { foreach ($_temp_dir_iteration as $_dir_file) { if (!$_dir_file->isFile()) { continue; } $_path = $_dir_file->getPathname(); $_phar_path = $_dir_file->getSubPathName(); $_extension = $this->©file->extension($_path); if (in_array($_extension, $_strippable_extensions, TRUE)) { file_put_contents($_path, $this->©php->strip_whitespace($_path, TRUE)); } } } $_phar->buildFromDirectory($_temp_dir, $_regex_compressable_extensions); if ($compress && $_phar->count()) { // Compressing files? $_phar->compressFiles(\Phar::GZ); } foreach ($_temp_dir_iteration as $_dir_file) { if (!$_dir_file->isFile()) { continue; } $_path = $_dir_file->getPathname(); $_phar_path = $_dir_file->getSubPathName(); $_extension = $this->©file->extension($_path); if (!in_array($_extension, $compressable_extensions, TRUE)) { $_phar->addFile($_path, $_phar_path); } } } $_phar->stopBuffering(); // Write to disk now. unset($_phar, $_stub_file_is_phar_var, $_stub_file_contents, $_strippable_extensions, $_regex_compressable_extensions); unset($_temp_dir_iteration, $_dir_file, $_path, $_phar_path, $_extension); if (isset($_temp_dir)) { // A little more housekeeping now. $this->delete($_temp_dir); } unset($_temp_dir); return $to; // It's a good day in Eureka! }
/** * Creates a new PHAR archive based on the information passed to the constructor. * * @return void */ protected function buildFromDirectory() { $phar = new \Phar($this->pharName, $this->flags, $this->alias); $phar->buildFromDirectory($this->directory); }
/** * Generates a new phar archive. * * @param array $args The command line arguments. * * @return void */ public function run(array $args) { $this->parseArguments($args); $tempName = $this->copySource(); $phar = new Phar($this->getTargetPathname(), 0, $this->getAlias()); $phar->startBuffering(); $phar->buildFromDirectory($tempName); $phar->compressFiles(Phar::GZ); $phar->setStub($this->getStub()); $phar->stopBuffering(); chmod($this->getTargetPathname(), 0775); }
<?php try { $phar = new Phar(dirname(__FILE__) . '/buildfromiterator.phar'); $phar->buildFromDirectory('files', new stdClass()); } catch (Exception $e) { var_dump(get_class($e)); echo $e->getMessage() . "\n"; } ?> ===DONE=== <?php unlink(dirname(__FILE__) . '/buildfromiterator.phar'); __halt_compiler(); ?>
#!/usr/bin/env php <?php const PHAR_FILE = __DIR__ . '/../blackhole-bot.phar'; const EXEC_FILE = __DIR__ . '/../blackhole-bot'; $phar = new Phar(PHAR_FILE, 0, 'blackhole-bot.phar'); /** * Add files to phar */ $append = new AppendIterator(); $append->append(new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__ . '/../src/', FilesystemIterator::SKIP_DOTS))); $append->append(new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__ . '/../vendor/', FilesystemIterator::SKIP_DOTS))); $append->append(new ArrayIterator(['src/Config/Services/services.yml' => realpath(__DIR__ . '/../src/Config/Services/services.yml')])); $phar->addFromString('bin/blackhole', str_replace('#!/usr/bin/env php', '', file_get_contents(__DIR__ . '/../bin/blackhole'))); /** * Build the phar */ $phar->buildFromIterator($append, __DIR__ . '/..'); // start buffering. Mandatory to modify stub. $phar->startBuffering(); // Get the default stub. You can create your own if you have specific needs $defaultStub = $phar->createDefaultStub('bin/blackhole'); // Adding files $phar->buildFromDirectory(__DIR__, '/\\.php$/'); // Create a custom stub to add the shebang $stub = "#!/usr/bin/env php \n" . $defaultStub; // Add the stub $phar->setStub($stub); $phar->stopBuffering(); chmod(PHAR_FILE, 0755); rename(PHAR_FILE, EXEC_FILE);
<?php // $srcRoot = __DIR__."/../"; // $buildRoot = __DIR__."/../../bin"; // $vendorRoot = __DIR__."/../../vendor"; // // $phar = new Phar($buildRoot . "/juborm.phar", 0, "juborm.phar"); // $phar->buildFromDirectory("$srcRoot",'/.php$/'); // $files = $phar->buildFromDirectory("$vendorRoot/nategood/commando/src",'/.php$/'); // $files = $phar->buildFromDirectory("$vendorRoot/kevinlebrun/colors.php/lib",'/.php$/'); // // $phar->setStub($phar->createDefaultStub('Assistant/bootloader.php')); $srcRoot = __DIR__ . "/../.."; $buildRoot = __DIR__ . "/../../bin"; $phar = new Phar($buildRoot . "/juborm.phar", 0, "juborm.phar"); $files = $phar->buildFromDirectory("{$srcRoot}", '/.php$/'); $phar->setStub($phar->createDefaultStub('/src/Assistant/bootloader.php'));
<?php /** * Phreeze Command Line Phar Builder * * @example php build.php */ if (php_sapi_name() == 'cli') { $APP_ROOT = realpath("./"); set_include_path($APP_ROOT . '/../libs' . PATH_SEPARATOR . get_include_path()); require_once 'verysimple/Phreeze/Phreezer.php'; $version = Phreezer::$Version; $path = 'phreeze-' . $version . '.phar'; echo "Generating phreeze-" . $version . ".phar ...\n"; $archive = new Phar($path); $archive->buildFromDirectory('../libs'); $archive->setStub(file_get_contents('stub.php')); echo "Finished.\n"; } else { echo 'build.php should be run from the command line'; }
<?php /* * PHP Phar - How to create and use a Phar archive */ $p = new Phar('cmap.phar', 0, 'cmap'); //issue the Phar::startBuffering() method call to buffer changes made to the archive until you issue the Phar::stopBuffering() command $p->startBuffering(); //set the Phar file stub //the file stub is merely a small segment of code that gets run initially when the Phar file is loaded, //and it always ends with a __HALT_COMPILER() $p->setStub('#/usr/bin/php <?php Phar::mapPhar(); include "phar://cmap/cmap.php"; __HALT_COMPILER();?>'); //Adding files to an archive using Phar::buildFromDirectory() //adds all of the PHP files in the stated directory to the Phar archive $p->buildFromDirectory(__DIR__ . '/../src', '$(.*)\\.php$'); $p->buildFromDirectory(__DIR__ . '/../vendor', '$(.*)\\.php$'); $p->buildFromDirectory(__DIR__ . '/../.', '$(.*)\\.php$'); print_r($p); //Stop buffering write requests to the Phar archive, and save changes to disk $p->stopBuffering();
<?php $p = new Phar('bug53872-phar.phar'); $p->buildFromDirectory(__DIR__ . "/bug53872/"); $p->setStub('<?php __HALT_COMPILER();?\\>'); $p->compressFiles(Phar::GZ); print file_get_contents('phar://bug53872-phar.phar/first.txt'); print file_get_contents('phar://bug53872-phar.phar/second.txt'); print file_get_contents('phar://bug53872-phar.phar/third.txt');
#!/usr/bin/env php <?php $srcRoot = './src'; $buildRoot = './build'; $phar = new Phar($buildRoot . '/vagrantrunner.phar', FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::KEY_AS_FILENAME, 'vagrantrunner.phar'); // start buffering. Mandatory to modify stub. $phar->startBuffering(); // Get the default stub. You can create your own if you have specific needs $defaultStub = $phar->createDefaultStub('index.php'); // Adding files $phar->buildFromDirectory(__DIR__ . '/src'); // Create a custom stub to add the shebang $stub = "#!/usr/bin/php \n" . $defaultStub; // Add the stub $phar->setStub($stub); $phar->stopBuffering();
<?php // Create a new htrouter phar file @unlink('htrouter.phar'); $phar = new Phar('htrouter.phar', 0, 'htrouter.phar'); $basePath = realpath(dirname(__FILE__) . "/../htrouter"); $phar->buildFromDirectory($basePath, '/\\.php$/'); $phar->addFile(dirname(__FILE__) . '/stub.php', '/stub.php'); // Add stub $phar->setStub($phar->createDefaultStub('stub.php', 'stub.php'));
<?php $srcPath = __DIR__ . '/../lib'; $pharPath = __DIR__ . '/MailControl.phar'; if (file_exists($pharPath)) { unlink($pharPath); } $phar = new Phar($pharPath, Phar::CURRENT_AS_FILEINFO, basename($pharPath)); $phar->buildFromDirectory($srcPath, '/\\.php$/'); $phar->setStub($phar->createDefaultStub('stub.php')); require $pharPath;