Skip to content

Commit

Permalink
Add Phar Bundler
Browse files Browse the repository at this point in the history
  • Loading branch information
paragonie-security committed Sep 9, 2021
1 parent 6ca896d commit 8ae290b
Show file tree
Hide file tree
Showing 3 changed files with 97 additions and 1 deletion.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -65,4 +65,4 @@ jobs:
composer-options: --ignore-platform-reqs

- name: PHPUnit tests
run: vendor/bin/phpunit
run: php -d phar.readonly=0 vendor/bin/phpunit
52 changes: 52 additions & 0 deletions lib/Release/Bundler/PharBundler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php
namespace ParagonIE\Gossamer\Release\Bundler;

use ParagonIE\Gossamer\GossamerException;
use Phar;

class PharBundler extends AbstractBundler
{
/** @var string $defaultStubFilename */
protected $defaultStubFilename = 'default-stub.php';

/**
* @param string $filename
* @return self
*/
public function setDefaultStubFilename($filename)
{
$this->assert(is_string($filename), "Argument 1 must be a string");
$this->defaultStubFilename = $filename;
return $this;
}

/**
* @return void
* @throws GossamerException
*/
public function throwIfPharReadonly()
{
$readOnly = (bool) ini_get('phar.readonly');
if ($readOnly) {
throw new GossamerException(
"Cannot work with Phars without setting readonly to false"
);
}
}

public function bundle($outputFile)
{
$this->throwIfPharReadonly();
$workingDir = \getcwd();
\chdir($this->directory);

$phar = new Phar($outputFile);
$phar->startBuffering();
$defaultStub = $phar->createDefaultStub($this->defaultStubFilename);
$phar->buildFromDirectory($this->directory);
$phar->setStub('#!/usr/bin/env php' . "\n" . $defaultStub);
$phar->stopBuffering();

\chdir($workingDir);
}
}
44 changes: 44 additions & 0 deletions tests/Release/Bundler/PharBundlerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php
namespace ParagonIE\Gossamer\Tests\Release\Bundler;

use Exception;
use ParagonIE\Gossamer\Release\Bundler\PharBundler;
use PHPUnit\Framework\TestCase;

/**
* @covers PharBundler
*/
class PharBundlerTest extends TestCase
{
/** @var string $dir */
protected $dir = '';

/**
* @before
*/
public function before()
{
$dir = __DIR__;
do {
$prev = $dir;
$dir = realpath(dirname($dir));
} while (!empty($dir) && $dir !== $prev && !is_dir($dir . '/.git'));
$this->dir = $dir;
}

/**
* @throws Exception
*/
public function testPhar()
{
if (ini_get('phar.readonly')) {
$this->markTestSkipped("phar.readonly is set to true");
}

$bundler = (new PharBundler())
->setWorkDirectory($this->dir . '/lib');
$bundler->bundle(dirname($this->dir) . '/test.phar');
$this->assertFileExists(dirname($this->dir) . '/test.phar');
unlink(dirname($this->dir) . '/test.phar');
}
}

0 comments on commit 8ae290b

Please sign in to comment.