Created
March 16, 2025 12:30
-
-
Save tegos/0fa95dbf5dbce39b969399dd7161921b to your computer and use it in GitHub Desktop.
Detecting Forbidden Functions in Laravel with PHPUnit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Read the full article