Skip to content

Instantly share code, notes, and snippets.

@szepeviktor
Last active November 26, 2023 20:39
Show Gist options
  • Save szepeviktor/61339b8f9862ed11737d6cb9f8af0019 to your computer and use it in GitHub Desktop.
Save szepeviktor/61339b8f9862ed11737d6cb9f8af0019 to your computer and use it in GitHub Desktop.
indent detector
#!/usr/bin/env php
<?php
declare(strict_types=1);
const INDENT_CHAR = ' ';
const INDENT_SIZE = 4;
const END_OF_LINE = "\n";
function exitWith(int $exitStatus, string $message): void
{
error_log($message);
exit($exitStatus);
}
function detect(string $filePath): void
{
$contents = file_get_contents($filePath);
if ($contents === false) {
exitWith(10, sprintf('File not found: %s', $filePath));
}
$previousIndent = 0;
foreach (explode(END_OF_LINE, $contents) as $lineNumber => $line) {
$indent = strspn($line, INDENT_CHAR);
// DocBlock
if ($indent === $previousIndent + 1 && substr($line, $indent, 1) === '*') {
$indent -= 1;
}
// DBG printf("%d: (%d) %d\n", $lineNumber, $previousIndent, $indent);
if ($lineNumber === 0 && $indent !== 0) {
exitWith(11, sprintf('First line indented in %s:%d', $filePath, $lineNumber + 1));
}
if ($indent < $previousIndent && $indent % INDENT_SIZE !== 0) {
exitWith(12, sprintf('Indentation is smaller in %s:%d', $filePath, $lineNumber + 1));
}
if ($indent > $previousIndent && $indent !== $previousIndent + INDENT_SIZE) {
exitWith(13, sprintf('Indentation does not match in %s:%d', $filePath, $lineNumber + 1));
}
if ($line !== '') {
$previousIndent = $indent;
}
}
}
detect($argv[1]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment