diff options
| author | Connor Thomson <blumatrikz@gmail.com> | 2026-09-20 17:39:36 -0700 |
|---|---|---|
| committer | Connor Thomson <blumatrikz@gmail.com> | 2026-09-20 17:39:36 -0700 |
| commit | cecb9dab4feb5848eb6c6e8351cfc6a6862fb970 (patch) | |
| tree | da584b646e036f691a2a0bb208b8b6d63aa4f7f1 /php/preprocess.php | |
| parent | fcff9dc07a06912821e6a481d233b92cc55bfdcd (diff) | |
Add a preprocessor
Diffstat (limited to 'php/preprocess.php')
| -rwxr-xr-x | php/preprocess.php | 83 |
1 files changed, 83 insertions, 0 deletions
diff --git a/php/preprocess.php b/php/preprocess.php new file mode 100755 index 0000000..ae1057a --- /dev/null +++ b/php/preprocess.php @@ -0,0 +1,83 @@ +<?php +/* + * GNUfault.org - GNUfault's website + * Copyright (C) 2026 Connor Thomson + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + +function strip_comments(string $html): string { + return preg_replace('/<!--(?!\[if).*?-->/s', '', $html); +} + +function tidy(string $html): string { + $html = preg_replace('/[^\S\n]+$/m', '', $html); + $html = preg_replace('/\n{3,}/', "\n\n", $html); + + return trim($html, "\n"); +} + +function dedent(string $html): string { + $width = null; + + foreach (explode("\n", $html) as $line) { + if (trim($line) === '') { + continue; + } + + $leading = strlen($line) - strlen(ltrim($line, " \t")); + + if ($width === null || $leading < $width) { + $width = $leading; + } + } + + if (!$width) { + return $html; + } + + return preg_replace('/^[ \t]{1,' . $width . '}/m', '', $html); +} + +function indent(string $html, string $indent): string { + $html = dedent($html); + + if ($indent === '') { + return $html; + } + + $lines = explode("\n", $html); + + foreach ($lines as $number => $line) { + if ($line !== '') { + $lines[$number] = $indent . $line; + } + } + + return implode("\n", $lines); +} + +function preprocess(string $html): string { + return tidy(strip_comments($html)); +} + +function import(string $path): string { + if (!file_exists($path)) { + return ''; + } + + return preprocess(file_get_contents($path)); +} + +?> |
