phingのカスタムタスクを作成してSmartyの構文チェックをしてみた
ファイルの置換だけじゃなくて、ちょっとした修正とか手作業でぱぱっと変更したりした時って、 typoだったり、閉じ忘れだったり、不要な文字を入れて保存してしまってたりでfatal errorが発生しないとも言えないと思います。
phingにphpの構文チェックがあるのでそれでphpファイルはチェックできるんですけど、テンプレート(今回はSmarty)を触った時も同様にチェクしたいわけです。
phingのカスタムタスクを使えばさくっと実現できたのでそのメモです。
ディレクトリ構成
サンプルのディレクトリ配置はこんな感じ
├ public PHPファイル
├ index.php
├ xxx.php
├ templates テンプレートファイル
├ index.tpl
├ xxx.tpl
├ buld
├ build.xml
├ tasks
├ SmartyLintTask.php
├ vendor
composer.json
実行コマンド
verndor/bin/phing -f buld/buld.xml
phingでphpのシンタックスチェックする場合
buld.xml はこんな感じ。
phingでSmartyテンプレートのシンタックスチェックする場合
そもそもSmartyの構文チェックどうするんだろう?と思ってggってみましたが、シンプルにfetch
との回答がありました。 うん。まぁそうですね。
Check smarty Syntax Error in Html
buld.xml はこんな感じに。
SmartyLintTask.php はこんな感じ。phplintを参考に。PhpLintTask.php
require __DIR__ . '/../../vendor/autoload.php';
require_once "Smarty/Smarty.class.php";
class SmartyLintTask extends Task
{
protected $smarty;
protected $filesets = [];
public function addFileSet(FileSet $fs)
{
$this->filesets[] = $fs;
}
public function init()
{
$this->smarty = new Smarty();
$this->smarty->template_dir = __DIR__ . "/../../templates/";
$this->smarty->compile_dir = __DIR__ . "/../../templates_c/";
}
public function main()
{
if ($this->file instanceof PhingFile) {
$this->lint($this->file->getPath());
} else { // process filesets
$project = $this->getProject();
foreach ($this->filesets as $fs) {
$ds = $fs->getDirectoryScanner($project);
$files = $ds->getIncludedFiles();
$dir = $fs->getDir($this->project)->getPath();
foreach ($files as $file) {
$this->lint($dir . DIRECTORY_SEPARATOR . $file);
}
}
}
}
public function getTemplatePath($file)
{
$path = pathinfo($file);
$dir = realpath($path['dirname']);
$templateDir = realpath($this->smarty->template_dir);
$relativeDir = str_replace($templateDir, '', $dir);
$file = $relativeDir . '/' . $path['basename'];
return ltrim($file, '/');
}
public function lint($file)
{
$file = $this->getTemplatePath($file);
try {
$this->smarty->fetch($file);
} catch (Exception $e) {
$this->log($e->getMessage(), Project::MSG_ERR);
}
}
}
実行結果
あえてtypoとテンプレートタグを閉じないようにエラーを出すとこんな感じに。
カスタムタスクを使えば色々柔軟な事が出来そうです。