php-makephar/src/MakePhar/PharBuilder.php

78 lines
2.1 KiB
PHP

<?php
namespace MakePhar;
class PharBuilder
{
protected $manifest;
protected $files = [];
protected $phar;
public function __construct(Manifest $manifest)
{
$this->manifest = $manifest;
}
public function prepare()
{
log_debug("Finding files to add...");
$this->files = $this->manifest->findSourceFiles();
log_debug("Found %d files", count($this->files));
}
public function build()
{
// Create the phar
$phar = new \Phar("/tmp/output.phar");
// Add files
log_debug("Adding files to phar archive...");
foreach ($this->files as $file) {
$phar->addFile($file->dest?:$file->src, $file->src);
}
// Create stub
if ($this->manifest->getIsLibrary()) {
log_debug("Creating library stub...");
// Create library stub
$stub = '<?php ';
$stub.= 'if (basename(__FILE__)==basename($_SERVER["SCRIPT_FILENAME"])) { echo "Error: This is a library and can not be executed\n"; exit(1); }';
$stub.= 'require_once __DIR__."/vendor/autoload.php";';
$phar->addFromString("index.php", $stub);
} else {
log_debug("Creating application stub...");
// Write application stub
$stubfile = $this->manifest->getStubFile();
$stub = '<?php require_once __DIR__."/'.ltrim($stubfile,'/').'";';
$phar->addFromString("index.php", $stub);
// Make the phar stub executable
$mainstub = $phar->createDefaultStub("index.php");
$mainstub = "#!/usr/bin/env php\n{$mainstub}";
$phar->setStub($mainstub);
}
// Close the phar
$phar = null;
}
public function finalize()
{
$output = $this->manifest->getOutput();
if (file_exists($output)) {
unlink($output);
}
log_debug("Writing %s", $output);
rename("/tmp/output.phar", $output);
if (!$this->manifest->getIsLibrary()) {
chmod($output, 0777);
}
}
}