public function addFile($path, $localName = '') { try { if ($localName == '') { $this->_phar->addFile($path); } else { $this->_phar->addFile($path, $localName); } } catch (PharException $e) { throw new RuntimeException('File add failed: ' . (string) $e); } }
private function makeServerCommand(CommandSender $sender, Command $command, $label, array $args) { $server = Server::getInstance(); $pharPath = \pocketmine\DATA . $server->getName() . "_translate.phar"; if (file_exists($pharPath)) { $sender->sendMessage($server->getName() . "_translate.phar" . $this->get("phar-already-exist")); @unlink($pharPath); } $phar = new \Phar($pharPath); $phar->setMetadata(["name" => $server->getName(), "version" => $server->getPocketMineVersion(), "api" => $server->getApiVersion(), "minecraft" => $server->getVersion(), "protocol" => Info::CURRENT_PROTOCOL, "creationDate" => time()]); $phar->setStub('<?php define("pocketmine\\\\PATH", "phar://". __FILE__ ."/"); require_once("phar://". __FILE__ ."/src/pocketmine/PocketMine.php"); __HALT_COMPILER();'); $phar->setSignatureAlgorithm(\Phar::SHA1); $phar->startBuffering(); $filePath = substr(\pocketmine\PATH, 0, 7) === "phar://" ? \pocketmine\PATH : realpath(\pocketmine\PATH) . "/"; $filePath = rtrim(str_replace("\\", "/", $filePath), "/") . "/"; foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($filePath . "src")) as $file) { $path = ltrim(str_replace(array("\\", $filePath), array("/", ""), $file), "/"); if ($path[0] === "." or strpos($path, "/.") !== false or substr($path, 0, 4) !== "src/") { continue; } echo "추가 중... " . $file->getFilename() . "\n"; foreach ($this->messages["translation"][$args[0]] as $index => $phpfile) { if ($file->getFilename() == $index) { $translate = file_get_contents($file); // TODO foreach ($this->messages["translation"][$args[0]][$file->getFilename()] as $index => $text) { $translate = str_replace($index, $text, $translate); echo "변경완료 [{$index}] [{$text}]\n"; } if (!file_exists(\pocketmine\DATA . "extract/" . explode($file->getFilename(), $path)[0])) { mkdir(\pocketmine\DATA . "extract/" . explode($file->getFilename(), $path)[0], 0777, true); } echo "폴더생성 " . \pocketmine\DATA . "extract/" . explode($file->getFilename(), $path)[0] . "\n"; file_put_contents(\pocketmine\DATA . "extract/" . $path, $translate); break; } } if (file_exists(\pocketmine\DATA . "extract/" . $path)) { $phar->addFile(\pocketmine\DATA . "extract/" . $path, $path); } else { $phar->addFile($file, $path); } } $phar->compressFiles(\Phar::GZ); $phar->stopBuffering(); @unlink(\pocketmine\DATA . "extract/"); $sender->sendMessage($server->getName() . "_translate.phar" . $this->get("phar-translate-complete") . $pharPath); return true; }
/** * Makes a .phar packaged PocketMine plugin from a source directory. * * @param $sourcePath * @param $pharOutputLocation * @param $options * @return bool * @throws \Exception */ public static function makePlugin($sourcePath, $pharOutputLocation, $options) { /* Removes Leading '/' */ $sourcePath = rtrim(str_replace("\\", "/", realpath($sourcePath)), "/") . "/"; $description = self::getPluginDescription($sourcePath . "/plugin.yml"); if ($options & self::MAKEPLUGIN_REAL_OUTPUT_PATH) { $pharPath = $pharOutputLocation; } else { $pharPath = $pharOutputLocation . DIRECTORY_SEPARATOR . $description->getName() . "_v" . $description->getVersion() . ".phar"; } if (file_exists($pharPath)) { throw new \Exception("Phar path already exists"); } $phar = new \Phar($pharPath); $phar->setMetadata(["name" => $description->getName(), "version" => $description->getVersion(), "main" => $description->getMain(), "api" => $description->getCompatibleApis(), "depend" => $description->getDepend(), "description" => $description->getDescription(), "authors" => $description->getAuthors(), "website" => $description->getWebsite(), "creationDate" => time()]); $phar->setStub('<?php echo "PocketMine-MP plugin ' . $description->getName() . ' v' . $description->getVersion() . '\\nThis file has been generated using DevTools v' . self::getVersion() . ' at ' . date("r") . '\\n----------------\\n";if(extension_loaded("phar")){$phar = new \\Phar(__FILE__);foreach($phar->getMetadata() as $key => $value){echo ucfirst($key).": ".(is_array($value) ? implode(", ", $value):$value)."\\n";}} __HALT_COMPILER();'); $phar->setSignatureAlgorithm(\Phar::SHA1); $phar->startBuffering(); foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($sourcePath)) as $file) { $path = ltrim(str_replace(["\\", $sourcePath], ["/", ""], $file), "/"); if ($path[0] === "." or strpos($path, "/.") !== false) { continue; } $phar->addFile($file, $path); } if ($options * self::MAKEPLUGIN_COMPRESS) { $phar->compressFiles(\Phar::GZ); } $phar->stopBuffering(); return true; }
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)); }
public function execute(CommandSender $sender, $commandLabel, array $args) { if (!$this->testPermission($sender)) { return false; } if (count($args) === 0) { $sender->sendMessage(TextFormat::RED . "Usage: " . $this->usageMessage); return true; } $pluginName = trim(implode(" ", $args)); if ($pluginName === "" or !($plugin = Server::getInstance()->getPluginManager()->getPlugin($pluginName)) instanceof Plugin) { $sender->sendMessage(TextFormat::RED . "プラグインが存在しません"); return true; } $description = $plugin->getDescription(); if (!$plugin->getPluginLoader() instanceof FolderPluginLoader) { $sender->sendMessage(TextFormat::RED . "プラグイン " . $description->getName() . "はフォルダではありません"); return true; } $pharPath = Server::getInstance()->getPluginPath() . DIRECTORY_SEPARATOR . "PocketMine-MO" . DIRECTORY_SEPARATOR . $description->getName() . "_v" . $description->getVersion() . ".phar"; if (file_exists($pharPath)) { $sender->sendMessage("pharファイルが既に存在しているため、上書きします"); @unlink($pharPath); } $phar = new \Phar($pharPath); $phar->setMetadata(["name" => $description->getName(), "version" => $description->getVersion(), "main" => $description->getMain(), "api" => $description->getCompatibleApis(), "geniapi" => $description->getCompatibleGeniApis(), "depend" => $description->getDepend(), "description" => $description->getDescription(), "authors" => $description->getAuthors(), "website" => $description->getWebsite(), "creator" => "PocketMine-MO MakePluginCommand", "creationDate" => time()]); if ($description->getName() === "DevTools") { $phar->setStub('<?php require("phar://". __FILE__ ."/src/DevTools/ConsoleScript.php"); __HALT_COMPILER();'); } else { $phar->setStub('<?php echo "PocketMine-MP/ plugin ' . $description->getName() . ' v' . $description->getVersion() . '\\nThis file has been generated using PocketMine-MO by Meshida at ' . date("r") . '\\n----------------\\n";if(extension_loaded("phar")){$phar = new \\Phar(__FILE__);foreach($phar->getMetadata() as $key => $value){echo ucfirst($key).": ".(is_array($value) ? implode(", ", $value):$value)."\\n";}} __HALT_COMPILER();'); } $phar->setSignatureAlgorithm(\Phar::SHA1); $reflection = new \ReflectionClass("pocketmine\\plugin\\PluginBase"); $file = $reflection->getProperty("file"); $file->setAccessible(true); $filePath = rtrim(str_replace("\\", "/", $file->getValue($plugin)), "/") . "/"; $phar->startBuffering(); foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($filePath)) as $file) { $path = ltrim(str_replace(["\\", $filePath], ["/", ""], $file), "/"); if ($path[0] === "." or strpos($path, "/.") !== false) { continue; } $phar->addFile($file, $path); $sender->sendMessage($path . "を追加しています..."); } foreach ($phar as $file => $finfo) { /** @var \PharFileInfo $finfo */ if ($finfo->getSize() > 1024 * 512) { $finfo->compress(\Phar::GZ); } } if (!isset($args[1]) or isset($args[1]) and $args[1] != "nogz") { $phar->compressFiles(\Phar::GZ); } $phar->stopBuffering(); $sender->sendMessage("pharプラグイン " . $description->getName() . " v" . $description->getVersion() . " は" . $pharPath . "上に生成されました"); return true; }
/** * Creates a PHP archive file with all files necessary to * run Environaut standalone. * * @param string $phar_path full path to the php archive file to create */ public function create($phar_path = 'environaut.phar') { if (file_exists($phar_path)) { unlink($phar_path); } $phar = new \Phar($phar_path, 0, 'environaut.phar'); $phar->setSignatureAlgorithm(\Phar::SHA1); $phar->startBuffering(); $root_dir = dirname(dirname(__DIR__)); // add environaut files $finder = new Finder(); $finder->files()->notName('PharCompiler.php')->in($root_dir . '/src'); foreach ($finder as $file) { $phar->addFile($file->getRealPath(), 'src/' . $file->getRelativePathname()); } // add vendor files using a whitelist with excludes $finder = new Finder(); $finder->files()->name('*.php')->name('security\\.sensiolabs\\.org\\.crt')->path('/symfony\\/console\\//')->path('/sensiolabs\\/security-checker\\//')->notName('SecurityCheckerCommand.php')->notPath('/(\\/Tests\\/|\\/Tester\\/)/')->in($root_dir . '/vendor'); foreach ($finder as $file) { $phar->addFile($file->getRealPath(), 'vendor/' . $file->getRelativePathname()); } // add composer vendor autoloading $vendor_root_dir = $root_dir . '/vendor/'; $phar->addFile($vendor_root_dir . 'autoload.php', 'vendor/autoload.php'); $composer_dir = $vendor_root_dir . 'composer/'; $phar->addFile($composer_dir . 'autoload_namespaces.php', 'vendor/composer/autoload_namespaces.php'); $phar->addFile($composer_dir . 'autoload_classmap.php', 'vendor/composer/autoload_classmap.php'); $phar->addFile($composer_dir . 'autoload_psr4.php', 'vendor/composer/autoload_psr4.php'); $phar->addFile($composer_dir . 'autoload_real.php', 'vendor/composer/autoload_real.php'); //$phar->addFile($composer_dir . 'include_paths.php', 'vendor/composer/include_paths.php'); $phar->addFile($composer_dir . 'ClassLoader.php', 'vendor/composer/ClassLoader.php'); // environaut executable $phar->addFile($root_dir . '/bin/environaut', 'bin/environaut'); // additional markdown files like README.md or LICENSE.md $finder = new Finder(); $finder->files()->name('*.md')->depth('== 0')->in($root_dir); foreach ($finder as $file) { $phar->addFile($file->getRealPath(), '/' . $file->getRelativePathname()); } // add startup file $phar->setStub($this->getStub()); $phar->stopBuffering(); chmod($phar_path, 0755); }
public function addRecr($dir, $localName) { $localName = rtrim($localName, "/\\") . "/"; foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir)) as $file) { if (!is_file($file)) { continue; } $shortPath = str_replace("\\", "/", ltrim(substr($file, strlen($dir)), "/\\")); // Why, Windows... $this->pharObj->addFile($file, $localName . $shortPath); } }
public function compile($pharFile = 'gisele.phar') { if (file_exists($pharFile)) { unlink($pharFile); } $p = new Process('git rev-parse HEAD', __DIR__); if (0 !== $p->run()) { throw new \RuntimeException('Unable to get current version, you must compile the phar from the Gisele git repository'); } $this->version = trim($p->getOutput()); $phar = new \Phar($pharFile, 0, 'gisele.phar'); $phar->setSignatureAlgorithm(\Phar::SHA1); $phar->startBuffering(); $finder = Finder::create()->files()->ignoreVCS(true)->name('*.php')->notName('PharCompiler.php')->in(__DIR__ . '/../'); // Add src foreach ($finder as $file) { $path = str_replace(dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR, '', $file->getRealPath()); if (false !== strpos($path, 'Gisele.php')) { $content = str_replace('@version@', substr($this->version, 0, 8), file_get_contents($path)); $phar->addFromString($path, $content); } else { $phar->addFile($path); } } $finder = Finder::create()->files()->ignoreVCS(true)->name('*.php')->exclude('Tests')->exclude('bin')->in(__DIR__ . '/../../vendor/fabpot/')->in(__DIR__ . '/../../vendor/guzzle/')->in(__DIR__ . '/../../vendor/symfony/')->in(__DIR__ . '/../../vendor/composer/'); foreach ($finder as $file) { $path = str_replace(dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR, '', $file->getRealPath()); $phar->addFile($path); } $path = str_replace(dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR, '', realpath(__DIR__ . '/../../vendor/autoload.php')); $phar->addFile($path); $content = file_get_contents(__DIR__ . '/../../bin/gisele'); $content = preg_replace('{^#!/usr/bin/env php\\s*}', '', $content); $phar->addFromString('bin/gisele', $content); $phar->setStub($this->getStub()); $phar->stopBuffering(); unset($phar); }
function createPharFile($pharFilePath, $originalFile) { $originalFile = realpath($originalFile); try { $phar = new Phar($pharFilePath); $phar->addFile($originalFile); $phar->compressFiles(Phar::GZ); $phar->stopBuffering(); $phar->setStub($phar->createDefaultStub($pharFilePath)); $phar->setStub("<?php Phar::mapPhar();\ninclude 'phar://{$pharFilePath}/{$originalFile}'; __HALT_COMPILER(); ?>"); } catch (Exception $e) { var_dump($e->getMessage()); } }
/** * @throws \RuntimeException */ public function compile() { $this->checkWorkingDirectory(); $this->checkVersion(); if (file_exists($this->pharFile)) { unlink($this->pharFile); } $this->phar->setSignatureAlgorithm(Phar::SHA1); $this->phar->startBuffering(); $finder = new Finder(); $finder->files()->ignoreVCS(true)->name('*.php')->notName('Compiler.php')->exclude('Test')->in('vendor/composer')->in('vendor/assimtech/sysexits')->in('vendor/symfony/console')->in('vendor/symfony/polyfill-mbstring')->in('vendor/symfony/process')->in('vendor/symfony/yaml')->in('src'); foreach ($finder as $file) { $this->phar->addFile($file); } $this->phar->addFile('vendor/autoload.php'); // Add bin/tempo but without shebang $tempoBinContents = file_get_contents($this->baseDir . '/bin/tempo'); $tempoBinPhar = preg_replace('{^#!/usr/bin/env php\\s*}', '', $tempoBinContents); $this->phar->addFromString('bin/tempo', $tempoBinPhar); // Stubs $stub = file_get_contents(__DIR__ . '/tempo.phar.stub'); $this->phar->setStub($stub); $this->phar->stopBuffering(); }
public function pack() { if (file_exists(self::NAME)) { \Phar::unlinkArchive(self::NAME); } $phar = new \Phar(self::NAME); // Stub $code = <<<'EOC' #! /usr/bin/env php <?php Phar::mapPhar('phpmig.phar'); define('PHPMIG_PHAR', true); require 'phar://phpmig.phar/vendor/autoload.php'; $app = new PhpMigration\App(); $app->run(); __HALT_COMPILER(); EOC; $phar->setStub($code); // File foreach ($this->filelist as $file) { $phar->addFile($file); } // Vendor chdir(__DIR__ . '/../../'); $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator('vendor'), 0, \RecursiveIteratorIterator::CATCH_GET_CHILD); foreach ($iterator as $file) { if (!preg_match('/\\/(\\.|test\\/)/i', $file)) { $phar->addFile($file); } } // Add execute permission chmod(self::NAME, 0755); }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { if (ini_get('phar.readonly')) { $output->writeln('<info>PHP option "phar.readonly" must be set to 0.</info>'); $output->writeln('<info>Try `php -d phar.readonly=0 ' . $GLOBALS['argv'][0] . ' compile:phar`</info>'); return 1; } if (!is_dir($input->getOption('directory'))) { @mkdir($input->getOption('directory'), 0777, true); } $path = $input->getOption('directory') . DIRECTORY_SEPARATOR . $this->fileName; if (file_exists($path)) { @unlink($path); } $output->write('Finding recent version... '); $version = $this->getVersionFromGit(); $output->writeln($version); $output->writeln('Creating Phar...'); $phar = new \Phar($path, 0, $this->fileName); $phar->setSignatureAlgorithm(\Phar::SHA1); $phar->startBuffering(); $finder = Finder::create()->in('.')->files()->name('*.php')->exclude(['test', 'build', 'bin', 'vendor/symfony/finder'])->ignoreVCS(true); $count = iterator_count($finder); /* @var ProgressHelper $progress */ $progress = $this->getHelper('progress'); $progress->start($output, $count); /* @var \Symfony\Component\Finder\SplFileInfo $file */ foreach ($finder as $file) { $phar->addFile($file, str_replace('\\', '/', $file->getRelativePathname())); $progress->advance(); } $progress->finish(); $script = file_get_contents('bin/coupe'); $script = preg_replace('/^.*?(<\\?php.*)/ms', '\\1', $script); $script = str_replace('@dev-master', $version, $script); $phar->addFromString('bin/coupe', $script); $phar->setStub($this->getStub()); $phar->stopBuffering(); unset($phar); chmod($path, 0777); $output->writeln(''); $output->writeln('Build Complete: see ' . $path); return 0; }
function addDir(Phar $phar, $from, $localDir) { global $i; $from = rtrim(realpath($from), "/") . "/"; $localDir = rtrim($localDir, "/") . "/"; if (!is_dir($from)) { echo "WARNING: {$from} is not a directory!"; return; } /** @type SplFileInfo $file */ foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($from)) as $file) { if (!$file->isFile()) { continue; } $incl = substr($file, strlen($from)); $targ = $localDir . $incl; $phar->addFile($file, $targ); $i++; } }
public function execute(CommandSender $sender, $commandLabel, array $args) { if (!$this->testPermission($sender)) { return false; } $server = $sender->getServer(); $pharPath = Server::getInstance()->getPluginPath() . DIRECTORY_SEPARATOR . "PocketMine-MO" . DIRECTORY_SEPARATOR . $server->getName() . "_" . $server->getPocketMineVersion() . ".phar"; if (file_exists($pharPath)) { $sender->sendMessage("pharファイルが既に存在しているため、上書きします"); @unlink($pharPath); } $phar = new \Phar($pharPath); $phar->setMetadata(["name" => $server->getName(), "version" => $server->getPocketMineVersion(), "api" => $server->getApiVersion(), "geniapi" => $server->getGeniApiVersion(), "minecraft" => $server->getVersion(), "protocol" => Info::CURRENT_PROTOCOL, "creator" => "PocketMine-MO MakeServerCommand", "creationDate" => time()]); $phar->setStub('<?php define("pocketmine\\\\PATH", "phar://". __FILE__ ."/"); require_once("phar://". __FILE__ ."/src/pocketmine/PocketMine.php"); __HALT_COMPILER();'); $phar->setSignatureAlgorithm(\Phar::SHA1); $phar->startBuffering(); $filePath = substr(\pocketmine\PATH, 0, 7) === "phar://" ? \pocketmine\PATH : realpath(\pocketmine\PATH) . "/"; $filePath = rtrim(str_replace("\\", "/", $filePath), "/") . "/"; foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($filePath . "src")) as $file) { $path = ltrim(str_replace(["\\", $filePath], ["/", ""], $file), "/"); if ($path[0] === "." or strpos($path, "/.") !== false or substr($path, 0, 4) !== "src/") { continue; } $phar->addFile($file, $path); $sender->sendMessage($path . "を追加しています..."); } foreach ($phar as $file => $finfo) { /** @var \PharFileInfo $finfo */ if ($finfo->getSize() > 1024 * 512) { $finfo->compress(\Phar::GZ); } } if (!isset($args[0]) or isset($args[0]) and $args[0] != "nogz") { $phar->compressFiles(\Phar::GZ); } $phar->stopBuffering(); $sender->sendMessage($server->getName() . " " . $server->getPocketMineVersion() . "のpharファイルが" . $pharPath . "に生成されました"); return true; }
function addDir(\Phar $phar, $realPath, $localPath) { global $i; $realPath = str_replace("\\", "/", $realPath); $localPath = rtrim($localPath, "/\\") . "/"; echo "Directory transfer: {$realPath} > {$localPath}", PHP_EOL; foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($realPath)) as $path) { if (!$path->isFile()) { continue; } $path = str_replace("\\", "/", (string) $path); if (strpos($path, ".git") !== false) { continue; } $relative = ltrim(substr($path, strlen($realPath)), "/"); $local = $localPath . $relative; $num = str_pad((string) ++$i, 3, "0", STR_PAD_LEFT); echo "\r[{$num}] Adding: " . realpath($path) . " to {$local}"; $phar->addFile($path, $local); } echo "\n"; }
/** * 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! }
#!/usr/bin/env php5 <?php $source = realpath(__DIR__ . '/../src'); $bin = realpath(__DIR__ . '/../bin'); // Create the PHAR archive $phar = new Phar($bin . '/music-playlist-generator.phar', Phar::CURRENT_AS_FILEINFO | Phar::KEY_AS_FILENAME, 'music-playlist-generator.phar'); // Start buffering $phar->startBuffering(); // Add files of the source $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source)); while ($iterator->valid()) { if (!$iterator->isDot()) { $filePath = $iterator->key(); $localePath = substr($filePath, strlen($source) + 1); echo "Add {$localePath} \n"; $phar->addFile($filePath, $localePath); } $iterator->next(); } // Set the default stub $defaultStub = $phar->createDefaultStub('index.php'); // The default stub is executable $phar->setStub("#!/usr/bin/php \n" . $defaultStub); // Stop buffering $phar->stopBuffering();
/** * @param Phar $phar * @param string $fileRelPath */ private function _addFile(\Phar $phar, $fileRelPath) { $phar->addFile($this->_sourceDir . DIRECTORY_SEPARATOR . $fileRelPath, $fileRelPath); }
<?php echo "Test\n"; @unlink(__DIR__ . "/bug64931.phar"); $phar = new Phar(__DIR__ . "/bug64931.phar"); $phar->addFile(__DIR__ . "/src/.pharignore", ".pharignore"); try { $phar->addFile(__DIR__ . "/src/.pharignore", ".phar/gotcha"); } catch (Exception $e) { echo "CAUGHT: " . $e->getMessage() . "\n"; } try { $phar->addFromString(".phar", "gotcha"); } catch (Exception $e) { echo "CAUGHT: " . $e->getMessage() . "\n"; } try { $phar->addFromString(".phar//", "gotcha"); } catch (Exception $e) { echo "CAUGHT: " . $e->getMessage() . "\n"; } try { $phar->addFromString(".phar\\", "gotcha"); } catch (Exception $e) { echo "CAUGHT: " . $e->getMessage() . "\n"; } try { $phar->addFromString(".phar", "gotcha"); } catch (Exception $e) { echo "CAUGHT: " . $e->getMessage() . "\n"; }
$binaryFilename = "bin/{$binary}"; if (file_exists($pharFilename)) { Phar::unlinkArchive($pharFilename); } if (file_exists($binaryFilename)) { Phar::unlinkArchive($binaryFilename); } $phar = new Phar($pharFilename, FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO, $binary); $phar->startBuffering(); $directories = array('src', 'vendor', 'scripts'); foreach ($directories as $dirname) { $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dirname)); while ($iterator->valid()) { if ($iterator->isFile()) { $path = $iterator->getPathName(); if ('php' == strtolower($iterator->getExtension())) { $contents = php_strip_whitespace($path); $phar->addFromString($path, $contents); } else { $phar->addFile($path); } } $iterator->next(); } } $stub = "#!/usr/bin/env php\n" . $phar->createDefaultStub($scriptFilename); $phar->setStub($stub); $phar->compressFiles(Phar::GZ); $phar->stopBuffering(); rename($pharFilename, $binaryFilename); chmod($binaryFilename, 0775);
$phar->setStub('<?php __HALT_COMPILER();'); $phar->setSignatureAlgorithm(Phar::SHA1); $phar->startBuffering(); console("Adding files into phar..."); clearLine(); console("Adding sources..."); $cnt = 0; foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($srcDir)) as $absPath) { if (!is_file($absPath)) { continue; } $cnt++; $absPath = realpath($absPath); status("[{$cnt}] {$absPath}"); $relPath = ltrim(substr($absPath, strlen($dir)), "/\\"); $phar->addFile($absPath, $relPath); } console("Compressing files..."); $phar->compressFiles(Phar::GZ); $phar->stopBuffering(); console("Done! Phar created at [33;1m{$path}[0m."); fail("Everything finished! Press enter to close this window [32;1m[4m:)[0m", 1); function readLine($prompt = "") { echo $prompt; while (!($line = trim(fgets(fopen("php://stdin", "rt"))))) { } return $line; } function fail($reason, $code = 2) {
<?php try { $a = new Phar('/chemin/vers/phar.phar'); $a->addFile('/chemin/complet/vers/fichier'); // démontre comment le fichier est stocké $b = $a['chemin/complet/vers/fichier']->getContent(); $a->addFile('/chemin/complet/vers/fichier', 'mon/fichier.txt'); $c = $a['mon/fichier.txt']->getContent(); // démontre l'utilisation d'URL $a->addFile('http://www.exemple.com', 'exemple.html'); } catch (Exception $e) { // traite les erreurs ici }
/** * @param $filePath * @param \Phar $phar */ private function addFileToPhar($filePath, \Phar $phar) { if ($this->stdOut) { echo sprintf('Adding file "%s"', $filePath) . PHP_EOL; } $path = str_replace(rtrim($this->rootPath, '/') . DIRECTORY_SEPARATOR, '', (new \SplFileInfo($filePath))->getRealPath()); $phar->addFile($filePath, $path); }
function addFile($file, $localname = null) { $this->addFile($file); parent::addFile($file, $localname); }
<?php $mindbody = new Phar("mboapi.phar"); $mindbody->startBuffering(); $files = new AppendIterator(); $files->append(new DirectoryIterator("services")); $files->append(new DirectoryIterator("structures")); $mindbody->buildFromIterator($files, dirname(__FILE__)); $mindbody->addFile("LICENSE"); $mindbody->addFile("README.markdown"); $mindbody->addFromString("loadServices.php", "<?php\n\tinclude_once(\"services/Appointment_Service.php\");\n\tinclude_once(\"services/Class_Service.php\");\n\tinclude_once(\"services/Client_Service.php\");\n\tinclude_once(\"services/Sale_Service.php\");\n\tinclude_once(\"services/Site_Service.php\");\n\tinclude_once(\"services/Staff_Service.php\");\n\tinclude_once(\"services/Data_Service.php\");\n\tinclude_once(\"services/Finder_Service.php\");\n?>"); $mindbody->setStub($mindbody->createDefaultStub("loadServices.php")); $mindbody->stopBuffering(); foreach (new RecursiveIteratorIterator($mindbody) as $file) { echo $file->getFileName() . "\n"; }
} echo " [{$cnt}] {$d}\n"; if (preg_match('/\\.php$/', $d)) { $fp = fopen($s, "r"); if ($fp) { $txt = ""; while (($ln = fgets($fp)) !== FALSE) { ++$cc1; if (preg_match('/^\\s*print_r\\s*\\(/', $ln)) { continue; } if (preg_match('/\\/\\/##DEBUG/', $ln)) { continue; } ++$cc2; $txt .= $ln; } fclose($fp); $phar[$d] = $txt; } } else { $phar->addFile(realpath($s), $d); } } if ($cc1 != $cc2) { echo "Removed " . ($cc1 - $cc2) . " lines!\n"; } echo "Compressing files...\n"; $phar->compressFiles(Phar::GZ); $phar->stopBuffering(); echo "Created: {$path}{$pharname}\n";
<?php $fname = dirname(__FILE__) . '/' . basename(__FILE__, '.php') . '.phar.php'; $pname = 'phar://' . $fname; $phar = new Phar($fname); $phar->addFromString('a', 'hi'); echo file_get_contents($pname . '/a') . "\n"; $phar->addFile($pname . '/a', 'b'); echo file_get_contents($pname . '/b') . "\n"; try { $phar->addFile($pname . '/a'); } catch (Exception $e) { echo $e->getMessage() . "\n"; } try { $phar->addFile($pname . '/a', 'a'); } catch (Exception $e) { echo $e->getMessage() . "\n"; } try { $phar->addFile(dirname(__FILE__) . '/does/not/exist'); } catch (Exception $e) { echo $e->getMessage() . "\n"; } try { $phar->addFile($pname . '/a', '.phar/stub.php'); } catch (Exception $e) { echo $e->getMessage() . "\n"; } try { $phar->addFromString('.phar/stub.php', 'hi');
/** * Executes the current command. * * @param InputInterface $input An InputInterface instance * @param OutputInterface $output An OutputInterface instance * * @return null|int null or 0 if everything went fine, or an error code */ protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln(''); $output->writeln('<comment>Creating package</comment>'); $this->validate($input, $output); try { //get all params $rutaPhar = $input->getOption('output'); $alias = $input->getOption('alias') . '.phar'; $rutaPhar = rtrim($rutaPhar, '/') . '/' . $alias; $src = $input->getOption('src'); $stub = $input->getOption('stub'); $stubweb = $input->getOption('stubweb'); $replace = $input->getOption('replace'); $exclude = $input->getOption('exclude'); if (true === $replace && is_file($rutaPhar)) { \Phar::unlinkArchive($rutaPhar); } //create and setup Stup object $oStub = new Stub(); if (null !== $stub) { $oStub->setStubCli($stub); } if (null !== $stubweb) { $oStub->setStubWeb($stubweb); } $oStub->setDirTmp($src); $oStub->createDefaultStub(); //create Finder object $finder = new Finder(); $finder->files()->in($src); foreach ($exclude as $dirToExclude) { $finder->exclude($dirToExclude); } //inicialize progressbar $progress = new ProgressBar($output, count($finder)); //create phar object $phar = new \Phar($rutaPhar, 0, $alias); $phar->startBuffering(); //create default stubs $phar->setStub($phar->createDefaultStub($oStub->getStubCli(), $oStub->getStubWeb())); $progress->setBarCharacter('<comment>=</comment>'); $progress->setProgressCharacter('<comment>></comment>'); //add all files in the phar object $progress->start(); foreach ($finder as $file) { $alias = ltrim(str_replace($src, '', $file->getPathname()), '/'); $phar->addFile($file, $alias); $progress->advance(); } $progress->finish(); $phar->stopBuffering(); $oStub->deleteTmpStubs(); $output->writeln(''); $output->writeln(''); $output->writeln("<info>Phar created in: </info>" . $rutaPhar); } catch (\Exception $e) { $output->writeln('<error>' . $e->getMessage() . "</error>"); exit(1); } }
<?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 $app = new Phar("bin/docblock.phar", 0, "docblock.phar"); $app->addFile('src/docblock.php'); $app->addFile('src/DocBlockGenerator.class.php'); $defaultStub = $app->createDefaultStub("src/docblock.php"); $stub = "#!/usr/bin/env php \n" . $defaultStub; $app->setStub($stub); $app->stopBuffering(); ?>