Skip to content

Instantly share code, notes, and snippets.

@dandelauro
Created January 21, 2016 04:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dandelauro/47b8b6e40b3e6488d45e to your computer and use it in GitHub Desktop.
Save dandelauro/47b8b6e40b3e6488d45e to your computer and use it in GitHub Desktop.
A mustache php pattern loader for Laravel and Pattern Lab.
<?php
namespace App\Extensions\Mustache;
use Mustache_Loader;
class PatternLoader implements Mustache_Loader
{
private $baseDir;
private $patterns = array();
public function __construct()
{
$this->baseDir = ‘/path/to/patternlab/source/patterns/’;
$patternObjects = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->baseDir), \RecursiveIteratorIterator::SELF_FIRST);
$patternObjects->setFlags(\FilesystemIterator::SKIP_DOTS);
$patternFiles = new \RegexIterator($patternObjects, '/^(.+)\.mustache$/i', \RecursiveRegexIterator::GET_MATCH);
foreach ($patternFiles as $patternFile) {
$key = substr($patternFile[1], strlen($this->baseDir));
$segs = array_filter(preg_split('/\//', $key));
$key = preg_replace('/\d+-/', '', array_shift($segs)).'-'.preg_replace('/\d+-/', '', array_pop($segs));
$this->patterns[$key] = $patternFile[0];
}
}
public function load($name)
{
if (!isset($this->templates[$name])) {
$this->templates[$name] = $this->loadPattern($name);
}
return $this->templates[$name];
}
protected function loadPattern($name)
{
$pattern = $this->patterns[$name];
if (!file_exists($pattern)) {
throw new Mustache_Exception_UnknownTemplateException($name);
}
return file_get_contents($pattern);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment