Last active
November 9, 2023 13:51
-
-
Save lyrixx/dd0249ef9f21a4fa63c5abe3929a68ac to your computer and use it in GitHub Desktop.
Updated your templates with the new twig include
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 | |
<<<CONFIG | |
packages: | |
- "symfony/finder: ~3.0" | |
- "symfony/console: ~3.0" | |
CONFIG; | |
use Symfony\Component\Console\Application; | |
use Symfony\Component\Console\Input\InputArgument; | |
use Symfony\Component\Console\Input\InputInterface; | |
use Symfony\Component\Console\Output\OutputInterface; | |
use Symfony\Component\Finder\Finder; | |
(new Application('Twig replace include', '1.0')) | |
->register('run') | |
->addArgument('path', InputArgument::REQUIRED, 'The folder where are located the templates.') | |
->setCode(function (InputInterface $input, OutputInterface $output) { | |
$finder = Finder::create() | |
->in($input->getArgument('path')) | |
->files() | |
; | |
foreach ($finder as $filename) { | |
$content = file_get_contents($filename); | |
if (false === strpos($content, 'include')) { | |
continue; | |
} | |
$callback = function(array $matches) { | |
$layout = '{{ include(\'%s\'%s%s) }}'; | |
$templateName = $matches['templateName']; | |
$templateName = str_replace(':', '/', $templateName); | |
$templateName = ltrim($templateName, '/'); | |
$variables = $only = ''; | |
if (isset($matches['variables'])) { | |
$variables = ', {'.$matches['variables'].'}'; | |
} | |
if (isset($matches['only'])) { | |
$only = ', with_context = false'; | |
} | |
return sprintf($layout, $templateName, $variables, $only); | |
}; | |
$pattern = '#{%[\s\\n]+include[\s\\n]+\'(?<templateName>[\w+\.-_]+)\'(?:[\s\\n]+with[\s\\n]+{(?<variables>(?:.|\n)*)})?(?:[\s\\n]+(?<only>only)[\s\\n]+)?[\s\\n]*%}#U'; | |
$content = preg_replace_callback($pattern, $callback, $content); | |
file_put_contents($filename, $content); | |
} | |
}) | |
->getApplication() | |
->setDefaultCommand('run', true) | |
->run() | |
; |
this is missing support for the whitespace-controll on the include tag
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
melody run https://gist.github.com/lyrixx/dd0249ef9f21a4fa63c5abe3929a68ac app/Resources/views/
For more information about melody, see the official website