Created
November 7, 2026 13:48
-
-
Save dg/ec6ee5335db26443660eb9dd367b1bf6 to your computer and use it in GitHub Desktop.
Adds the missing comma between the name and the arguments of Latte tags ({control}, {link}, n:href, {include}, ...) without changing what templates do
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); | |
| /** | |
| * Adds the missing comma between the name and the arguments of Latte tags: | |
| * {control poll 1, 'foo'} -> {control poll, 1, 'foo'} | |
| * {link Product:show $id} -> {link Product:show, $id} | |
| * <a n:href="Product:show $id"> -> <a n:href="Product:show, $id"> | |
| * | |
| * Covers {control}, {form}, {input}, {label}, {link}, {plink}, n:href, {include}, {import}, {embed}, {define} and {sandbox}. | |
| * A comma is kept only where the template compiles to exactly the same code as before, | |
| * so the script never changes what a template does. Tags where a comma after the name would change | |
| * the compiled code are listed for a manual check; they are most likely broken already. | |
| * | |
| * Usage (from the root of your project): | |
| * php latte-comma.php [--dry-run] [--bootstrap=<file>] <dir|file>... | |
| * | |
| * --dry-run show what would change, write nothing | |
| * --bootstrap=<file> PHP file returning your configured Latte\Engine, needed when templates use your own tags, | |
| * for example the one created by the LatteFactory service of your DI container | |
| * | |
| * Options go before the paths. Commit your templates first, so you can review the changes with git diff. | |
| */ | |
| $options = getopt('', ['dry-run', 'bootstrap:'], $restIndex); | |
| $paths = array_slice($argv, $restIndex); | |
| if (!$paths || preg_grep('#^-#', $paths)) { | |
| fwrite(STDERR, "Usage: php latte-comma.php [--dry-run] [--bootstrap=<file>] <dir|file>...\n"); | |
| exit(2); | |
| } | |
| foreach ($paths as $path) { | |
| if (!file_exists($path)) { | |
| fwrite(STDERR, "Path '$path' does not exist.\n"); | |
| exit(2); | |
| } | |
| } | |
| $autoload = findAutoload(getcwd()); | |
| if ($autoload === null) { | |
| fwrite(STDERR, "Run the script from your project, vendor/autoload.php was not found.\n"); | |
| exit(2); | |
| } | |
| require $autoload; | |
| $engine = isset($options['bootstrap']) | |
| ? require $options['bootstrap'] | |
| : new Latte\Engine; | |
| if (!$engine instanceof Latte\Engine) { | |
| fwrite(STDERR, "The bootstrap file must return Latte\\Engine.\n"); | |
| exit(2); | |
| } | |
| addNetteExtensions($engine); | |
| $engine->setLoader(new Latte\Loaders\StringLoader); | |
| $dryRun = isset($options['dry-run']); | |
| $fixed = $suspicious = $failed = 0; | |
| foreach ($paths as $path) { | |
| foreach (findFiles($path) as $file) { | |
| $source = file_get_contents($file); | |
| $original = compileNormalized($engine, $source, $error); | |
| if ($original === null) { | |
| echo "$file: skipped, the template does not compile: $error\n"; | |
| $failed++; | |
| continue; | |
| } | |
| $new = $source; | |
| foreach (array_reverse(findTags($source)) as [$start, $argsStart, $end, $name]) { | |
| $result = addComma($engine, $new, $original, $start, $argsStart, $end); | |
| $line = substr_count($source, "\n", 0, $start) + 1; | |
| $oldTag = substr($new, $start, $end - $start + 1); | |
| if ($result === false && !in_array($name, ['include', 'import', 'embed', 'define', 'sandbox'], true)) { // their keywords, like {include block $name}, look the same | |
| echo "$file:$line: check manually, a comma would change the meaning: $oldTag\n"; | |
| $suspicious++; | |
| } elseif (is_string($result)) { | |
| $new = $result; | |
| $original = compileNormalized($engine, $new); // the compiled code quotes the whole source | |
| echo "$file:$line: $oldTag -> " . substr($new, $start, $end - $start + 2) . "\n"; | |
| $fixed++; | |
| } | |
| } | |
| if ($new !== $source && !$dryRun) { | |
| file_put_contents($file, $new); | |
| } | |
| } | |
| } | |
| echo "\n", $dryRun ? 'Would fix' : 'Fixed', " $fixed tags, $suspicious to check manually, $failed files skipped.\n"; | |
| if ($failed) { | |
| echo "If a file was skipped because of your own tags or filters, pass your configured engine with --bootstrap.\n"; | |
| } | |
| exit($suspicious || $failed ? 1 : 0); | |
| /** | |
| * Returns the source with a comma added after the tag name, null when nothing is to be added, | |
| * or false when a comma right after the name compiles to different code. | |
| */ | |
| function addComma(Latte\Engine $engine, string $source, string $original, int $start, int $argsStart, int $end): string|false|null | |
| { | |
| $tag = substr($source, $start, $end - $start + 1); | |
| $candidates = 0; | |
| $changesMeaning = false; | |
| $depth = 0; | |
| for ($i = $argsStart; $i < $end; $i++) { | |
| $ch = $source[$i]; | |
| if ($ch === '"' || $ch === "'") { | |
| $i = strpos($source, $ch, $i + 1) ?: $end; // n:href values hold only the other kind of quotes | |
| continue; | |
| } elseif ($ch === '[' || $ch === '(' || $ch === '{') { | |
| $depth++; | |
| continue; | |
| } elseif ($ch === ']' || $ch === ')' || $ch === '}') { | |
| $depth--; | |
| continue; | |
| } elseif ($ch === ',' && !$depth) { | |
| break; // the arguments are already separated | |
| } elseif ($depth || !ctype_space($ch) || ctype_space($source[$i - 1])) { | |
| continue; | |
| } | |
| $rest = ltrim(substr($source, $i, $end - $i)); | |
| if ($rest === '' || $rest === '/' || $rest[0] === ',' || $rest[0] === '|') { | |
| continue; | |
| } | |
| if (++$candidates > 20) { | |
| break; | |
| } | |
| $attempt = substr_replace($source, ',', $i, 0); | |
| $compiled = compileNormalized($engine, $attempt); | |
| $compiled = $compiled === null ? null : str_replace(substr_replace($tag, ',', $i - $start, 0), $tag, $compiled); // comments quote the source of tags | |
| if ($compiled === $original) { | |
| return $attempt; | |
| } | |
| $changesMeaning = $changesMeaning || ($candidates === 1 && $compiled !== null); | |
| } | |
| return $changesMeaning ? false : null; | |
| } | |
| /** | |
| * Finds the candidate tags outside comments and returns [start, start of arguments, end, tag name] offsets. | |
| * @return list<array{int, int, int, string}> | |
| */ | |
| function findTags(string $s): array | |
| { | |
| $res = []; | |
| preg_match_all('#\{(control|form|input|label|link|plink|include|import|embed|define|sandbox)\s#', $s, $tags, PREG_OFFSET_CAPTURE | PREG_SET_ORDER); | |
| foreach ($tags as [[$match, $offset], [$name]]) { | |
| $argsStart = $offset + strlen($match); | |
| $end = findTagEnd($s, $argsStart); | |
| if ($end !== null) { | |
| $res[] = [$offset, $argsStart, $end, $name]; | |
| } | |
| } | |
| preg_match_all('#\bn:href=(["\'])#', $s, $attrs, PREG_OFFSET_CAPTURE); | |
| foreach ($attrs[0] as [$match, $offset]) { | |
| $argsStart = $offset + strlen($match); | |
| $end = strpos($s, $match[-1], $argsStart); | |
| if ($end !== false) { | |
| $res[] = [$offset, $argsStart, $end, 'n:href']; | |
| } | |
| } | |
| preg_match_all('#\{\*.*?\*\}#s', $s, $comments, PREG_OFFSET_CAPTURE); | |
| $res = array_filter($res, function (array $tag) use ($comments): bool { | |
| foreach ($comments[0] as [$comment, $offset]) { | |
| if ($tag[0] > $offset && $tag[0] < $offset + strlen($comment)) { | |
| return false; | |
| } | |
| } | |
| return true; | |
| }); | |
| usort($res, fn($a, $b) => $a[0] <=> $b[0]); | |
| return $res; | |
| } | |
| /** Returns the offset of the closing brace of a tag, skipping strings and nested braces. */ | |
| function findTagEnd(string $s, int $pos): ?int | |
| { | |
| $depth = 0; | |
| for ($len = strlen($s); $pos < $len; $pos++) { | |
| $ch = $s[$pos]; | |
| if ($ch === '"' || $ch === "'") { | |
| for ($pos++; $pos < $len && $s[$pos] !== $ch; $pos++) { | |
| if ($s[$pos] === '\\') { | |
| $pos++; | |
| } | |
| } | |
| } elseif ($ch === '{' || $ch === '[' || $ch === '(') { | |
| $depth++; | |
| } elseif ($ch === ']' || $ch === ')') { | |
| $depth--; | |
| } elseif ($ch === '}') { | |
| if (!$depth--) { | |
| return $pos; | |
| } | |
| } | |
| } | |
| return null; | |
| } | |
| /** Compiles the template and strips what depends on positions in the source or changes on every compilation. */ | |
| function compileNormalized(Latte\Engine $engine, string $source, ?string &$error = null): ?string | |
| { | |
| set_error_handler(fn(int $severity) => in_array($severity, [E_USER_DEPRECATED, E_USER_NOTICE, E_USER_WARNING, E_DEPRECATED], true)); | |
| try { | |
| $code = $engine->compile($source); | |
| } catch (Throwable $e) { | |
| $error = $e->getMessage(); | |
| return null; | |
| } finally { | |
| restore_error_handler(); | |
| } | |
| return preg_replace( | |
| ['#/\* (pos|line) [\d:]+ \*/#', '#Template_[0-9a-f]+#', "#createCache\\('[A-Za-z0-9+/=]+'#"], | |
| ['', '', 'createCache('], | |
| $code, | |
| ); | |
| } | |
| /** Adds the extensions of the installed Nette packages the engine does not have yet. */ | |
| function addNetteExtensions(Latte\Engine $engine): void | |
| { | |
| $factories = [ | |
| Latte\Essential\TranslatorExtension::class => fn() => new Latte\Essential\TranslatorExtension(null), | |
| Nette\Bridges\ApplicationLatte\UIExtension::class => fn() => new Nette\Bridges\ApplicationLatte\UIExtension(null), | |
| Nette\Bridges\FormsLatte\FormsExtension::class => fn() => new Nette\Bridges\FormsLatte\FormsExtension, | |
| Nette\Bridges\CacheLatte\CacheExtension::class => fn() => new Nette\Bridges\CacheLatte\CacheExtension(new Nette\Caching\Storages\DevNullStorage), | |
| Nette\Bridges\AssetsLatte\LatteExtension::class => fn() => new Nette\Bridges\AssetsLatte\LatteExtension(new Nette\Assets\Registry), | |
| ]; | |
| $present = method_exists($engine, 'getExtensions') // since Latte 3.0.4 | |
| ? array_map(fn($extension) => $extension::class, $engine->getExtensions()) | |
| : []; | |
| foreach ($factories as $class => $factory) { | |
| if (class_exists($class) && !in_array($class, $present, true)) { | |
| $engine->addExtension($factory()); | |
| } | |
| } | |
| } | |
| /** @return iterable<string> */ | |
| function findFiles(string $path): iterable | |
| { | |
| if (is_file($path)) { | |
| yield $path; | |
| return; | |
| } | |
| $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS)); | |
| foreach ($iterator as $file) { | |
| $relative = substr($file->getPathname(), strlen($path)); | |
| if ($file->getExtension() === 'latte' && !preg_match('#(^|[/\\\\])(vendor|node_modules|temp)[/\\\\]#', $relative)) { | |
| yield $file->getPathname(); | |
| } | |
| } | |
| } | |
| function findAutoload(string $dir): ?string | |
| { | |
| do { | |
| if (is_file($file = "$dir/vendor/autoload.php")) { | |
| return $file; | |
| } | |
| } while ($dir !== ($dir = dirname($dir))); | |
| return null; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment