Skip to content

Commit

Permalink
Properly parse binaries (#147)
Browse files Browse the repository at this point in the history
As now we have access to the content of the file, we can also check if a file is a PHP file based on its content. This ensure binary PHP files are scoped.

Also did a small refactoring regarding the order of the scopers registered for a micro-optimisation.
  • Loading branch information
theofidry authored Feb 6, 2018
1 parent a59b5fb commit 8008d45
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 7 deletions.
5 changes: 5 additions & 0 deletions src/Scoper/PhpScoper.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ final class PhpScoper implements Scoper
{
private const FILE_PATH_PATTERN = '/.*\.php$/';
private const NOT_FILE_BINARY = '/\..+?$/';
private const PHP_TAG = '/^<\?php/';
private const PHP_BINARY = '/^#!.+?php.*\n{1,}<\?php/';

private $parser;
Expand Down Expand Up @@ -70,6 +71,10 @@ private function isPhpFile(string $filePath, string $contents): bool
return false;
}

if (1 === preg_match(self::PHP_TAG, ltrim($contents))) {
return true;
}

return 1 === preg_match(self::PHP_BINARY, $contents);
}
}
16 changes: 9 additions & 7 deletions src/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@
use Symfony\Component\Console\Application as SymfonyApplication;
use Symfony\Component\Filesystem\Filesystem;

// TODO: register this file to the list of functions if possible to be autoloaded

/**
* @private
*/
Expand Down Expand Up @@ -87,14 +89,14 @@ function get_version(): string
function create_scoper(): Scoper
{
return new PatchScoper(
new JsonFileScoper(
new InstalledPackagesScoper(
new PhpScoper(
create_parser(),
new NullScoper(),
new TraverserFactory()
new PhpScoper(
create_parser(),
new JsonFileScoper(
new InstalledPackagesScoper(
new NullScoper()
)
)
),
new TraverserFactory()
)
);
}
Expand Down
27 changes: 27 additions & 0 deletions tests/Scoper/PhpScoperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,33 @@ public function test_does_not_scope_file_if_is_not_a_PHP_file()
$this->decoratedScoperProphecy->scope(Argument::cetera())->shouldHaveBeenCalledTimes(1);
}

public function test_can_scope_a_PHP_file_with_the_wrong_extension()
{
$prefix = 'Humbug';
$filePath = escape_path($this->tmp.'/file');
$patchers = [create_fake_patcher()];
$whitelist = ['Foo'];
$whitelister = create_fake_whitelister();

$contents = <<<'PHP'
<?php
echo "Humbug!";

PHP;

$expected = <<<'PHP'
<?php
echo "Humbug!";

PHP;

$actual = $this->scoper->scope($filePath, $contents, $prefix, $patchers, $whitelist, $whitelister);

$this->assertSame($expected, $actual);
}

public function test_can_scope_PHP_binary_files()
{
$prefix = 'Humbug';
Expand Down

0 comments on commit 8008d45

Please sign in to comment.