Created
June 15, 2024 15:29
-
-
Save caendesilva/0be5301d142385f70caf3922a34ab525 to your computer and use it in GitHub Desktop.
A simple file linter written in PHP
This file contains 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); | |
write('Running file Linter!', '32'); | |
const PATTERN = '/src/*.php'; | |
$files = glob(__DIR__ . '/' . ltrim(PATTERN, '/'); | |
$exitCode = 0; | |
foreach ($files as $file) { | |
write(' Linting file '.basename($file), '33'); | |
try { | |
lint($file); | |
} catch (RuntimeException $exception) { | |
write(' '.$exception->getMessage(), '31'); | |
$exitCode = 1; | |
} | |
} | |
function write(string $line, string $color = null): void | |
{ | |
if ($color) { | |
$line = "\033[{$color}m$line\033[0m"; | |
} | |
echo $line . PHP_EOL; | |
} | |
function lint(string $file): void | |
{ | |
$contents = file_get_contents($file); | |
$filename = basename($file); | |
if (false === $contents) { | |
throw new RuntimeException("Could not read file: $filename"); | |
} | |
if (empty(trim($contents))) { | |
throw new RuntimeException("File is empty: $filename"); | |
} | |
foreach (explode(PHP_EOL, $contents) as $line) { | |
if (str_contains($line, "\t")) { | |
throw new RuntimeException("File contains tabs: $filename"); | |
} | |
if ($line !== rtrim($line)) { | |
throw new RuntimeException("File contains trailing whitespace: $filename"); | |
} | |
} | |
} | |
write("\nLinting complete!", '32'); | |
exit($exitCode); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment