レガシーPHPリファクタ 38:Pestで全Smartyテンプレートのコンパイルチェックを自動化する

2007年に執筆された『Smarty動的Webサイト構築入門』のサンプルコードリポジトリをメンテナンスしています(対象PR:ninton/smartybook#838)。

このサンプルコードリポジトリ自体はどこにもリリースしませんが、実際のレガシーSmartyプロジェクトの参考になるように、テンプレート変更時の安全網(セーフティネット)の選択肢をこのリポジトリで試して提示する目的でメンテナンスを続けています。

すでに Golden Master テストや SmartyLint を導入していますが、凡ミスを防ぐための選択肢の一つとして、CI に組み込める一括コンパイルチェックを追加しました。Smarty の compileTemplateSource() メソッドを使い、描画は行わずにテンプレートが正常にコンパイルできるかを Pest のデータセットで検証します。


実装の概要

テンプレートディレクトリ配下の .tpl ファイルを再帰的に走査し、ファイルごとに一時ディレクトリへコンパイルして成功を確認しています。

1. テンプレート一括コンパイルテスト(EachTemplateCompileTest.php)

<?php

declare(strict_types=1);

use App\Smarty\SmartyFactory;
use Tests\Support\Smarty\SmartyCompileStubs;

test('template compiles cleanly', function (string $relativePath): void {
    $compileDir = sys_get_temp_dir() . '/smarty_templates_c_' . uniqid('', true);
    mkdir($compileDir, 0777, true);

    try {
        $smarty = SmartyFactory::create();
        $smarty->setCompileDir($compileDir);

        // スタブのプラグインを登録します
        SmartyCompileStubs::register($smarty);

        // 個別テンプレートを強制コンパイル(描画はしない)
        $template = $smarty->createTemplate($relativePath);
        $template->compileTemplateSource();

        expect(true)->toBeTrue();
    } finally {
        array_map('unlink', glob($compileDir . '/*') ?: []);
        @rmdir($compileDir);
    }
})->with(function (): Generator {
    $baseDir = realpath(SMARTY_TEMPLATE_DIR) ?: SMARTY_TEMPLATE_DIR;
    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($baseDir, FilesystemIterator::SKIP_DOTS),
    );

    $relativePaths = [];

    foreach ($iterator as $file) {
        if ($file->isFile() && $file->getExtension() === 'tpl') {
            $relativePaths[] = ltrim(str_replace($baseDir, '', $file->getPathname()), DIRECTORY_SEPARATOR);
        }
    }

    sort($relativePaths, SORT_STRING);

    foreach ($relativePaths as $relative) {
        yield $relative => [$relative];
    }
});

2. カスタムプラグインのスタブ定義(SmartyCompileStubs.php)

<?php

declare(strict_types=1);

namespace Tests\Support\Smarty;

use Smarty\Smarty;

final class SmartyCompileStubs
{
    /**
     * @var array<int, array{type: string, name: string, callback: callable}>|null
     */
    private static ?array $stubDefinitions = null;

    public static function register(Smarty $smarty): void
    {
        foreach (self::definitions() as $stub) {
            $smarty->registerPlugin($stub['type'], $stub['name'], $stub['callback']);
        }
    }

    /**
     * @return array<int, array{type: string, name: string, callback: callable}>
     */
    private static function definitions(): array
    {
        if (self::$stubDefinitions !== null) {
            return self::$stubDefinitions;
        }

        $emptyString = static fn (): string => '';

        self::$stubDefinitions = [
            ['type' => Smarty::PLUGIN_FUNCTION, 'name' => 'insert_noticeText', 'callback' => $emptyString],
            ['type' => Smarty::PLUGIN_FUNCTION, 'name' => 'insert_noticeText2', 'callback' => $emptyString],
            ['type' => Smarty::PLUGIN_FUNCTION, 'name' => 'login_form', 'callback' => $emptyString],
            ['type' => Smarty::PLUGIN_MODIFIER, 'name' => 'mb_truncate', 'callback' => $emptyString],
        ];

        return self::$stubDefinitions;
    }
}

テスト配置場所の判断

既存のテスト構成を踏まえ、tests/Integration/Template/EachTemplateCompileTest.php に配置しました。

テスト種別配置パス今回のテストとの位置づけ
単体テストapp/path/to/tests/FugaTest.php
smartybook/path/to/tests/FugaTest.php
クラス・関数単位でコード近傍に配置。全テンプレート横断の検証とは責務が異なる
Golden Master テストtests/GoldenMaster/GoldenMasterTest.phpシステム・複数ファイルを横断検証し tests/ 直下系に集約。方針として整合する
今回のコンパイル検証tests/Integration/Template/EachTemplateCompileTest.phpSmartyFactory・Smartyエンジン・実 .tpl ファイル・一時ディレクトリを組み合わせる統合テスト寄り(Features/ は未導入のため Integration/Template を選択)

設計上の工夫・良い点

  • 責務の分離: テスト本体はテンプレートの走査・コンパイル実行・クリーンアップに集中させ、プラグインのスタブ登録は Tests\Support\Smarty\SmartyCompileStubs に切り出しました。
  • 名前空間とPestスタイルの両立: SmartyCompileStubs は namespace Tests\Support\Smarty; の final class として PSR-4 オートロードに載せつつ、テストファイル側は namespace なしで test(...)->with(...) に集中できる構成にしています。
  • 一時ディレクトリの隔離と掃除: テストケースごとに sys_get_temp_dir() 配下へ一意のコンパイル先ディレクトリを作成し、finally ブロックでファイルを削除してディレクトリを片付けています。
  • スタブ定義の拡張しやすさ: プラグイン定義を配列で管理しているため、今後新しいカスタムプラグインが必要になった際も追記しやすくなっています。

注意点・落とし穴とハマりどころ

1. カスタムプラグインの事前登録が必須(実際に引っかかった例)

compileTemplateSource() の前にプラグインが登録されていないと、コンパイル時に失敗します。

今回のリポジトリでは SmartyFactory::create() ではプラグインを登録しておらず、エンドポイント個別でプラグインを登録する形になっていました。そのため最初にテストを回したところ、大量のエラーが出ました。

プラグイン登録を SmartyFactory::create() に寄せるのが正攻法ではありますが、今回はアプリケーションコードを触る変更を別機会に切り出したかったため、全章分のプラグインのスタブを用意して SmartyCompileStubs から一括登録する方針をとりました。

2. 親テンプレート・パーツ類もコンパイル対象になる

templates ディレクトリを丸ごと対象にしているため、layouts/ や components/、partials/ のように単体描画を想定していないテンプレートもコンパイルされ、一時領域にコンパイル済みファイルが生成されます。pages/ だけに絞って検証漏れが出るよりは、全 .tpl を対象にして不要ファイル生成を許容する判断としました。

3. 実行時エラーまでは検知できない

タグ構文や修飾子・プラグイン対応などのコンパイル時エラーは検出できますが、未定義変数の参照や実行時のデータ依存ロジックまでは検証できません。描画結果や実行時挙動の確認は、既存の Golden Master テストに委ねています。

4. コンパイル先ディレクトリの権限とクリーンアップ

検証後にコンパイル済みファイルが残るとノイズや権限トラブルの原因になるため、テストごとに一時ディレクトリを払い出し、finally で掃除する運用にしています。


CI での運用とローカルでのテスト実行結果

このテストは CI に組み込んでおり、テンプレート変更時に全 .tpl のコンパイル可否を自動でチェックできるようにしています。ローカル環境で全120テンプレートのデータセットに対して実行したところ、0.23秒で完了しました。

 PASS  Tests\Integration\Template\EachTemplateCompileTest
  ✓ template compiles cleanly with dataset "components/chapter3/03_12_header.tpl"                                                                                                                                                                                           0.01s  
  ✓ template compiles cleanly with dataset "components/chapter3/03_13_assign.tpl"
  ✓ template compiles cleanly with dataset "components/chapter4_7/select_date.tpl"
  ✓ template compiles cleanly with dataset "components/chapter4_7/select_time.tpl"
  ✓ template compiles cleanly with dataset "components/chapter5_6/amazon_image.tpl"
  ✓ template compiles cleanly with dataset "components/chapter5_6/amazon_item.tpl"
  ✓ template compiles cleanly with dataset "layouts/chapter4_6/base.tpl"
  ✓ template compiles cleanly with dataset "layouts/chapter4_7/base.tpl"
  ✓ template compiles cleanly with dataset "layouts/chapter4_8/base.tpl"
  ✓ template compiles cleanly with dataset "layouts/chapter5_3/base_ezweb.tpl"
  ✓ template compiles cleanly with dataset "layouts/chapter5_3/base_imode.tpl"
  ✓ template compiles cleanly with dataset "layouts/chapter5_3/base_softbank.tpl"
  ✓ template compiles cleanly with dataset "layouts/chapter5_6/base.tpl"
  ✓ template compiles cleanly with dataset "pages/chapter3/03_01.tpl"
  ✓ template compiles cleanly with dataset "pages/chapter3/03_02.tpl"
  ✓ template compiles cleanly with dataset "pages/chapter3/03_03.tpl"
  ✓ template compiles cleanly with dataset "pages/chapter3/03_04.tpl"
  ...
  ✓ template compiles cleanly with dataset "pages/chapter5_5/notice.tpl"
  ✓ template compiles cleanly with dataset "pages/chapter5_6/admin_form.tpl"
  ✓ template compiles cleanly with dataset "pages/chapter5_6/admin_preview.tpl"
  ✓ template compiles cleanly with dataset "pages/chapter5_6/view.tpl"
  ✓ template compiles cleanly with dataset "partials/chapter4_8/menu_box.tpl"
  ✓ template compiles cleanly with dataset "partials/chapter5_6/footer.tpl"

  Tests:    120 passed (120 assertions)
  Duration: 0.23s
タイトルとURLをコピーしました