Skip to content

Instantly share code, notes, and snippets.

@jahidulpabelislam
Forked from dbisso/php2twig.php
Last active October 16, 2023 09:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jahidulpabelislam/a14e874a0025eb76b7d6f943b75a3e2f to your computer and use it in GitHub Desktop.
Save jahidulpabelislam/a14e874a0025eb76b7d6f943b75a3e2f to your computer and use it in GitHub Desktop.
Twiggify
#!/usr/bin/env php
<?php
$file = $argv[1];
$contents = file_get_contents($file);
/** @var $patterns */
$patterns = [
/** @lang PhpRegExp */
'~<\?=[ ]?([^?]+);?[ ]?\?>~m' => '{{ $1 }}',
/** @lang PhpRegExp */
'~<\?(php)? ?([^?]+);? ?\?>~s' => '{% $2 %}',
/** @lang PhpRegExp */
'~->~' => '.',
'~=>~' => ':',
/** @lang PhpRegExp */
'~\$~' => '',
// '~this~' => '',
/** @lang PhpRegExp */
'~\{\{ this\.t\(([\'"][^\'"]*[\'"])\) \}\}~' => '{{ $1|t }}',
/** @lang PhpRegExp */
'~\{\{ this\.p\(([^)]*)\) \}\}~' => '{{ $1|p }}',
'~\{% if \((.*)\) *: *%}~' => '{% if $1 %}',
'~\{% else *: *%}~' => '{% else %}',
'~\{% elseif \((.*)\) *: *%}~' => '{% elseif $1 %}',
'~\{% foreach \((.*)\) *: *%}~' => '{% for $1 %}',
'~\{% endforeach *%}~' => '{% endfor %}',
/** @lang PhpRegExp */
'~\{\{ D3R::page\(\)\.renderPartial\(~' => '{{ partial(',
'~\{\% D3R::page\(\)\.addJavascript\(~' => '{% javascript(',
'~\{\% this\.page\.addJavascript\(~' => '{% javascript(',
'~\{\% D3R::page\(\)\.addScript\(~' => '{% script(',
'~\{\% this\.page\.addScript\(~' => '{% script(',
'~\{\% D3R::page\(\)\.addOnLoad\(~' => '{% onload(',
'~\{\% this\.page\.addOnLoad\(~' => '{% onload(',
'~\{\% D3R::page\(\)\.addStylesheet\(~' => '{% stylesheet(',
'~\{\% this\.page\.addStylesheet\(~' => '{% stylesheet(',
'~D3R::page\(\)~' => 'D3R.page()',
'~D3R::~' => 'D3R.',
'~\/\**? (.*) */~' => '{# $1 #}',
'~\&\&~' => 'and',
'~\|\|~' => 'or',
'~; +([}%]})~' => ' $1',
];
$contents = preg_replace(array_keys($patterns), array_values($patterns), $contents);
$outputFile = preg_replace('~\.html$~', '.twig', $file);
echo 'Writing to ' . $outputFile;
file_put_contents($outputFile, $contents);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment