Here is real task, which is called from CLI.
The problem is, that generated template really contains /etc/passwd.
This Task basically go throw all volt templates and generate php. Then I use ngettext to extract strings.
The chdir and getcwd is hack, to start working templates generation, because Phalcon don't have any templateRoot.
<?php
class GenerateVoltTemplatesTask extends \Phalcon\CLI\Task
{
private $cacheDir;
public function mainAction()
{
$this->compileDirectory(APPLICATION_PATH . '/views');
}
/**
* Compiles
* @param path
*/
private function compileDirectory($path)
{
echo "$path \n";
// Create a compiler
$compiler = new \Phalcon\Mvc\View\Engine\Volt\Compiler();
$compiler->setOptions(array(
'compiledPath' => $this->cacheDir,
'compiledExtension' => '.php',
'compiledSeparator' => '_'
// 'compileAlways' => true
));
$compiler->addFunction('_', '_');
$compiler->addFunction('strtotime', function ($resolvedArgs, $exprArgs)
{
return 'strtotime(' . $resolvedArgs . ')';
});
$baseDir = getcwd();
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS | RecursiveIteratorIterator::LEAVES_ONLY));
$i = 0;
// go throw all volt files and compile them
foreach ($objects as $name => $object)
{
if ($object->getExtension() !== 'volt')
continue;
echo $object->getBasename() . " ";
try
{
chdir($baseDir);
$newFilename = $this->optimizePath($name, getcwd());
$newFilename = substr($newFilename, 1);
$compiler->compile($newFilename);
}
catch (\Exception $e)
{
echo "\nERROR 1: " . $e->getMessage();
try
{
chdir(dirname($object->getPath()));
$newFilename = $this->optimizePath($name, getcwd());
$newFilename = substr($newFilename, 1);
$compiler->compile($newFilename);
}
catch (\Exception $e)
{
echo "\nERROR 2: " . $e->getMessage();
try
{
chdir(dirname($object->getPath()));
$newFilename = $this->optimizePath($name, getcwd());
$newFilename = substr($newFilename, 1);
$compiler->compile($newFilename);
}
catch (\Exception $e)
{
echo "\nERROR 3: " . $e->getMessage();
continue;
}
}
}
echo "\n -> " . $compiler->getCompiledTemplatePath() . "\n";
$i ++;
}
chdir($baseDir);
echo "Templates compiled: $i\n\n";
}
private function optimizePath($filename, $directory)
{
return str_replace($directory, '', $filename);
}
}