LoginSignup
2
1

More than 3 years have passed since last update.

SmartyファイルをTwigに変換する (EC-CUBE2 → EC-CUBE4 移行用)

Last updated at Posted at 2020-08-17

テンプレートを捨てたくない

  • EC-CUBE3以降、テンプレートエンジンがSmartyからTwigになった
  • EC-CUBE2でデフォルトのページを使ってた人は、EC-CUBE4でもそのままデフォルトのページを使えばいいと思う
  • オリジナルのページを追加して使ってた人にとっては、それをEC-CUBE4に移行してからも持ち越して使いたいことがある ( = 私)
  • それが手で書き移せるような分量ではない場合もある ( = 私)

自動変換ツール

PHP Smarty to Twig Converter

sankarsuda/to-twig

toTwig is an utility to convert smarty template engine to twig template engine.

  • 個人制作 (インドのSankar Sudaさんありがとう‥‥)
  • 7年前に作ったまま放置されている

Converting Smarty templates to Twig

OXID-eSales/smarty-to-twig-converter

Converting tool located at GitHub allows to convert existing Smarty template files to Twig syntax. The tool besides standard Smarty syntax is adjusted to handle custom OXID modifications and extensions.

  • 上記のto-twigを企業がフォークして自社サービス向けにリファクター&改造した物らしい
  • 今もメンテされていて、PHP7.4までバッチリ対応

  • こちらをいじくって使っていこうと思います。

git clone https://github.com/OXID-eSales/smarty-to-twig-converter.git
cd smarty-to-twig-converter

EC-CUBE2式のブラケットに対応させる

  • 素のSmartyはブラケットに{ }を使っていますが、EC-CUBE2はこの書式を<!--{ }-->に変更して使っています (ちなみにOXIDでは[{ }]みたいです)。
  • コード内の、正規表現でブラケットをパターンマッチさせている部分をEC-CUBE2の書式に合わせて書き換えていきます。
app\toTwig\Converter\ConverterAbstract.php
    protected function getOpeningTagPattern(string $tagName): string
    {
-       return sprintf("#\[\{\s*%s\b\s*((?:(?!\[\{|\}\]).(?<!\[\{)(?<!\}\]))+)?\}\]#is", preg_quote($tagName, '#'));
+       return sprintf("#<!--\{\s*%s\b\s*((?:(?!<!--\{|\}-->).(?<!<!--\{)(?<!\}-->))+)?\}-->#is", preg_quote($tagName, '#'));
    }

    protected function getClosingTagPattern(string $tagName): string
    {
-       return sprintf("#\[\{\s*/%s\s*\}\]#i", preg_quote($tagName, '#'));
+       return sprintf("#<!--\{\s*/%s\s*\}-->#i", preg_quote($tagName, '#'));
    }

    private function convertFilters(string $string): string
    {
        return preg_replace_callback(
-           '/\|@?(?:\w+)(?:\:|\b)(?:"\s+"|\'\s+\'|[^\s}|])*/',
+           '/\|@?(?:\w+)(?:\:|\b)(?:"\s+"|\'\s+\'|[^}|])*/',
app\toTwig\Converter\VariableConverter.php
    public function convert(string $content): string
    {
-       $pattern = '/\[\{([^{}]+)?\}\]/';
+       $pattern = '/<!--\{([^{}]+)?\}-->/';
app\toTwig\Converter\CommentConverter.php
    public function convert(string $content): string
    {
-       $pattern = '#\[\{\*((?:(?!\[\{|\}\]).(?<!\[\{)(?<!\}\]))+)?\*\}\]#is';
+       $pattern = '#<!--\{\*((?:(?!<!--\{\*|\*\}-->).(?<!<!--\{\*)(?<!\*\}-->))+)?\*\}-->#is';

変換 → 手動で調整

composer install
php toTwig convert --path=/path/to/dir --ext=.twig
  • この自動変換は全く完璧ではありません。生成したTwigファイルをEC-CUBE4に持ってった後、間違いのない表示になるまで手直しし続けることになりました。
  • それでも一から書き写すよりはずっと楽でした。終わり!
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1