Skip to content

Instantly share code, notes, and snippets.

@tegos
Created March 16, 2025 12:30
Show Gist options
  • Save tegos/0fa95dbf5dbce39b969399dd7161921b to your computer and use it in GitHub Desktop.
Save tegos/0fa95dbf5dbce39b969399dd7161921b to your computer and use it in GitHub Desktop.
Detecting Forbidden Functions in Laravel with PHPUnit
<?php
declare(strict_types=1);
namespace Tests\Unit\Architecture;
use Illuminate\Support\Facades\App;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use RegexIterator;
use SplFileInfo;
use Tests\TestCase;
final class ForbiddenFunctionTest extends TestCase
{
public function test_forbidden_functions()
{
$forbiddenFunctions = [
'dd', 'dump', 'exit', 'die', 'print_r', 'var_dump', 'echo', 'print',
];
$files = $this->getPhpFiles(App::path());
foreach ($files as $file) {
$content = file_get_contents($file->getPathname());
foreach ($forbiddenFunctions as $function) {
$pattern = '/\b' . preg_quote($function, '/') . '\s*\(/';
$matches = [];
preg_match_all($pattern, $content, $matches, PREG_OFFSET_CAPTURE);
foreach ($matches[0] as $match) {
$lineNumber = substr_count(substr($content, 0, $match[1]), "\n") + 1;
$this->fail("Forbidden function '$function' found in file: $file:$lineNumber");
}
}
}
$this->expectNotToPerformAssertions();
}
/**
* @return SplFileInfo[]
*/
protected function getPhpFiles(string $directory): array
{
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($directory)
);
$phpFiles = new RegexIterator($iterator, '/\.php$/');
return iterator_to_array($phpFiles);
}
}
@tegos
Copy link
Author

tegos commented Mar 16, 2025

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment