Skip to content

Commit

Permalink
An attempt at re-scoping PHPStan
Browse files Browse the repository at this point in the history
  • Loading branch information
patrickkusebauch committed Mar 30, 2024
1 parent 79d2a70 commit 3684a49
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 2 deletions.
5 changes: 3 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@ help: ## Displays list of available targets with their descriptions


.PHONY: build
build: tests ## Runs tests and creates the phar-binary
$(BOX_BIN) compile
build: ## Creates the phar-binary
$(PHP_BIN) build/repack-phpstan.php
$(BOX_BIN) compile --no-parallel

.PHONY: composer-install
composer-install: ## Installs dependencies
Expand Down
69 changes: 69 additions & 0 deletions build/repack-phpstan.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
<?php

declare(strict_types=1);

require_once __DIR__.'/../vendor/autoload.php';

$datePrefix = (new DateTimeImmutable('now'))->format('Ym');
$prefix = 'DEPTRAC_'.$datePrefix;

// Path to the PHPStan PHAR
$phpstanPharPath = __DIR__.'/../vendor/phpstan/phpstan/phpstan.phar';

// Temporary directory for extraction and scoped files
$tempDir = __DIR__.'/deptrac-build/phpstan';

// Extract the PHAR
$phar = new Phar($phpstanPharPath);
$phar->extractTo($tempDir, null, true);

// Apply scoping to the extracted files
applyScoping($tempDir, $prefix);

// Repackage the scoped files into a new PHAR
repackagePhar($tempDir, $phpstanPharPath);

// Clean up the temporary directory
cleanup($tempDir);

echo "Scoped PHPStan PHAR created successfully!\n";

// Function to apply scoping
function applyScoping(string $directory, string $prefix): void
{
$finder = new Symfony\Component\Finder\Finder();
$finder->files()->in($directory);

foreach ($finder as $file) {
$contents = file_get_contents($file->getRealPath());
$scopedContents = preg_replace('/^namespace\s+(.+?);/m', 'namespace '.$prefix.'$1;', $contents);
file_put_contents($file->getRealPath(), $scopedContents);
}
}

// Function to repackage PHAR
function repackagePhar(string $directory, string $outputPhar): void
{
$phar = new Phar($outputPhar);
$phar->buildFromDirectory($directory);
$phar->setStub($phar->createDefaultStub('bootstrap.php'));
}

// Function to clean up temporary directory
function cleanup(string $directory): void
{
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST
);

foreach ($files as $file) {
if ($file->isDir()) {
rmdir($file->getRealPath());
} else {
unlink($file->getRealPath());
}
}

rmdir($directory);
}

0 comments on commit 3684a49

Please sign in to comment.