From bf3ed6cbd180b9414c96591b678d4f9b979353f3 Mon Sep 17 00:00:00 2001 From: Matt Wells Date: Fri, 3 Jan 2014 09:34:01 -0500 Subject: [PATCH 1/8] Refactoring for Composer compatibility -- Generation works without the -c flag -- Requires "Mustache_Loader_PatternLoader" shim -- -c flag will require loading non-PSR-0-compliant css-rule-saver library --- .gitignore | 1 + builder/builder.php | 11 +- builder/lib/{builder.lib.php => Buildr.php} | 0 .../lib/{generator.lib.php => Generatr.php} | 0 builder/lib/Mustache/Autoloader.php | 69 -- builder/lib/Mustache/Compiler.php | 475 ------------ builder/lib/Mustache/Context.php | 149 ---- builder/lib/Mustache/Engine.php | 729 ------------------ builder/lib/Mustache/Exception.php | 18 - .../Exception/InvalidArgumentException.php | 18 - .../lib/Mustache/Exception/LogicException.php | 18 - .../Mustache/Exception/RuntimeException.php | 18 - .../Mustache/Exception/SyntaxException.php | 29 - .../Exception/UnknownFilterException.php | 29 - .../Exception/UnknownHelperException.php | 29 - .../Exception/UnknownTemplateException.php | 29 - builder/lib/Mustache/HelperCollection.php | 170 ---- builder/lib/Mustache/LICENSE | 20 - builder/lib/Mustache/LambdaHelper.php | 49 -- builder/lib/Mustache/Loader.php | 28 - builder/lib/Mustache/Loader/ArrayLoader.php | 78 -- .../lib/Mustache/Loader/CascadingLoader.php | 69 -- .../lib/Mustache/Loader/FilesystemLoader.php | 120 --- builder/lib/Mustache/Loader/InlineLoader.php | 121 --- builder/lib/Mustache/Loader/MutableLoader.php | 32 - builder/lib/Mustache/Loader/StringLoader.php | 40 - builder/lib/Mustache/Logger.php | 135 ---- .../lib/Mustache/Logger/AbstractLogger.php | 121 --- builder/lib/Mustache/Logger/StreamLogger.php | 193 ----- builder/lib/Mustache/Parser.php | 91 --- builder/lib/Mustache/Template.php | 177 ----- builder/lib/Mustache/Tokenizer.php | 315 -------- builder/lib/{watcher.lib.php => Watchr.php} | 0 builder/lib/css-rule-saver/LICENSE | 20 - builder/lib/css-rule-saver/css-rule-saver.php | 267 ------- .../lib/php-selector/History.rdoc | 20 - .../lib/php-selector/Readme.rdoc | 78 -- .../lib/php-selector/selector.php | 176 ----- .../lib/php-selector/test.selector.php | 124 --- composer.json | 24 + composer.lock | 81 ++ 41 files changed, 109 insertions(+), 4062 deletions(-) rename builder/lib/{builder.lib.php => Buildr.php} (100%) rename builder/lib/{generator.lib.php => Generatr.php} (100%) delete mode 100644 builder/lib/Mustache/Autoloader.php delete mode 100644 builder/lib/Mustache/Compiler.php delete mode 100644 builder/lib/Mustache/Context.php delete mode 100644 builder/lib/Mustache/Engine.php delete mode 100644 builder/lib/Mustache/Exception.php delete mode 100644 builder/lib/Mustache/Exception/InvalidArgumentException.php delete mode 100644 builder/lib/Mustache/Exception/LogicException.php delete mode 100644 builder/lib/Mustache/Exception/RuntimeException.php delete mode 100644 builder/lib/Mustache/Exception/SyntaxException.php delete mode 100644 builder/lib/Mustache/Exception/UnknownFilterException.php delete mode 100644 builder/lib/Mustache/Exception/UnknownHelperException.php delete mode 100644 builder/lib/Mustache/Exception/UnknownTemplateException.php delete mode 100644 builder/lib/Mustache/HelperCollection.php delete mode 100644 builder/lib/Mustache/LICENSE delete mode 100644 builder/lib/Mustache/LambdaHelper.php delete mode 100644 builder/lib/Mustache/Loader.php delete mode 100644 builder/lib/Mustache/Loader/ArrayLoader.php delete mode 100644 builder/lib/Mustache/Loader/CascadingLoader.php delete mode 100644 builder/lib/Mustache/Loader/FilesystemLoader.php delete mode 100644 builder/lib/Mustache/Loader/InlineLoader.php delete mode 100644 builder/lib/Mustache/Loader/MutableLoader.php delete mode 100644 builder/lib/Mustache/Loader/StringLoader.php delete mode 100644 builder/lib/Mustache/Logger.php delete mode 100644 builder/lib/Mustache/Logger/AbstractLogger.php delete mode 100644 builder/lib/Mustache/Logger/StreamLogger.php delete mode 100644 builder/lib/Mustache/Parser.php delete mode 100644 builder/lib/Mustache/Template.php delete mode 100644 builder/lib/Mustache/Tokenizer.php rename builder/lib/{watcher.lib.php => Watchr.php} (100%) delete mode 100644 builder/lib/css-rule-saver/LICENSE delete mode 100644 builder/lib/css-rule-saver/css-rule-saver.php delete mode 100755 builder/lib/css-rule-saver/lib/php-selector/History.rdoc delete mode 100755 builder/lib/css-rule-saver/lib/php-selector/Readme.rdoc delete mode 100755 builder/lib/css-rule-saver/lib/php-selector/selector.php delete mode 100755 builder/lib/css-rule-saver/lib/php-selector/test.selector.php create mode 100644 composer.json create mode 100644 composer.lock diff --git a/.gitignore b/.gitignore index a23cf51e7..9c6f80dae 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ public/* config.ini latest-change.txt *-ck.js +vendor diff --git a/builder/builder.php b/builder/builder.php index 92565d6ef..b040c0a3c 100644 --- a/builder/builder.php +++ b/builder/builder.php @@ -18,17 +18,12 @@ * */ -// load builder classes -require __DIR__."/lib/builder.lib.php"; -require __DIR__."/lib/generator.lib.php"; -require __DIR__."/lib/watcher.lib.php"; +require '../vendor/autoload.php'; + + -// load mustache & register it -require __DIR__."/lib/Mustache/Autoloader.php"; Mustache_Autoloader::register(); -// load css rule saver -require __DIR__."/lib/css-rule-saver/css-rule-saver.php"; // make sure this script is being accessed from the command line if (php_sapi_name() == 'cli') { diff --git a/builder/lib/builder.lib.php b/builder/lib/Buildr.php similarity index 100% rename from builder/lib/builder.lib.php rename to builder/lib/Buildr.php diff --git a/builder/lib/generator.lib.php b/builder/lib/Generatr.php similarity index 100% rename from builder/lib/generator.lib.php rename to builder/lib/Generatr.php diff --git a/builder/lib/Mustache/Autoloader.php b/builder/lib/Mustache/Autoloader.php deleted file mode 100644 index df48536d0..000000000 --- a/builder/lib/Mustache/Autoloader.php +++ /dev/null @@ -1,69 +0,0 @@ -baseDir = dirname(__FILE__).'/..'; - } else { - $this->baseDir = rtrim($baseDir, '/'); - } - } - - /** - * Register a new instance as an SPL autoloader. - * - * @param string $baseDir Mustache library base directory (default: dirname(__FILE__).'/..') - * - * @return Mustache_Autoloader Registered Autoloader instance - */ - public static function register($baseDir = null) - { - $loader = new self($baseDir); - spl_autoload_register(array($loader, 'autoload')); - - return $loader; - } - - /** - * Autoload Mustache classes. - * - * @param string $class - */ - public function autoload($class) - { - if ($class[0] === '\\') { - $class = substr($class, 1); - } - - if (strpos($class, 'Mustache') !== 0) { - return; - } - - $file = sprintf('%s/%s.php', $this->baseDir, str_replace('_', '/', $class)); - if (is_file($file)) { - require $file; - } - } -} diff --git a/builder/lib/Mustache/Compiler.php b/builder/lib/Mustache/Compiler.php deleted file mode 100644 index a95c9194b..000000000 --- a/builder/lib/Mustache/Compiler.php +++ /dev/null @@ -1,475 +0,0 @@ -pragmas = array(); - $this->sections = array(); - $this->source = $source; - $this->indentNextLine = true; - $this->customEscape = $customEscape; - $this->charset = $charset; - $this->strictCallables = $strictCallables; - - return $this->writeCode($tree, $name); - } - - /** - * Helper function for walking the Mustache token parse tree. - * - * @throws Mustache_Exception_SyntaxException upon encountering unknown token types. - * - * @param array $tree Parse tree of Mustache tokens - * @param int $level (default: 0) - * - * @return string Generated PHP source code - */ - private function walk(array $tree, $level = 0) - { - $code = ''; - $level++; - foreach ($tree as $node) { - switch ($node[Mustache_Tokenizer::TYPE]) { - case Mustache_Tokenizer::T_PRAGMA: - $this->pragmas[$node[Mustache_Tokenizer::NAME]] = true; - break; - - case Mustache_Tokenizer::T_SECTION: - $code .= $this->section( - $node[Mustache_Tokenizer::NODES], - $node[Mustache_Tokenizer::NAME], - $node[Mustache_Tokenizer::INDEX], - $node[Mustache_Tokenizer::END], - $node[Mustache_Tokenizer::OTAG], - $node[Mustache_Tokenizer::CTAG], - $level - ); - break; - - case Mustache_Tokenizer::T_INVERTED: - $code .= $this->invertedSection( - $node[Mustache_Tokenizer::NODES], - $node[Mustache_Tokenizer::NAME], - $level - ); - break; - - case Mustache_Tokenizer::T_PARTIAL: - case Mustache_Tokenizer::T_PARTIAL_2: - $code .= $this->partial( - $node[Mustache_Tokenizer::NAME], - isset($node[Mustache_Tokenizer::INDENT]) ? $node[Mustache_Tokenizer::INDENT] : '', - $level - ); - break; - - case Mustache_Tokenizer::T_UNESCAPED: - case Mustache_Tokenizer::T_UNESCAPED_2: - $code .= $this->variable($node[Mustache_Tokenizer::NAME], false, $level); - break; - - case Mustache_Tokenizer::T_COMMENT: - break; - - case Mustache_Tokenizer::T_ESCAPED: - $code .= $this->variable($node[Mustache_Tokenizer::NAME], true, $level); - break; - - case Mustache_Tokenizer::T_TEXT: - $code .= $this->text($node[Mustache_Tokenizer::VALUE], $level); - break; - - default: - throw new Mustache_Exception_SyntaxException(sprintf('Unknown token type: %s', $node[Mustache_Tokenizer::TYPE]), $node); - } - } - - return $code; - } - - const KLASS = 'lambdaHelper = new Mustache_LambdaHelper($this->mustache, $context); - $buffer = \'\'; - %s - - return $buffer; - } - %s - }'; - - const KLASS_NO_LAMBDAS = 'walk($tree); - $sections = implode("\n", $this->sections); - $klass = empty($this->sections) ? self::KLASS_NO_LAMBDAS : self::KLASS; - $callable = $this->strictCallables ? $this->prepare(self::STRICT_CALLABLE) : ''; - - return sprintf($this->prepare($klass, 0, false, true), $name, $callable, $code, $sections); - } - - const SECTION_CALL = ' - // %s section - $buffer .= $this->section%s($context, $indent, $context->%s(%s)); - '; - - const SECTION = ' - private function section%s(Mustache_Context $context, $indent, $value) - { - $buffer = \'\'; - if (%s) { - $source = %s; - $buffer .= $this->mustache - ->loadLambda((string) call_user_func($value, $source, $this->lambdaHelper)%s) - ->renderInternal($context, $indent); - } elseif (!empty($value)) { - $values = $this->isIterable($value) ? $value : array($value); - foreach ($values as $value) { - $context->push($value);%s - $context->pop(); - } - } - - return $buffer; - }'; - - /** - * Generate Mustache Template section PHP source. - * - * @param array $nodes Array of child tokens - * @param string $id Section name - * @param int $start Section start offset - * @param int $end Section end offset - * @param string $otag Current Mustache opening tag - * @param string $ctag Current Mustache closing tag - * @param int $level - * - * @return string Generated section PHP source code - */ - private function section($nodes, $id, $start, $end, $otag, $ctag, $level) - { - $method = $this->getFindMethod($id); - $id = var_export($id, true); - $source = var_export(substr($this->source, $start, $end - $start), true); - $callable = $this->getCallable(); - - if ($otag !== '{{' || $ctag !== '}}') { - $delims = ', '.var_export(sprintf('{{= %s %s =}}', $otag, $ctag), true); - } else { - $delims = ''; - } - - $key = ucfirst(md5($delims."\n".$source)); - - if (!isset($this->sections[$key])) { - $this->sections[$key] = sprintf($this->prepare(self::SECTION), $key, $callable, $source, $delims, $this->walk($nodes, 2)); - } - - return sprintf($this->prepare(self::SECTION_CALL, $level), $id, $key, $method, $id); - } - - const INVERTED_SECTION = ' - // %s inverted section - $value = $context->%s(%s); - if (empty($value)) { - %s - }'; - - /** - * Generate Mustache Template inverted section PHP source. - * - * @param array $nodes Array of child tokens - * @param string $id Section name - * @param int $level - * - * @return string Generated inverted section PHP source code - */ - private function invertedSection($nodes, $id, $level) - { - $method = $this->getFindMethod($id); - $id = var_export($id, true); - - return sprintf($this->prepare(self::INVERTED_SECTION, $level), $id, $method, $id, $this->walk($nodes, $level)); - } - - const PARTIAL = ' - if ($partial = $this->mustache->loadPartial(%s)) { - $buffer .= $partial->renderInternal($context, %s); - } - '; - - /** - * Generate Mustache Template partial call PHP source. - * - * @param string $id Partial name - * @param string $indent Whitespace indent to apply to partial - * @param int $level - * - * @return string Generated partial call PHP source code - */ - private function partial($id, $indent, $level) - { - return sprintf( - $this->prepare(self::PARTIAL, $level), - var_export($id, true), - var_export($indent, true) - ); - } - - const VARIABLE = ' - $value = $this->resolveValue($context->%s(%s), $context, $indent);%s - $buffer .= %s%s; - '; - - /** - * Generate Mustache Template variable interpolation PHP source. - * - * @param string $id Variable name - * @param boolean $escape Escape the variable value for output? - * @param int $level - * - * @return string Generated variable interpolation PHP source - */ - private function variable($id, $escape, $level) - { - $filters = ''; - - if (isset($this->pragmas[Mustache_Engine::PRAGMA_FILTERS])) { - list($id, $filters) = $this->getFilters($id, $level); - } - - $method = $this->getFindMethod($id); - $id = ($method !== 'last') ? var_export($id, true) : ''; - $value = $escape ? $this->getEscape() : '$value'; - - return sprintf($this->prepare(self::VARIABLE, $level), $method, $id, $filters, $this->flushIndent(), $value); - } - - /** - * Generate Mustache Template variable filtering PHP source. - * - * @param string $id Variable name - * @param int $level - * - * @return string Generated variable filtering PHP source - */ - private function getFilters($id, $level) - { - $filters = array_map('trim', explode('|', $id)); - $id = array_shift($filters); - - return array($id, $this->getFilter($filters, $level)); - } - - const FILTER = ' - $filter = $context->%s(%s); - if (!(%s)) { - throw new Mustache_Exception_UnknownFilterException(%s); - } - $value = call_user_func($filter, $value);%s - '; - - /** - * Generate PHP source for a single filter. - * - * @param array $filters - * @param int $level - * - * @return string Generated filter PHP source - */ - private function getFilter(array $filters, $level) - { - if (empty($filters)) { - return ''; - } - - $name = array_shift($filters); - $method = $this->getFindMethod($name); - $filter = ($method !== 'last') ? var_export($name, true) : ''; - $callable = $this->getCallable('$filter'); - $msg = var_export($name, true); - - return sprintf($this->prepare(self::FILTER, $level), $method, $filter, $callable, $msg, $this->getFilter($filters, $level)); - } - - const LINE = '$buffer .= "\n";'; - const TEXT = '$buffer .= %s%s;'; - - /** - * Generate Mustache Template output Buffer call PHP source. - * - * @param string $text - * @param int $level - * - * @return string Generated output Buffer call PHP source - */ - private function text($text, $level) - { - if ($text === "\n") { - $this->indentNextLine = true; - - return $this->prepare(self::LINE, $level); - } else { - return sprintf($this->prepare(self::TEXT, $level), $this->flushIndent(), var_export($text, true)); - } - } - - /** - * Prepare PHP source code snippet for output. - * - * @param string $text - * @param int $bonus Additional indent level (default: 0) - * @param boolean $prependNewline Prepend a newline to the snippet? (default: true) - * @param boolean $appendNewline Append a newline to the snippet? (default: false) - * - * @return string PHP source code snippet - */ - private function prepare($text, $bonus = 0, $prependNewline = true, $appendNewline = false) - { - $text = ($prependNewline ? "\n" : '').trim($text); - if ($prependNewline) { - $bonus++; - } - if ($appendNewline) { - $text .= "\n"; - } - - return preg_replace("/\n( {8})?/", "\n".str_repeat(" ", $bonus * 4), $text); - } - - const DEFAULT_ESCAPE = 'htmlspecialchars(%s, ENT_COMPAT, %s)'; - const CUSTOM_ESCAPE = 'call_user_func($this->mustache->getEscape(), %s)'; - - /** - * Get the current escaper. - * - * @param string $value (default: '$value') - * - * @return string Either a custom callback, or an inline call to `htmlspecialchars` - */ - private function getEscape($value = '$value') - { - if ($this->customEscape) { - return sprintf(self::CUSTOM_ESCAPE, $value); - } else { - return sprintf(self::DEFAULT_ESCAPE, $value, var_export($this->charset, true)); - } - } - - /** - * Select the appropriate Context `find` method for a given $id. - * - * The return value will be one of `find`, `findDot` or `last`. - * - * @see Mustache_Context::find - * @see Mustache_Context::findDot - * @see Mustache_Context::last - * - * @param string $id Variable name - * - * @return string `find` method name - */ - private function getFindMethod($id) - { - if ($id === '.') { - return 'last'; - } elseif (strpos($id, '.') === false) { - return 'find'; - } else { - return 'findDot'; - } - } - - const IS_CALLABLE = '!is_string(%s) && is_callable(%s)'; - const STRICT_IS_CALLABLE = 'is_object(%s) && is_callable(%s)'; - - private function getCallable($variable = '$value') - { - $tpl = $this->strictCallables ? self::STRICT_IS_CALLABLE : self::IS_CALLABLE; - - return sprintf($tpl, $variable, $variable); - } - - const LINE_INDENT = '$indent . '; - - /** - * Get the current $indent prefix to write to the buffer. - * - * @return string "$indent . " or "" - */ - private function flushIndent() - { - if ($this->indentNextLine) { - $this->indentNextLine = false; - - return self::LINE_INDENT; - } else { - return ''; - } - } -} diff --git a/builder/lib/Mustache/Context.php b/builder/lib/Mustache/Context.php deleted file mode 100644 index e7783b43c..000000000 --- a/builder/lib/Mustache/Context.php +++ /dev/null @@ -1,149 +0,0 @@ -stack = array($context); - } - } - - /** - * Push a new Context frame onto the stack. - * - * @param mixed $value Object or array to use for context - */ - public function push($value) - { - array_push($this->stack, $value); - } - - /** - * Pop the last Context frame from the stack. - * - * @return mixed Last Context frame (object or array) - */ - public function pop() - { - return array_pop($this->stack); - } - - /** - * Get the last Context frame. - * - * @return mixed Last Context frame (object or array) - */ - public function last() - { - return end($this->stack); - } - - /** - * Find a variable in the Context stack. - * - * Starting with the last Context frame (the context of the innermost section), and working back to the top-level - * rendering context, look for a variable with the given name: - * - * * If the Context frame is an associative array which contains the key $id, returns the value of that element. - * * If the Context frame is an object, this will check first for a public method, then a public property named - * $id. Failing both of these, it will try `__isset` and `__get` magic methods. - * * If a value named $id is not found in any Context frame, returns an empty string. - * - * @param string $id Variable name - * - * @return mixed Variable value, or '' if not found - */ - public function find($id) - { - return $this->findVariableInStack($id, $this->stack); - } - - /** - * Find a 'dot notation' variable in the Context stack. - * - * Note that dot notation traversal bubbles through scope differently than the regular find method. After finding - * the initial chunk of the dotted name, each subsequent chunk is searched for only within the value of the previous - * result. For example, given the following context stack: - * - * $data = array( - * 'name' => 'Fred', - * 'child' => array( - * 'name' => 'Bob' - * ), - * ); - * - * ... and the Mustache following template: - * - * {{ child.name }} - * - * ... the `name` value is only searched for within the `child` value of the global Context, not within parent - * Context frames. - * - * @param string $id Dotted variable selector - * - * @return mixed Variable value, or '' if not found - */ - public function findDot($id) - { - $chunks = explode('.', $id); - $first = array_shift($chunks); - $value = $this->findVariableInStack($first, $this->stack); - - foreach ($chunks as $chunk) { - if ($value === '') { - return $value; - } - - $value = $this->findVariableInStack($chunk, array($value)); - } - - return $value; - } - - /** - * Helper function to find a variable in the Context stack. - * - * @see Mustache_Context::find - * - * @param string $id Variable name - * @param array $stack Context stack - * - * @return mixed Variable value, or '' if not found - */ - private function findVariableInStack($id, array $stack) - { - for ($i = count($stack) - 1; $i >= 0; $i--) { - if (is_object($stack[$i]) && !$stack[$i] instanceof Closure) { - if (method_exists($stack[$i], $id)) { - return $stack[$i]->$id(); - } elseif (isset($stack[$i]->$id)) { - return $stack[$i]->$id; - } - } elseif (is_array($stack[$i]) && array_key_exists($id, $stack[$i])) { - return $stack[$i][$id]; - } - } - - return ''; - } -} diff --git a/builder/lib/Mustache/Engine.php b/builder/lib/Mustache/Engine.php deleted file mode 100644 index 5f92d1948..000000000 --- a/builder/lib/Mustache/Engine.php +++ /dev/null @@ -1,729 +0,0 @@ - '__MyTemplates_', - * - * // A cache directory for compiled templates. Mustache will not cache templates unless this is set - * 'cache' => dirname(__FILE__).'/tmp/cache/mustache', - * - * // Override default permissions for cache files. Defaults to using the system-defined umask. It is - * // *strongly* recommended that you configure your umask properly rather than overriding permissions here. - * 'cache_file_mode' => 0666, - * - * // A Mustache template loader instance. Uses a StringLoader if not specified. - * 'loader' => new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views'), - * - * // A Mustache loader instance for partials. - * 'partials_loader' => new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views/partials'), - * - * // An array of Mustache partials. Useful for quick-and-dirty string template loading, but not as - * // efficient or lazy as a Filesystem (or database) loader. - * 'partials' => array('foo' => file_get_contents(dirname(__FILE__).'/views/partials/foo.mustache')), - * - * // An array of 'helpers'. Helpers can be global variables or objects, closures (e.g. for higher order - * // sections), or any other valid Mustache context value. They will be prepended to the context stack, - * // so they will be available in any template loaded by this Mustache instance. - * 'helpers' => array('i18n' => function($text) { - * // do something translatey here... - * }), - * - * // An 'escape' callback, responsible for escaping double-mustache variables. - * 'escape' => function($value) { - * return htmlspecialchars($buffer, ENT_COMPAT, 'UTF-8'); - * }, - * - * // Character set for `htmlspecialchars`. Defaults to 'UTF-8'. Use 'UTF-8'. - * 'charset' => 'ISO-8859-1', - * - * // A Mustache Logger instance. No logging will occur unless this is set. Using a PSR-3 compatible - * // logging library -- such as Monolog -- is highly recommended. A simple stream logger implementation is - * // available as well: - * 'logger' => new Mustache_Logger_StreamLogger('php://stderr'), - * - * // Only treat Closure instances and invokable classes as callable. If true, values like - * // `array('ClassName', 'methodName')` and `array($classInstance, 'methodName')`, which are traditionally - * // "callable" in PHP, are not called to resolve variables for interpolation or section contexts. This - * // helps protect against arbitrary code execution when user input is passed directly into the template. - * // This currently defaults to false, but will default to true in v3.0. - * 'strict_callables' => true, - * ); - * - * @throws Mustache_Exception_InvalidArgumentException If `escape` option is not callable. - * - * @param array $options (default: array()) - */ - public function __construct(array $options = array()) - { - if (isset($options['template_class_prefix'])) { - $this->templateClassPrefix = $options['template_class_prefix']; - } - - if (isset($options['cache'])) { - $this->cache = $options['cache']; - } - - if (isset($options['cache_file_mode'])) { - $this->cacheFileMode = $options['cache_file_mode']; - } - - if (isset($options['loader'])) { - $this->setLoader($options['loader']); - } - - if (isset($options['partials_loader'])) { - $this->setPartialsLoader($options['partials_loader']); - } - - if (isset($options['partials'])) { - $this->setPartials($options['partials']); - } - - if (isset($options['helpers'])) { - $this->setHelpers($options['helpers']); - } - - if (isset($options['escape'])) { - if (!is_callable($options['escape'])) { - throw new Mustache_Exception_InvalidArgumentException('Mustache Constructor "escape" option must be callable'); - } - - $this->escape = $options['escape']; - } - - if (isset($options['charset'])) { - $this->charset = $options['charset']; - } - - if (isset($options['logger'])) { - $this->setLogger($options['logger']); - } - - if (isset($options['strict_callables'])) { - $this->strictCallables = $options['strict_callables']; - } - } - - /** - * Shortcut 'render' invocation. - * - * Equivalent to calling `$mustache->loadTemplate($template)->render($context);` - * - * @see Mustache_Engine::loadTemplate - * @see Mustache_Template::render - * - * @param string $template - * @param mixed $context (default: array()) - * - * @return string Rendered template - */ - public function render($template, $context = array()) - { - return $this->loadTemplate($template)->render($context); - } - - /** - * Get the current Mustache escape callback. - * - * @return mixed Callable or null - */ - public function getEscape() - { - return $this->escape; - } - - /** - * Get the current Mustache character set. - * - * @return string - */ - public function getCharset() - { - return $this->charset; - } - - /** - * Set the Mustache template Loader instance. - * - * @param Mustache_Loader $loader - */ - public function setLoader(Mustache_Loader $loader) - { - $this->loader = $loader; - } - - /** - * Get the current Mustache template Loader instance. - * - * If no Loader instance has been explicitly specified, this method will instantiate and return - * a StringLoader instance. - * - * @return Mustache_Loader - */ - public function getLoader() - { - if (!isset($this->loader)) { - $this->loader = new Mustache_Loader_StringLoader; - } - - return $this->loader; - } - - /** - * Set the Mustache partials Loader instance. - * - * @param Mustache_Loader $partialsLoader - */ - public function setPartialsLoader(Mustache_Loader $partialsLoader) - { - $this->partialsLoader = $partialsLoader; - } - - /** - * Get the current Mustache partials Loader instance. - * - * If no Loader instance has been explicitly specified, this method will instantiate and return - * an ArrayLoader instance. - * - * @return Mustache_Loader - */ - public function getPartialsLoader() - { - if (!isset($this->partialsLoader)) { - $this->partialsLoader = new Mustache_Loader_ArrayLoader; - } - - return $this->partialsLoader; - } - - /** - * Set partials for the current partials Loader instance. - * - * @throws Mustache_Exception_RuntimeException If the current Loader instance is immutable - * - * @param array $partials (default: array()) - */ - public function setPartials(array $partials = array()) - { - if (!isset($this->partialsLoader)) { - $this->partialsLoader = new Mustache_Loader_ArrayLoader; - } - - if (!$this->partialsLoader instanceof Mustache_Loader_MutableLoader) { - throw new Mustache_Exception_RuntimeException('Unable to set partials on an immutable Mustache Loader instance'); - } - - $this->partialsLoader->setTemplates($partials); - } - - /** - * Set an array of Mustache helpers. - * - * An array of 'helpers'. Helpers can be global variables or objects, closures (e.g. for higher order sections), or - * any other valid Mustache context value. They will be prepended to the context stack, so they will be available in - * any template loaded by this Mustache instance. - * - * @throws Mustache_Exception_InvalidArgumentException if $helpers is not an array or Traversable - * - * @param array|Traversable $helpers - */ - public function setHelpers($helpers) - { - if (!is_array($helpers) && !$helpers instanceof Traversable) { - throw new Mustache_Exception_InvalidArgumentException('setHelpers expects an array of helpers'); - } - - $this->getHelpers()->clear(); - - foreach ($helpers as $name => $helper) { - $this->addHelper($name, $helper); - } - } - - /** - * Get the current set of Mustache helpers. - * - * @see Mustache_Engine::setHelpers - * - * @return Mustache_HelperCollection - */ - public function getHelpers() - { - if (!isset($this->helpers)) { - $this->helpers = new Mustache_HelperCollection; - } - - return $this->helpers; - } - - /** - * Add a new Mustache helper. - * - * @see Mustache_Engine::setHelpers - * - * @param string $name - * @param mixed $helper - */ - public function addHelper($name, $helper) - { - $this->getHelpers()->add($name, $helper); - } - - /** - * Get a Mustache helper by name. - * - * @see Mustache_Engine::setHelpers - * - * @param string $name - * - * @return mixed Helper - */ - public function getHelper($name) - { - return $this->getHelpers()->get($name); - } - - /** - * Check whether this Mustache instance has a helper. - * - * @see Mustache_Engine::setHelpers - * - * @param string $name - * - * @return boolean True if the helper is present - */ - public function hasHelper($name) - { - return $this->getHelpers()->has($name); - } - - /** - * Remove a helper by name. - * - * @see Mustache_Engine::setHelpers - * - * @param string $name - */ - public function removeHelper($name) - { - $this->getHelpers()->remove($name); - } - - /** - * Set the Mustache Logger instance. - * - * @throws Mustache_Exception_InvalidArgumentException If logger is not an instance of Mustache_Logger or Psr\Log\LoggerInterface. - * - * @param Mustache_Logger|Psr\Log\LoggerInterface $logger - */ - public function setLogger($logger = null) - { - if ($logger !== null && !($logger instanceof Mustache_Logger || is_a($logger, 'Psr\\Log\\LoggerInterface'))) { - throw new Mustache_Exception_InvalidArgumentException('Expected an instance of Mustache_Logger or Psr\\Log\\LoggerInterface.'); - } - - $this->logger = $logger; - } - - /** - * Get the current Mustache Logger instance. - * - * @return Mustache_Logger|Psr\Log\LoggerInterface - */ - public function getLogger() - { - return $this->logger; - } - - /** - * Set the Mustache Tokenizer instance. - * - * @param Mustache_Tokenizer $tokenizer - */ - public function setTokenizer(Mustache_Tokenizer $tokenizer) - { - $this->tokenizer = $tokenizer; - } - - /** - * Get the current Mustache Tokenizer instance. - * - * If no Tokenizer instance has been explicitly specified, this method will instantiate and return a new one. - * - * @return Mustache_Tokenizer - */ - public function getTokenizer() - { - if (!isset($this->tokenizer)) { - $this->tokenizer = new Mustache_Tokenizer; - } - - return $this->tokenizer; - } - - /** - * Set the Mustache Parser instance. - * - * @param Mustache_Parser $parser - */ - public function setParser(Mustache_Parser $parser) - { - $this->parser = $parser; - } - - /** - * Get the current Mustache Parser instance. - * - * If no Parser instance has been explicitly specified, this method will instantiate and return a new one. - * - * @return Mustache_Parser - */ - public function getParser() - { - if (!isset($this->parser)) { - $this->parser = new Mustache_Parser; - } - - return $this->parser; - } - - /** - * Set the Mustache Compiler instance. - * - * @param Mustache_Compiler $compiler - */ - public function setCompiler(Mustache_Compiler $compiler) - { - $this->compiler = $compiler; - } - - /** - * Get the current Mustache Compiler instance. - * - * If no Compiler instance has been explicitly specified, this method will instantiate and return a new one. - * - * @return Mustache_Compiler - */ - public function getCompiler() - { - if (!isset($this->compiler)) { - $this->compiler = new Mustache_Compiler; - } - - return $this->compiler; - } - - /** - * Helper method to generate a Mustache template class. - * - * @param string $source - * - * @return string Mustache Template class name - */ - public function getTemplateClassName($source) - { - return $this->templateClassPrefix . md5(sprintf( - 'version:%s,escape:%s,charset:%s,strict_callables:%s,source:%s', - self::VERSION, - isset($this->escape) ? 'custom' : 'default', - $this->charset, - $this->strictCallables ? 'true' : 'false', - $source - )); - } - - /** - * Load a Mustache Template by name. - * - * @param string $name - * - * @return Mustache_Template - */ - public function loadTemplate($name) - { - return $this->loadSource($this->getLoader()->load($name)); - } - - /** - * Load a Mustache partial Template by name. - * - * This is a helper method used internally by Template instances for loading partial templates. You can most likely - * ignore it completely. - * - * @param string $name - * - * @return Mustache_Template - */ - public function loadPartial($name) - { - try { - if (isset($this->partialsLoader)) { - $loader = $this->partialsLoader; - } elseif (isset($this->loader) && !$this->loader instanceof Mustache_Loader_StringLoader) { - $loader = $this->loader; - } else { - throw new Mustache_Exception_UnknownTemplateException($name); - } - - return $this->loadSource($loader->load($name)); - } catch (Mustache_Exception_UnknownTemplateException $e) { - // If the named partial cannot be found, log then return null. - $this->log( - Mustache_Logger::WARNING, - 'Partial not found: "{name}"', - array('name' => $e->getTemplateName()) - ); - } - } - - /** - * Load a Mustache lambda Template by source. - * - * This is a helper method used by Template instances to generate subtemplates for Lambda sections. You can most - * likely ignore it completely. - * - * @param string $source - * @param string $delims (default: null) - * - * @return Mustache_Template - */ - public function loadLambda($source, $delims = null) - { - if ($delims !== null) { - $source = $delims . "\n" . $source; - } - - return $this->loadSource($source); - } - - /** - * Instantiate and return a Mustache Template instance by source. - * - * @see Mustache_Engine::loadTemplate - * @see Mustache_Engine::loadPartial - * @see Mustache_Engine::loadLambda - * - * @param string $source - * - * @return Mustache_Template - */ - private function loadSource($source) - { - $className = $this->getTemplateClassName($source); - - if (!isset($this->templates[$className])) { - if (!class_exists($className, false)) { - if ($fileName = $this->getCacheFilename($source)) { - if (!is_file($fileName)) { - $this->log( - Mustache_Logger::DEBUG, - 'Writing "{className}" class to template cache: "{fileName}"', - array('className' => $className, 'fileName' => $fileName) - ); - - $this->writeCacheFile($fileName, $this->compile($source)); - } - - require_once $fileName; - } else { - $this->log( - Mustache_Logger::WARNING, - 'Template cache disabled, evaluating "{className}" class at runtime', - array('className' => $className) - ); - - eval('?>'.$this->compile($source)); - } - } - - $this->log( - Mustache_Logger::DEBUG, - 'Instantiating template: "{className}"', - array('className' => $className) - ); - - $this->templates[$className] = new $className($this); - } - - return $this->templates[$className]; - } - - /** - * Helper method to tokenize a Mustache template. - * - * @see Mustache_Tokenizer::scan - * - * @param string $source - * - * @return array Tokens - */ - private function tokenize($source) - { - return $this->getTokenizer()->scan($source); - } - - /** - * Helper method to parse a Mustache template. - * - * @see Mustache_Parser::parse - * - * @param string $source - * - * @return array Token tree - */ - private function parse($source) - { - return $this->getParser()->parse($this->tokenize($source)); - } - - /** - * Helper method to compile a Mustache template. - * - * @see Mustache_Compiler::compile - * - * @param string $source - * - * @return string generated Mustache template class code - */ - private function compile($source) - { - $tree = $this->parse($source); - $name = $this->getTemplateClassName($source); - - $this->log( - Mustache_Logger::INFO, - 'Compiling template to "{className}" class', - array('className' => $name) - ); - - return $this->getCompiler()->compile($source, $tree, $name, isset($this->escape), $this->charset, $this->strictCallables); - } - - /** - * Helper method to generate a Mustache Template class cache filename. - * - * @param string $source - * - * @return string Mustache Template class cache filename - */ - private function getCacheFilename($source) - { - if ($this->cache) { - return sprintf('%s/%s.php', $this->cache, $this->getTemplateClassName($source)); - } - } - - /** - * Helper method to dump a generated Mustache Template subclass to the file cache. - * - * @throws Mustache_Exception_RuntimeException if unable to create the cache directory or write to $fileName. - * - * @param string $fileName - * @param string $source - * - * @codeCoverageIgnore - */ - private function writeCacheFile($fileName, $source) - { - $dirName = dirname($fileName); - if (!is_dir($dirName)) { - $this->log( - Mustache_Logger::INFO, - 'Creating Mustache template cache directory: "{dirName}"', - array('dirName' => $dirName) - ); - - @mkdir($dirName, 0777, true); - if (!is_dir($dirName)) { - throw new Mustache_Exception_RuntimeException(sprintf('Failed to create cache directory "%s".', $dirName)); - } - - } - - $this->log( - Mustache_Logger::DEBUG, - 'Caching compiled template to "{fileName}"', - array('fileName' => $fileName) - ); - - $tempFile = tempnam($dirName, basename($fileName)); - if (false !== @file_put_contents($tempFile, $source)) { - if (@rename($tempFile, $fileName)) { - $mode = isset($this->cacheFileMode) ? $this->cacheFileMode : (0666 & ~umask()); - @chmod($fileName, $mode); - - return; - } - - $this->log( - Mustache_Logger::ERROR, - 'Unable to rename Mustache temp cache file: "{tempName}" -> "{fileName}"', - array('tempName' => $tempFile, 'fileName' => $fileName) - ); - } - - throw new Mustache_Exception_RuntimeException(sprintf('Failed to write cache file "%s".', $fileName)); - } - - /** - * Add a log record if logging is enabled. - * - * @param integer $level The logging level - * @param string $message The log message - * @param array $context The log context - */ - private function log($level, $message, array $context = array()) - { - if (isset($this->logger)) { - $this->logger->log($level, $message, $context); - } - } -} diff --git a/builder/lib/Mustache/Exception.php b/builder/lib/Mustache/Exception.php deleted file mode 100644 index b4f830046..000000000 --- a/builder/lib/Mustache/Exception.php +++ /dev/null @@ -1,18 +0,0 @@ -token = $token; - parent::__construct($msg); - } - - public function getToken() - { - return $this->token; - } -} diff --git a/builder/lib/Mustache/Exception/UnknownFilterException.php b/builder/lib/Mustache/Exception/UnknownFilterException.php deleted file mode 100644 index f5c0884d4..000000000 --- a/builder/lib/Mustache/Exception/UnknownFilterException.php +++ /dev/null @@ -1,29 +0,0 @@ -filterName = $filterName; - parent::__construct(sprintf('Unknown filter: %s', $filterName)); - } - - public function getFilterName() - { - return $this->filterName; - } -} diff --git a/builder/lib/Mustache/Exception/UnknownHelperException.php b/builder/lib/Mustache/Exception/UnknownHelperException.php deleted file mode 100644 index 98af13ebe..000000000 --- a/builder/lib/Mustache/Exception/UnknownHelperException.php +++ /dev/null @@ -1,29 +0,0 @@ -helperName = $helperName; - parent::__construct(sprintf('Unknown helper: %s', $helperName)); - } - - public function getHelperName() - { - return $this->helperName; - } -} diff --git a/builder/lib/Mustache/Exception/UnknownTemplateException.php b/builder/lib/Mustache/Exception/UnknownTemplateException.php deleted file mode 100644 index 141d372bd..000000000 --- a/builder/lib/Mustache/Exception/UnknownTemplateException.php +++ /dev/null @@ -1,29 +0,0 @@ -templateName = $templateName; - parent::__construct(sprintf('Unknown template: %s', $templateName)); - } - - public function getTemplateName() - { - return $this->templateName; - } -} diff --git a/builder/lib/Mustache/HelperCollection.php b/builder/lib/Mustache/HelperCollection.php deleted file mode 100644 index e9911378a..000000000 --- a/builder/lib/Mustache/HelperCollection.php +++ /dev/null @@ -1,170 +0,0 @@ - $helper` pairs. - * - * @throws Mustache_Exception_InvalidArgumentException if the $helpers argument isn't an array or Traversable - * - * @param array|Traversable $helpers (default: null) - */ - public function __construct($helpers = null) - { - if ($helpers !== null) { - if (!is_array($helpers) && !$helpers instanceof Traversable) { - throw new Mustache_Exception_InvalidArgumentException('HelperCollection constructor expects an array of helpers'); - } - - foreach ($helpers as $name => $helper) { - $this->add($name, $helper); - } - } - } - - /** - * Magic mutator. - * - * @see Mustache_HelperCollection::add - * - * @param string $name - * @param mixed $helper - */ - public function __set($name, $helper) - { - $this->add($name, $helper); - } - - /** - * Add a helper to this collection. - * - * @param string $name - * @param mixed $helper - */ - public function add($name, $helper) - { - $this->helpers[$name] = $helper; - } - - /** - * Magic accessor. - * - * @see Mustache_HelperCollection::get - * - * @param string $name - * - * @return mixed Helper - */ - public function __get($name) - { - return $this->get($name); - } - - /** - * Get a helper by name. - * - * @throws Mustache_Exception_UnknownHelperException If helper does not exist. - * - * @param string $name - * - * @return mixed Helper - */ - public function get($name) - { - if (!$this->has($name)) { - throw new Mustache_Exception_UnknownHelperException($name); - } - - return $this->helpers[$name]; - } - - /** - * Magic isset(). - * - * @see Mustache_HelperCollection::has - * - * @param string $name - * - * @return boolean True if helper is present - */ - public function __isset($name) - { - return $this->has($name); - } - - /** - * Check whether a given helper is present in the collection. - * - * @param string $name - * - * @return boolean True if helper is present - */ - public function has($name) - { - return array_key_exists($name, $this->helpers); - } - - /** - * Magic unset(). - * - * @see Mustache_HelperCollection::remove - * - * @param string $name - */ - public function __unset($name) - { - $this->remove($name); - } - - /** - * Check whether a given helper is present in the collection. - * - * @throws Mustache_Exception_UnknownHelperException if the requested helper is not present. - * - * @param string $name - */ - public function remove($name) - { - if (!$this->has($name)) { - throw new Mustache_Exception_UnknownHelperException($name); - } - - unset($this->helpers[$name]); - } - - /** - * Clear the helper collection. - * - * Removes all helpers from this collection - */ - public function clear() - { - $this->helpers = array(); - } - - /** - * Check whether the helper collection is empty. - * - * @return boolean True if the collection is empty - */ - public function isEmpty() - { - return empty($this->helpers); - } -} diff --git a/builder/lib/Mustache/LICENSE b/builder/lib/Mustache/LICENSE deleted file mode 100644 index 6db530008..000000000 --- a/builder/lib/Mustache/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) -Copyright (c) 2010 Justin Hileman - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE -OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/builder/lib/Mustache/LambdaHelper.php b/builder/lib/Mustache/LambdaHelper.php deleted file mode 100644 index dfd4659c4..000000000 --- a/builder/lib/Mustache/LambdaHelper.php +++ /dev/null @@ -1,49 +0,0 @@ -mustache = $mustache; - $this->context = $context; - } - - /** - * Render a string as a Mustache template with the current rendering context. - * - * @param string $string - * - * @return Rendered template. - */ - public function render($string) - { - return $this->mustache - ->loadLambda((string) $string) - ->renderInternal($this->context); - } -} diff --git a/builder/lib/Mustache/Loader.php b/builder/lib/Mustache/Loader.php deleted file mode 100644 index f659a1d3a..000000000 --- a/builder/lib/Mustache/Loader.php +++ /dev/null @@ -1,28 +0,0 @@ - '{{ bar }}', - * 'baz' => 'Hey {{ qux }}!' - * ); - * - * $tpl = $loader->load('foo'); // '{{ bar }}' - * - * The ArrayLoader is used internally as a partials loader by Mustache_Engine instance when an array of partials - * is set. It can also be used as a quick-and-dirty Template loader. - */ -class Mustache_Loader_ArrayLoader implements Mustache_Loader, Mustache_Loader_MutableLoader -{ - - /** - * ArrayLoader constructor. - * - * @param array $templates Associative array of Template source (default: array()) - */ - public function __construct(array $templates = array()) - { - $this->templates = $templates; - } - - /** - * Load a Template. - * - * @throws Mustache_Exception_UnknownTemplateException If a template file is not found. - * - * @param string $name - * - * @return string Mustache Template source - */ - public function load($name) - { - if (!isset($this->templates[$name])) { - throw new Mustache_Exception_UnknownTemplateException($name); - } - - return $this->templates[$name]; - } - - /** - * Set an associative array of Template sources for this loader. - * - * @param array $templates - */ - public function setTemplates(array $templates) - { - $this->templates = $templates; - } - - /** - * Set a Template source by name. - * - * @param string $name - * @param string $template Mustache Template source - */ - public function setTemplate($name, $template) - { - $this->templates[$name] = $template; - } -} diff --git a/builder/lib/Mustache/Loader/CascadingLoader.php b/builder/lib/Mustache/Loader/CascadingLoader.php deleted file mode 100644 index 192edb97f..000000000 --- a/builder/lib/Mustache/Loader/CascadingLoader.php +++ /dev/null @@ -1,69 +0,0 @@ -loaders = array(); - foreach ($loaders as $loader) { - $this->addLoader($loader); - } - } - - /** - * Add a Loader instance. - * - * @param Mustache_Loader $loader A Mustache Loader instance - */ - public function addLoader(Mustache_Loader $loader) - { - $this->loaders[] = $loader; - } - - /** - * Load a Template by name. - * - * @throws Mustache_Exception_UnknownTemplateException If a template file is not found. - * - * @param string $name - * - * @return string Mustache Template source - */ - public function load($name) - { - foreach ($this->loaders as $loader) { - try { - return $loader->load($name); - } catch (Mustache_Exception_UnknownTemplateException $e) { - // do nothing, check the next loader. - } - } - - throw new Mustache_Exception_UnknownTemplateException($name); - } -} diff --git a/builder/lib/Mustache/Loader/FilesystemLoader.php b/builder/lib/Mustache/Loader/FilesystemLoader.php deleted file mode 100644 index 71d7f1c8e..000000000 --- a/builder/lib/Mustache/Loader/FilesystemLoader.php +++ /dev/null @@ -1,120 +0,0 @@ -load('foo'); // equivalent to `file_get_contents(dirname(__FILE__).'/views/foo.mustache'); - * - * This is probably the most useful Mustache Loader implementation. It can be used for partials and normal Templates: - * - * $m = new Mustache(array( - * 'loader' => new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views'), - * 'partials_loader' => new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views/partials'), - * )); - */ -class Mustache_Loader_FilesystemLoader implements Mustache_Loader -{ - private $baseDir; - private $extension = '.mustache'; - private $templates = array(); - - /** - * Mustache filesystem Loader constructor. - * - * Passing an $options array allows overriding certain Loader options during instantiation: - * - * $options = array( - * // The filename extension used for Mustache templates. Defaults to '.mustache' - * 'extension' => '.ms', - * ); - * - * @throws Mustache_Exception_RuntimeException if $baseDir does not exist. - * - * @param string $baseDir Base directory containing Mustache template files. - * @param array $options Array of Loader options (default: array()) - */ - public function __construct($baseDir, array $options = array()) - { - $this->baseDir = rtrim(realpath($baseDir), '/'); - - if (!is_dir($this->baseDir)) { - throw new Mustache_Exception_RuntimeException(sprintf('FilesystemLoader baseDir must be a directory: %s', $baseDir)); - } - - if (array_key_exists('extension', $options)) { - if (empty($options['extension'])) { - $this->extension = ''; - } else { - $this->extension = '.' . ltrim($options['extension'], '.'); - } - } - } - - /** - * Load a Template by name. - * - * $loader = new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views'); - * $loader->load('admin/dashboard'); // loads "./views/admin/dashboard.mustache"; - * - * @param string $name - * - * @return string Mustache Template source - */ - public function load($name) - { - if (!isset($this->templates[$name])) { - $this->templates[$name] = $this->loadFile($name); - } - - return $this->templates[$name]; - } - - /** - * Helper function for loading a Mustache file by name. - * - * @throws Mustache_Exception_UnknownTemplateException If a template file is not found. - * - * @param string $name - * - * @return string Mustache Template source - */ - protected function loadFile($name) - { - $fileName = $this->getFileName($name); - - if (!file_exists($fileName)) { - throw new Mustache_Exception_UnknownTemplateException($name); - } - - return file_get_contents($fileName); - } - - /** - * Helper function for getting a Mustache template file name. - * - * @param string $name - * - * @return string Template file name - */ - protected function getFileName($name) - { - $fileName = $this->baseDir . '/' . $name; - if (substr($fileName, 0 - strlen($this->extension)) !== $this->extension) { - $fileName .= $this->extension; - } - - return $fileName; - } -} diff --git a/builder/lib/Mustache/Loader/InlineLoader.php b/builder/lib/Mustache/Loader/InlineLoader.php deleted file mode 100644 index 1463bf8b5..000000000 --- a/builder/lib/Mustache/Loader/InlineLoader.php +++ /dev/null @@ -1,121 +0,0 @@ -load('hello'); - * $goodbye = $loader->load('goodbye'); - * - * __halt_compiler(); - * - * @@ hello - * Hello, {{ planet }}! - * - * @@ goodbye - * Goodbye, cruel {{ planet }} - * - * Templates are deliniated by lines containing only `@@ name`. - * - * The InlineLoader is well-suited to micro-frameworks such as Silex: - * - * $app->register(new MustacheServiceProvider, array( - * 'mustache.loader' => new Mustache_Loader_InlineLoader(__FILE__, __COMPILER_HALT_OFFSET__) - * )); - * - * $app->get('/{name}', function() use ($app) { - * return $app['mustache']->render('hello', compact('name')); - * }) - * ->value('name', 'world'); - * - * __halt_compiler(); - * - * @@ hello - * Hello, {{ name }}! - * - */ -class Mustache_Loader_InlineLoader implements Mustache_Loader -{ - protected $fileName; - protected $offset; - protected $templates; - - /** - * The InlineLoader requires a filename and offset to process templates. - * The magic constants `__FILE__` and `__COMPILER_HALT_OFFSET__` are usually - * perfectly suited to the job: - * - * $loader = new Mustache_Loader_InlineLoader(__FILE__, __COMPILER_HALT_OFFSET__); - * - * Note that this only works if the loader is instantiated inside the same - * file as the inline templates. If the templates are located in another - * file, it would be necessary to manually specify the filename and offset. - * - * @param string $fileName The file to parse for inline templates - * @param int $offset A string offset for the start of the templates. - * This usually coincides with the `__halt_compiler` - * call, and the `__COMPILER_HALT_OFFSET__`. - */ - public function __construct($fileName, $offset) - { - if (!is_file($fileName)) { - throw new Mustache_Exception_InvalidArgumentException('InlineLoader expects a valid filename.'); - } - - if (!is_int($offset) || $offset < 0) { - throw new Mustache_Exception_InvalidArgumentException('InlineLoader expects a valid file offset.'); - } - - $this->fileName = $fileName; - $this->offset = $offset; - } - - /** - * Load a Template by name. - * - * @throws Mustache_Exception_UnknownTemplateException If a template file is not found. - * - * @param string $name - * - * @return string Mustache Template source - */ - public function load($name) - { - $this->loadTemplates(); - - if (!array_key_exists($name, $this->templates)) { - throw new Mustache_Exception_UnknownTemplateException($name); - } - - return $this->templates[$name]; - } - - /** - * Parse and load templates from the end of a source file. - */ - protected function loadTemplates() - { - if ($this->templates === null) { - $this->templates = array(); - $data = file_get_contents($this->fileName, false, null, $this->offset); - foreach (preg_split("/^@@(?= [\w\d\.]+$)/m", $data, -1) as $chunk) { - if (trim($chunk)) { - list($name, $content) = explode("\n", $chunk, 2); - $this->templates[trim($name)] = trim($content); - } - } - } - } -} diff --git a/builder/lib/Mustache/Loader/MutableLoader.php b/builder/lib/Mustache/Loader/MutableLoader.php deleted file mode 100644 index 02bb207a9..000000000 --- a/builder/lib/Mustache/Loader/MutableLoader.php +++ /dev/null @@ -1,32 +0,0 @@ -load('{{ foo }}'); // '{{ foo }}' - * - * This is the default Template Loader instance used by Mustache: - * - * $m = new Mustache; - * $tpl = $m->loadTemplate('{{ foo }}'); - * echo $tpl->render(array('foo' => 'bar')); // "bar" - */ -class Mustache_Loader_StringLoader implements Mustache_Loader -{ - - /** - * Load a Template by source. - * - * @param string $name Mustache Template source - * - * @return string Mustache Template source - */ - public function load($name) - { - return $name; - } -} diff --git a/builder/lib/Mustache/Logger.php b/builder/lib/Mustache/Logger.php deleted file mode 100644 index e08359a91..000000000 --- a/builder/lib/Mustache/Logger.php +++ /dev/null @@ -1,135 +0,0 @@ -log(Mustache_Logger::EMERGENCY, $message, $context); - } - - /** - * Action must be taken immediately. - * - * Example: Entire website down, database unavailable, etc. This should - * trigger the SMS alerts and wake you up. - * - * @param string $message - * @param array $context - */ - public function alert($message, array $context = array()) - { - $this->log(Mustache_Logger::ALERT, $message, $context); - } - - /** - * Critical conditions. - * - * Example: Application component unavailable, unexpected exception. - * - * @param string $message - * @param array $context - */ - public function critical($message, array $context = array()) - { - $this->log(Mustache_Logger::CRITICAL, $message, $context); - } - - /** - * Runtime errors that do not require immediate action but should typically - * be logged and monitored. - * - * @param string $message - * @param array $context - */ - public function error($message, array $context = array()) - { - $this->log(Mustache_Logger::ERROR, $message, $context); - } - - /** - * Exceptional occurrences that are not errors. - * - * Example: Use of deprecated APIs, poor use of an API, undesirable things - * that are not necessarily wrong. - * - * @param string $message - * @param array $context - */ - public function warning($message, array $context = array()) - { - $this->log(Mustache_Logger::WARNING, $message, $context); - } - - /** - * Normal but significant events. - * - * @param string $message - * @param array $context - */ - public function notice($message, array $context = array()) - { - $this->log(Mustache_Logger::NOTICE, $message, $context); - } - - /** - * Interesting events. - * - * Example: User logs in, SQL logs. - * - * @param string $message - * @param array $context - */ - public function info($message, array $context = array()) - { - $this->log(Mustache_Logger::INFO, $message, $context); - } - - /** - * Detailed debug information. - * - * @param string $message - * @param array $context - */ - public function debug($message, array $context = array()) - { - $this->log(Mustache_Logger::DEBUG, $message, $context); - } -} diff --git a/builder/lib/Mustache/Logger/StreamLogger.php b/builder/lib/Mustache/Logger/StreamLogger.php deleted file mode 100644 index da771f90e..000000000 --- a/builder/lib/Mustache/Logger/StreamLogger.php +++ /dev/null @@ -1,193 +0,0 @@ - 100, - self::INFO => 200, - self::NOTICE => 250, - self::WARNING => 300, - self::ERROR => 400, - self::CRITICAL => 500, - self::ALERT => 550, - self::EMERGENCY => 600, - ); - - protected $stream = null; - protected $url = null; - - /** - * @throws InvalidArgumentException if the logging level is unknown. - * - * @param string $stream Resource instance or URL - * @param integer $level The minimum logging level at which this handler will be triggered - */ - public function __construct($stream, $level = Mustache_Logger::ERROR) - { - $this->setLevel($level); - - if (is_resource($stream)) { - $this->stream = $stream; - } else { - $this->url = $stream; - } - } - - /** - * Close stream resources. - */ - public function __destruct() - { - if (is_resource($this->stream)) { - fclose($this->stream); - } - } - - /** - * Set the minimum logging level. - * - * @throws Mustache_Exception_InvalidArgumentException if the logging level is unknown. - * - * @param integer $level The minimum logging level which will be written - */ - public function setLevel($level) - { - if (!array_key_exists($level, self::$levels)) { - throw new Mustache_Exception_InvalidArgumentException(sprintf('Unexpected logging level: %s', $level)); - } - - $this->level = $level; - } - - /** - * Get the current minimum logging level. - * - * @return integer - */ - public function getLevel() - { - return $this->level; - } - - /** - * Logs with an arbitrary level. - * - * @throws Mustache_Exception_InvalidArgumentException if the logging level is unknown. - * - * @param mixed $level - * @param string $message - * @param array $context - */ - public function log($level, $message, array $context = array()) - { - if (!array_key_exists($level, self::$levels)) { - throw new Mustache_Exception_InvalidArgumentException(sprintf('Unexpected logging level: %s', $level)); - } - - if (self::$levels[$level] >= self::$levels[$this->level]) { - $this->writeLog($level, $message, $context); - } - } - - /** - * Write a record to the log. - * - * @throws Mustache_Exception_LogicException If neither a stream resource nor url is present. - * @throws Mustache_Exception_RuntimeException If the stream url cannot be opened. - * - * @param integer $level The logging level - * @param string $message The log message - * @param array $context The log context - */ - protected function writeLog($level, $message, array $context = array()) - { - if (!is_resource($this->stream)) { - if (!isset($this->url)) { - throw new Mustache_Exception_LogicException('Missing stream url, the stream can not be opened. This may be caused by a premature call to close().'); - } - - $this->stream = fopen($this->url, 'a'); - if (!is_resource($this->stream)) { - // @codeCoverageIgnoreStart - throw new Mustache_Exception_RuntimeException(sprintf('The stream or file "%s" could not be opened.', $this->url)); - // @codeCoverageIgnoreEnd - } - } - - fwrite($this->stream, self::formatLine($level, $message, $context)); - } - - /** - * Gets the name of the logging level. - * - * @throws InvalidArgumentException if the logging level is unknown. - * - * @param integer $level - * - * @return string - */ - protected static function getLevelName($level) - { - return strtoupper($level); - } - - /** - * Format a log line for output. - * - * @param integer $level The logging level - * @param string $message The log message - * @param array $context The log context - * - * @return string - */ - protected static function formatLine($level, $message, array $context = array()) - { - return sprintf( - "%s: %s\n", - self::getLevelName($level), - self::interpolateMessage($message, $context) - ); - } - - /** - * Interpolate context values into the message placeholders. - * - * @param string $message - * @param array $context - * - * @return string - */ - protected static function interpolateMessage($message, array $context = array()) - { - if (strpos($message, '{') === false) { - return $message; - } - - // build a replacement array with braces around the context keys - $replace = array(); - foreach ($context as $key => $val) { - $replace['{' . $key . '}'] = $val; - } - - // interpolate replacement values into the the message and return - return strtr($message, $replace); - } -} diff --git a/builder/lib/Mustache/Parser.php b/builder/lib/Mustache/Parser.php deleted file mode 100644 index ab7db8463..000000000 --- a/builder/lib/Mustache/Parser.php +++ /dev/null @@ -1,91 +0,0 @@ -buildTree(new ArrayIterator($tokens)); - } - - /** - * Helper method for recursively building a parse tree. - * - * @throws Mustache_Exception_SyntaxException when nesting errors or mismatched section tags are encountered. - * - * @param ArrayIterator $tokens Stream of Mustache tokens - * @param array $parent Parent token (default: null) - * - * @return array Mustache Token parse tree - */ - private function buildTree(ArrayIterator $tokens, array $parent = null) - { - $nodes = array(); - - do { - $token = $tokens->current(); - $tokens->next(); - - if ($token === null) { - continue; - } else { - switch ($token[Mustache_Tokenizer::TYPE]) { - case Mustache_Tokenizer::T_SECTION: - case Mustache_Tokenizer::T_INVERTED: - $nodes[] = $this->buildTree($tokens, $token); - break; - - case Mustache_Tokenizer::T_END_SECTION: - if (!isset($parent)) { - $msg = sprintf('Unexpected closing tag: /%s', $token[Mustache_Tokenizer::NAME]); - throw new Mustache_Exception_SyntaxException($msg, $token); - } - - if ($token[Mustache_Tokenizer::NAME] !== $parent[Mustache_Tokenizer::NAME]) { - $msg = sprintf('Nesting error: %s vs. %s', $parent[Mustache_Tokenizer::NAME], $token[Mustache_Tokenizer::NAME]); - throw new Mustache_Exception_SyntaxException($msg, $token); - } - - $parent[Mustache_Tokenizer::END] = $token[Mustache_Tokenizer::INDEX]; - $parent[Mustache_Tokenizer::NODES] = $nodes; - - return $parent; - break; - - default: - $nodes[] = $token; - break; - } - } - - } while ($tokens->valid()); - - if (isset($parent)) { - $msg = sprintf('Missing closing tag: %s', $parent[Mustache_Tokenizer::NAME]); - throw new Mustache_Exception_SyntaxException($msg, $parent); - } - - return $nodes; - } -} diff --git a/builder/lib/Mustache/Template.php b/builder/lib/Mustache/Template.php deleted file mode 100644 index aeee42d49..000000000 --- a/builder/lib/Mustache/Template.php +++ /dev/null @@ -1,177 +0,0 @@ -mustache = $mustache; - } - - /** - * Mustache Template instances can be treated as a function and rendered by simply calling them: - * - * $m = new Mustache_Engine; - * $tpl = $m->loadTemplate('Hello, {{ name }}!'); - * echo $tpl(array('name' => 'World')); // "Hello, World!" - * - * @see Mustache_Template::render - * - * @param mixed $context Array or object rendering context (default: array()) - * - * @return string Rendered template - */ - public function __invoke($context = array()) - { - return $this->render($context); - } - - /** - * Render this template given the rendering context. - * - * @param mixed $context Array or object rendering context (default: array()) - * - * @return string Rendered template - */ - public function render($context = array()) - { - return $this->renderInternal($this->prepareContextStack($context)); - } - - /** - * Internal rendering method implemented by Mustache Template concrete subclasses. - * - * This is where the magic happens :) - * - * NOTE: This method is not part of the Mustache.php public API. - * - * @param Mustache_Context $context - * @param string $indent (default: '') - * - * @return string Rendered template - */ - abstract public function renderInternal(Mustache_Context $context, $indent = ''); - - /** - * Tests whether a value should be iterated over (e.g. in a section context). - * - * In most languages there are two distinct array types: list and hash (or whatever you want to call them). Lists - * should be iterated, hashes should be treated as objects. Mustache follows this paradigm for Ruby, Javascript, - * Java, Python, etc. - * - * PHP, however, treats lists and hashes as one primitive type: array. So Mustache.php needs a way to distinguish - * between between a list of things (numeric, normalized array) and a set of variables to be used as section context - * (associative array). In other words, this will be iterated over: - * - * $items = array( - * array('name' => 'foo'), - * array('name' => 'bar'), - * array('name' => 'baz'), - * ); - * - * ... but this will be used as a section context block: - * - * $items = array( - * 1 => array('name' => 'foo'), - * 'banana' => array('name' => 'bar'), - * 42 => array('name' => 'baz'), - * ); - * - * @param mixed $value - * - * @return boolean True if the value is 'iterable' - */ - protected function isIterable($value) - { - if (is_object($value)) { - return $value instanceof Traversable; - } elseif (is_array($value)) { - $i = 0; - foreach ($value as $k => $v) { - if ($k !== $i++) { - return false; - } - } - - return true; - } else { - return false; - } - } - - /** - * Helper method to prepare the Context stack. - * - * Adds the Mustache HelperCollection to the stack's top context frame if helpers are present. - * - * @param mixed $context Optional first context frame (default: null) - * - * @return Mustache_Context - */ - protected function prepareContextStack($context = null) - { - $stack = new Mustache_Context; - - $helpers = $this->mustache->getHelpers(); - if (!$helpers->isEmpty()) { - $stack->push($helpers); - } - - if (!empty($context)) { - $stack->push($context); - } - - return $stack; - } - - /** - * Resolve a context value. - * - * Invoke the value if it is callable, otherwise return the value. - * - * @param mixed $value - * @param Mustache_Context $context - * @param string $indent - * - * @return string - */ - protected function resolveValue($value, Mustache_Context $context, $indent = '') - { - if (($this->strictCallables ? is_object($value) : !is_string($value)) && is_callable($value)) { - return $this->mustache - ->loadLambda((string) call_user_func($value)) - ->renderInternal($context, $indent); - } - - return $value; - } -} diff --git a/builder/lib/Mustache/Tokenizer.php b/builder/lib/Mustache/Tokenizer.php deleted file mode 100644 index 56e8ba6b7..000000000 --- a/builder/lib/Mustache/Tokenizer.php +++ /dev/null @@ -1,315 +0,0 @@ -'; - const T_PARTIAL_2 = '<'; - const T_DELIM_CHANGE = '='; - const T_ESCAPED = '_v'; - const T_UNESCAPED = '{'; - const T_UNESCAPED_2 = '&'; - const T_TEXT = '_t'; - const T_PRAGMA = '%'; - - // Valid token types - private static $tagTypes = array( - self::T_SECTION => true, - self::T_INVERTED => true, - self::T_END_SECTION => true, - self::T_COMMENT => true, - self::T_PARTIAL => true, - self::T_PARTIAL_2 => true, - self::T_DELIM_CHANGE => true, - self::T_ESCAPED => true, - self::T_UNESCAPED => true, - self::T_UNESCAPED_2 => true, - self::T_PRAGMA => true, - ); - - // Interpolated tags - private static $interpolatedTags = array( - self::T_ESCAPED => true, - self::T_UNESCAPED => true, - self::T_UNESCAPED_2 => true, - ); - - // Token properties - const TYPE = 'type'; - const NAME = 'name'; - const OTAG = 'otag'; - const CTAG = 'ctag'; - const INDEX = 'index'; - const END = 'end'; - const INDENT = 'indent'; - const NODES = 'nodes'; - const VALUE = 'value'; - - private $pragmas; - private $state; - private $tagType; - private $tag; - private $buffer; - private $tokens; - private $seenTag; - private $lineStart; - private $otag; - private $ctag; - - /** - * Scan and tokenize template source. - * - * @param string $text Mustache template source to tokenize - * @param string $delimiters Optionally, pass initial opening and closing delimiters (default: null) - * - * @return array Set of Mustache tokens - */ - public function scan($text, $delimiters = null) - { - $this->reset(); - - if ($delimiters = trim($delimiters)) { - list($otag, $ctag) = explode(' ', $delimiters); - $this->otag = $otag; - $this->ctag = $ctag; - } - - $len = strlen($text); - for ($i = 0; $i < $len; $i++) { - switch ($this->state) { - case self::IN_TEXT: - if ($this->tagChange($this->otag, $text, $i)) { - $i--; - $this->flushBuffer(); - $this->state = self::IN_TAG_TYPE; - } else { - $char = substr($text, $i, 1); - if ($char == "\n") { - $this->filterLine(); - } else { - $this->buffer .= $char; - } - } - break; - - case self::IN_TAG_TYPE: - - $i += strlen($this->otag) - 1; - $char = substr($text, $i + 1, 1); - if (isset(self::$tagTypes[$char])) { - $tag = $char; - $this->tagType = $tag; - } else { - $tag = null; - $this->tagType = self::T_ESCAPED; - } - - if ($this->tagType === self::T_DELIM_CHANGE) { - $i = $this->changeDelimiters($text, $i); - $this->state = self::IN_TEXT; - } elseif ($this->tagType === self::T_PRAGMA) { - $i = $this->addPragma($text, $i); - $this->state = self::IN_TEXT; - } else { - if ($tag !== null) { - $i++; - } - $this->state = self::IN_TAG; - } - $this->seenTag = $i; - break; - - default: - if ($this->tagChange($this->ctag, $text, $i)) { - $this->tokens[] = array( - self::TYPE => $this->tagType, - self::NAME => trim($this->buffer), - self::OTAG => $this->otag, - self::CTAG => $this->ctag, - self::INDEX => ($this->tagType == self::T_END_SECTION) ? $this->seenTag - strlen($this->otag) : $i + strlen($this->ctag) - ); - - $this->buffer = ''; - $i += strlen($this->ctag) - 1; - $this->state = self::IN_TEXT; - if ($this->tagType == self::T_UNESCAPED) { - if ($this->ctag == '}}') { - $i++; - } else { - // Clean up `{{{ tripleStache }}}` style tokens. - $lastName = $this->tokens[count($this->tokens) - 1][self::NAME]; - if (substr($lastName, -1) === '}') { - $this->tokens[count($this->tokens) - 1][self::NAME] = trim(substr($lastName, 0, -1)); - } - } - } - } else { - $this->buffer .= substr($text, $i, 1); - } - break; - } - } - - $this->filterLine(true); - - foreach ($this->pragmas as $pragma) { - array_unshift($this->tokens, array( - self::TYPE => self::T_PRAGMA, - self::NAME => $pragma, - )); - } - - return $this->tokens; - } - - /** - * Helper function to reset tokenizer internal state. - */ - private function reset() - { - $this->state = self::IN_TEXT; - $this->tagType = null; - $this->tag = null; - $this->buffer = ''; - $this->tokens = array(); - $this->seenTag = false; - $this->lineStart = 0; - $this->otag = '{{'; - $this->ctag = '}}'; - $this->pragmas = array(); - } - - /** - * Flush the current buffer to a token. - */ - private function flushBuffer() - { - if (!empty($this->buffer)) { - $this->tokens[] = array(self::TYPE => self::T_TEXT, self::VALUE => $this->buffer); - $this->buffer = ''; - } - } - - /** - * Test whether the current line is entirely made up of whitespace. - * - * @return boolean True if the current line is all whitespace - */ - private function lineIsWhitespace() - { - $tokensCount = count($this->tokens); - for ($j = $this->lineStart; $j < $tokensCount; $j++) { - $token = $this->tokens[$j]; - if (isset(self::$tagTypes[$token[self::TYPE]])) { - if (isset(self::$interpolatedTags[$token[self::TYPE]])) { - return false; - } - } elseif ($token[self::TYPE] == self::T_TEXT) { - if (preg_match('/\S/', $token[self::VALUE])) { - return false; - } - } - } - - return true; - } - - /** - * Filter out whitespace-only lines and store indent levels for partials. - * - * @param bool $noNewLine Suppress the newline? (default: false) - */ - private function filterLine($noNewLine = false) - { - $this->flushBuffer(); - if ($this->seenTag && $this->lineIsWhitespace()) { - $tokensCount = count($this->tokens); - for ($j = $this->lineStart; $j < $tokensCount; $j++) { - if ($this->tokens[$j][self::TYPE] == self::T_TEXT) { - if (isset($this->tokens[$j+1]) && $this->tokens[$j+1][self::TYPE] == self::T_PARTIAL) { - $this->tokens[$j+1][self::INDENT] = $this->tokens[$j][self::VALUE]; - } - - $this->tokens[$j] = null; - } - } - } elseif (!$noNewLine) { - $this->tokens[] = array(self::TYPE => self::T_TEXT, self::VALUE => "\n"); - } - - $this->seenTag = false; - $this->lineStart = count($this->tokens); - } - - /** - * Change the current Mustache delimiters. Set new `otag` and `ctag` values. - * - * @param string $text Mustache template source - * @param int $index Current tokenizer index - * - * @return int New index value - */ - private function changeDelimiters($text, $index) - { - $startIndex = strpos($text, '=', $index) + 1; - $close = '='.$this->ctag; - $closeIndex = strpos($text, $close, $index); - - list($otag, $ctag) = explode(' ', trim(substr($text, $startIndex, $closeIndex - $startIndex))); - $this->otag = $otag; - $this->ctag = $ctag; - - return $closeIndex + strlen($close) - 1; - } - - private function addPragma($text, $index) - { - $end = strpos($text, $this->ctag, $index); - $this->pragmas[] = trim(substr($text, $index + 2, $end - $index - 2)); - - return $end + strlen($this->ctag) - 1; - } - - /** - * Test whether it's time to change tags. - * - * @param string $tag Current tag name - * @param string $text Mustache template source - * @param int $index Current tokenizer index - * - * @return boolean True if this is a closing section tag - */ - private function tagChange($tag, $text, $index) - { - return substr($text, $index, strlen($tag)) === $tag; - } - - public function returnTokens() - { - return $this->tokens; - } -} diff --git a/builder/lib/watcher.lib.php b/builder/lib/Watchr.php similarity index 100% rename from builder/lib/watcher.lib.php rename to builder/lib/Watchr.php diff --git a/builder/lib/css-rule-saver/LICENSE b/builder/lib/css-rule-saver/LICENSE deleted file mode 100644 index 2e13f8ef8..000000000 --- a/builder/lib/css-rule-saver/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013 Dave Olsen, http://dmolsen.com - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/builder/lib/css-rule-saver/css-rule-saver.php b/builder/lib/css-rule-saver/css-rule-saver.php deleted file mode 100644 index 061d11f5f..000000000 --- a/builder/lib/css-rule-saver/css-rule-saver.php +++ /dev/null @@ -1,267 +0,0 @@ -ruleSets and $this->atRules arrays - * @param {String} the filename of the CSS file - */ - public function loadCSS($file) { - - if (!file_exists($file)) { - $this->error("The CSS file you supplied doesn't seem to exist. Check the path."); - } - - $commentOpen = false; - $atRuleOpen = false; - $declarationBlockOpen = false; - $fontFaceRuleOpen = false; - - $atRule = ""; - $declarationBlock = ""; - $selectors = ""; - - // iterate over the given file and parse it into at-rules, selectors and their given declaration blocks - $fp = fopen($file, "r"); - while(!feof($fp)) { - $current_line = fgets($fp); - if (!feof($fp)) { - - if ((strpos($current_line, "/*") !== false) && (strpos($current_line, "*/") === false)) { - - // matched a comment that *didn't* close on the same line - $commentOpen = true; - - } else if (strpos($current_line, "*/") !== false) { - - // comment closed - $commentOpen = false; - - } else if ($commentOpen) { - - // skip this line of the CSS file because we're inside a comment - - } else if (strpos($current_line, "@") !== false) { - - // matched an at-rule like a media query - $atRuleOpen = true; - $atRule = trim(str_replace("{","",$current_line)); - - // handle the weird case of the @font-face at-rule - if (strpos($current_line, "@font-face") !== false) { - $declarationBlock = ""; - $declarationBlockOpen = true; - $fontFaceRuleOpen = true; - } - - } else if (strpos($current_line, "{") !== false) { - - // matched the opening of a declaration block - $declarationBlock = ""; - $declarationBlockOpen = true; - $selectors = trim(str_replace("{","",$current_line)); - - } else if (strpos($current_line, "}") !== false) { - - // matched the closing of a declaration block or at-rule - if ($atRuleOpen && !$declarationBlockOpen) { - - // it was an at-rule. close it up - $atRuleOpen = false; - - } else { - - // it was a declaration block. close it up. - $declarationBlockOpen = false; - $declarationBlock .= "\t".trim(str_replace("}","",$current_line)); - - // if we're within an at-rule assign all the styles to it (e.g. styles under a media query) - if ($atRuleOpen) { - if (!array_key_exists($atRule,$this->atRules)) { - $this->atRules[$atRule] = array(); - } - $this->atRules[$atRule][$selectors] = !array_key_exists($selectors,$this->atRules[$atRule]) ? "\t".trim($declarationBlock) : $this->atRules[$atRule][$selectors]."\n\t".trim($declarationBlock); - } else { - $this->ruleSets[$selectors] = !array_key_exists($selectors,$this->ruleSets) ? "\t".trim($declarationBlock) : $this->ruleSets[$selectors]."\n\t".trim($declarationBlock); - } - - // wait, a font-face rule was open. close it all up - if ($fontFaceRuleOpen) { - $fontFaceRuleOpen = false; - $atRuleOpen = false; - } else if (substr_count($current_line, "}") > 1) { - - // oops, someone closed the at-rule on the same line as the declaration block - // *shakes fist at sass* - $atRuleOpen = false; - } - } - } else if ($declarationBlockOpen) { - - // declaration block is open so keep reading it in - $declarationBlock .= "\t".ltrim($current_line); - - } - } - } - fclose($fp); - - } - - /** - * Load the HTML data - * @param {String} the filename of the HTML file - */ - public function loadHTML($file,$load = true) { - if ($load) { - if (file_exists($file)) { - $this->htmlData = file_get_contents($file); - } else { - $this->error("The HTML file you supplied doesn't seem to exist. Check the path."); - } - } else { - $this->htmlData = $file; - } - } - - /** - * Save the CSS rules that match between the given CSS file and the HTML file - * - * @return {String} the rules that match between the given CSS file and HTML file - */ - public function saveRules() { - - // make sure data exists to compare - if (($this->htmlData == "") || (count($this->ruleSets) == 0)) { - $this->error("This would work better if there was CSS or HTML data."); - } - - // set-up the selector DOM to compare - $this->dom = new SelectorDOM($this->htmlData); - - // iterate over the default rule sets and test them against the given mark-up - $statements = ""; - foreach ($this->ruleSets as $selector => $declarationBlock) { - $statements .= $this->buildRuleSet($selector,$declarationBlock); - } - - // iterate over the at-rules - foreach ($this->atRules as $atRule => $ruleSets) { - - // iterate over the rule sets in the at-rules and test them against the given mark-up - $atRuleSets = ""; - foreach ($ruleSets as $selector => $declarationBlock) { - $atRuleSets .= $this->buildRuleSet($selector,$declarationBlock,"\t"); - } - - if ($atRuleSets != "") { - - // only write-out the at-rule if it contains at least one rule set - $statements .= $atRule." {\n"; - $statements .= $atRuleSets."\n"; - $statements .= "}\n\n"; - - } else if ($atRule == "@font-face") { - - // if the at-rule is a @font-face write it out no matter what - foreach ($ruleSets as $selector => $ruleSet) { - $statements .= $atRule." {\n"; - $statements .= $ruleSet."\n"; - $statements .= "}\n\n"; - } - - } - } - - unset($this->dom); - - return $statements; - - } - - /** - * Compare the given selector(s) against the DOM. Return the rule set if it matches - * @param {String} the selector(s) to test against the xPath - * @param {String} the declaration block that goes with the selector - * @param {String} any indent characters that might need to be added to the final output - * - * @return {String} if the selector(s) matched return the entire rule set with matches - */ - protected function buildRuleSet($selector,$declarationBlock,$indent = "") { - - // trap the selectors that are found - $foundSelectors = array(); - - // a given selector may have multiple parts (e.g. h1, h2, h3 ) break it up so each can be tested. - $selectors = explode(",",$selector); - - // iterate over each selector - foreach ($selectors as $selector) { - - $selector = trim($selector); - - // save the original selector and strip off bad pseudo-classes for matching purposes - $selectorOrig = $selector; - $badPseudoClasses = array(":first-child",":last-child",":after",":before",":nth-of",":visited",":hover",":focus","::"); - foreach ($badPseudoClasses as $badPseudoClass) { - $pos = strpos($selector,$badPseudoClass); - if ($pos !== false) { - $selector = substr($selector,0,$pos-strlen($selector)); - break; - } - } - - // match the selector against the DOM. if result is found save the original selector format - if (count($this->dom->select($selector)) > 0) { - $foundSelectors[] = $selectorOrig; - } - } - - // if the given selectors matched against the DOM build the rule set - if (count($foundSelectors) > 0) { - - // combine selectors that share a rule set - $i = 0; - $selectorList = ""; - foreach ($foundSelectors as $selector) { - $selectorList .= ($i > 0) ? ", ".$selector : $selector; - $i++; - } - - // write out the rule set & return it - $text = $indent.$selectorList." { \n"; - $text .= str_replace($indent,$indent.$indent,$declarationBlock)."\n"; - $text .= $indent."}\n\n"; - return $text; - - } - - } - - /** - * Print the error message. Yes, I should be using exception handling but I'm being lazy for now - * @param {String} the message to spit out - */ - protected function error($msg) { - print $msg."\n"; - exit; - } - -} diff --git a/builder/lib/css-rule-saver/lib/php-selector/History.rdoc b/builder/lib/css-rule-saver/lib/php-selector/History.rdoc deleted file mode 100755 index 27ebf9014..000000000 --- a/builder/lib/css-rule-saver/lib/php-selector/History.rdoc +++ /dev/null @@ -1,20 +0,0 @@ - -=== 1.1.3 / 2009-07-17 - -* Added comma support - -=== 1.1.2 / 2009-07-17 - -* Supress annoying libxml warnings - -=== 1.1.1 / 2009-07-17 - -* Fixed attributes - -=== 1.1.0 / 2009-07-17 - -* Added SelectorDom - -=== 1.0.0 / 2009-07-17 - -* Initial Release \ No newline at end of file diff --git a/builder/lib/css-rule-saver/lib/php-selector/Readme.rdoc b/builder/lib/css-rule-saver/lib/php-selector/Readme.rdoc deleted file mode 100755 index e52f73232..000000000 --- a/builder/lib/css-rule-saver/lib/php-selector/Readme.rdoc +++ /dev/null @@ -1,78 +0,0 @@ -= PHP Selector - -Quick DOM query library I whipped up for an old -PHP data miner I had which needed more flexibility. - -Current supports most CSS3 selectors. - -Tested with php 5.4 - -== Examples - -Given the sample html: - - $html = << -

Article Name

-

Contents of article

- - - HTML; - -The following will return an array of elements: - - select_elements('div#article.large', $html); - select_elements('div > h2:contains(Article)', $html); - select_elements('div p + ul', $html); - select_elements('ul > li:first-child', $html); - select_elements('ul > li ~ li', $html); - select_elements('ul > li:last-child', $html); - select_elements('li a[href=#]', $html); - -== SelectorDOM - -Persistant object for element selection. - - $dom = new SelectorDOM($html); - $links = $dom->select('a'); - $list_links = $dom->select('ul li a'); - -== Contribution - -* Like it? use it? feel free to extend and add more CSS3 support, and - run test.selector.php - -== More Information - -* View the source :P - -== License - -(The MIT License) - -Copyright (c) 2008 - 2009 TJ Holowaychuk - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/builder/lib/css-rule-saver/lib/php-selector/selector.php b/builder/lib/css-rule-saver/lib/php-selector/selector.php deleted file mode 100755 index af9044363..000000000 --- a/builder/lib/css-rule-saver/lib/php-selector/selector.php +++ /dev/null @@ -1,176 +0,0 @@ - MIT Licensed - * - * Persitant object for selecting elements. - * - * $dom = new SelectorDOM($html); - * $links = $dom->select('a'); - * $list_links = $dom->select('ul li a'); - * - */ -class SelectorDOM { - - const VERSION = '1.1.3'; - - /** - * @var DOMXPath - */ - protected $xpath; - - /** - * Map of regexes to convert CSS selector to XPath - * - * @var array - */ - public static $regexMap = array( - '/\s*,\s*/' => '|descendant-or-self::', - '/:(button|submit|file|checkbox|radio|image|reset|text|password)/' => 'input[@type="\1"]', - '/\[(\w+)\]/' => '*[@\1]', # [id] - '/\[(\w+)=[\'"]?(.*?)[\'"]?\]/' => '[@\1="\2"]', # foo[id=foo] - '/^\[/' => '*[', # [id=foo] - '/([\w\-]+)\#([\w\-]+)/' => '\1[@id="\2"]', # div#foo - '/\#([\w\-]+)/' => '*[@id="\1"]', # #foo - '/([\w\-]+)\.([\w\-]+)/' => '\1[contains(concat(" ",@class," ")," \2 ")]', # div.foo - '/\.([\w\-]+)/' => '*[contains(concat(" ",@class," ")," \1 ")]', # .foo - '/([\w\-]+):first-child/' => '*/\1[position()=1]', - '/([\w\-]+):last-child/' => '*/\1[position()=last()]', - '/:first-child/' => '*/*[position()=1]', - '/:last-child/' => '*/*[position()=last()]', - '/([\w\-]+):nth-child\((\d+)\)/' => '*/\1[position()=\2]', - '/:nth-child\((\d+)\)/' => '*/*[position()=\1]', - '/([\w\-]+):contains\((.*?)\)/' => '\1[contains(string(.),"\2")]', - '/\s*>\s*/' => '/', # > - '/\s*~\s*/' => '/following-sibling::', # ~ - '/\s*\+\s*([\w\-]+)/' => '/following-sibling::\1[position()=1]', # + - '/\]\*/' => ']', - '/\]\/\*/' => ']', - ); - - /** - * Load $data into the object - * - * @param string|DOMDocument $data - * @param array $errors A by-ref capture for libxml error messages. - */ - public function __construct($data, &$errors = null) { - # Wrap this with libxml errors off - # this both sets the new value, and returns the previous. - $lib_xml_errors = libxml_use_internal_errors(true); - - if (is_a($data, 'DOMDocument')) { - $this->xpath = new DOMXpath($data); - } else { - $dom = new DOMDocument(); - $dom->loadHTML($data); - $this->xpath = new DOMXpath($dom); - } - - # Clear any errors and restore the original value - $errors = libxml_get_errors(); - libxml_clear_errors(); - libxml_use_internal_errors($lib_xml_errors); - } - - /** - * Select elements from the loaded HTML using the css $selector. - * When $as_array is true elements and their children will - * be converted to array's containing the following keys (defaults to true): - * - * - name : element name - * - text : element text - * - children : array of children elements - * - attributes : attributes array - * - * Otherwise regular DOMElement's will be returned. - * - * @param string $selector CSS Selector - * @param boolean $as_array Whether to return an array or DOMElement - */ - public function select($selector, $as_array = true) { - $elements = $this->xpath->evaluate(self::selectorToXpath($selector)); - return $as_array ? self::elementsToArray($elements) : $elements; - } - - /** - * This allows a static access to the class, in the same way as the - * `select_elements` function did. - * - * @see $this->select() - * @param string $html - * @param string $selector CSS Selector - */ - public static function selectElements($selector, $html, $as_array = true) { - $dom = new SelectorDOM($html); - return $dom->select($selector, $as_array); - } - - /** - * Convert $elements to an array. - * - * @param DOMNodeList $elements - */ - public function elementsToArray($elements) { - $array = array(); - for ($i = 0, $length = $elements->length; $i < $length; ++$i) { - if ($elements->item($i)->nodeType == XML_ELEMENT_NODE) { - array_push($array, self::elementToArray($elements->item($i))); - } - } - return $array; - } - - /** - * Convert $element to an array. - */ - public function elementToArray($element) { - $array = array( - 'name' => $element->nodeName, - 'attributes' => array(), - 'text' => $element->textContent, - 'children' => self::elementsToArray($element->childNodes), - ); - if ($element->attributes->length) { - foreach($element->attributes as $key => $attr) { - $array['attributes'][$key] = $attr->value; - } - } - return $array; - } - - /** - * Convert $selector into an XPath string. - */ - public static function selectorToXpath($selector) { - // remove spaces around operators - $selector = preg_replace('/\s*(>|~|\+|,)\s*/', '$1', $selector); - $selectors = preg_split("/\s+/", $selector); - // Process all regular expressions to convert selector to XPath - foreach ($selectors as &$selector) { - foreach (self::$regexMap as $regex => $replacement) { - $selector = preg_replace($regex, $replacement, $selector); - } - } - $selector = implode('/descendant::', $selectors); - $selector = 'descendant-or-self::' . $selector; - return $selector; - } - -} - -# -# Procedural components -# - -define('SELECTOR_VERSION', SelectorDOM::VERSION); - -/** - * Provides a procedural function to select use SelectorDOM::select() - * on some HTML. - */ -function select_elements($selector, $html, $as_array = true) { - return SelectorDOM::selectElements($selector, $html, $as_array); -} - diff --git a/builder/lib/css-rule-saver/lib/php-selector/test.selector.php b/builder/lib/css-rule-saver/lib/php-selector/test.selector.php deleted file mode 100755 index 00a65e07a..000000000 --- a/builder/lib/css-rule-saver/lib/php-selector/test.selector.php +++ /dev/null @@ -1,124 +0,0 @@ - bar', 'descendant-or-self::foo/bar'); -test('foo >bar', 'descendant-or-self::foo/bar'); -test('foo>bar', 'descendant-or-self::foo/bar'); -test('foo> bar', 'descendant-or-self::foo/bar'); -test('div#foo', 'descendant-or-self::div[@id="foo"]'); -test('#foo', 'descendant-or-self::*[@id="foo"]'); -test('div.foo', 'descendant-or-self::div[contains(concat(" ",@class," ")," foo ")]'); -test('.foo', 'descendant-or-self::*[contains(concat(" ",@class," ")," foo ")]'); -test('[id]', 'descendant-or-self::*[@id]'); -test('[id=bar]', 'descendant-or-self::*[@id="bar"]'); -test('foo[id=bar]', 'descendant-or-self::foo[@id="bar"]'); -test(':button', 'descendant-or-self::input[@type="button"]'); -test('textarea', 'descendant-or-self::textarea'); -test(':submit', 'descendant-or-self::input[@type="submit"]'); -test(':first-child', 'descendant-or-self::*/*[position()=1]'); -test('div:first-child', 'descendant-or-self::*/div[position()=1]'); -test(':last-child', 'descendant-or-self::*/*[position()=last()]'); -test('div:last-child', 'descendant-or-self::*/div[position()=last()]'); -test(':nth-child(2)', 'descendant-or-self::*/*[position()=2]'); -test('div:nth-child(2)', 'descendant-or-self::*/div[position()=2]'); -test('foo + bar', 'descendant-or-self::foo/following-sibling::bar[position()=1]'); -test('li:contains(Foo)', 'descendant-or-self::li[contains(string(.),"Foo")]'); -test('foo bar baz', 'descendant-or-self::foo/descendant::bar/descendant::baz'); -test('foo + bar + baz', 'descendant-or-self::foo/following-sibling::bar[position()=1]/following-sibling::baz[position()=1]'); -test('foo > bar > baz', 'descendant-or-self::foo/bar/baz'); -test('p ~ p ~ p', 'descendant-or-self::p/following-sibling::p/following-sibling::p'); -test('div#article p em', 'descendant-or-self::div[@id="article"]/descendant::p/descendant::em'); -test('div.foo:first-child', 'descendant-or-self::div[contains(concat(" ",@class," ")," foo ")][position()=1]'); -test('form#login > input[type=hidden]._method', 'descendant-or-self::form[@id="login"]/input[@type="hidden"][contains(concat(" ",@class," ")," _method ")]'); - -test_selector('*', 12); -test_selector('div', 1); -test_selector('div, p', 2); -test_selector('div , p', 2); -test_selector('div ,p', 2); -test_selector('div, p, ul li a', 3); -test_selector('div#article', 1); -test_selector('div#article.block', 1); -test_selector('div#article.large.block', 1); -test_selector('h2', 1); -test_selector('div h2', 1); -test_selector('div > h2', 1); -test_selector('ul li a', 1); -test_selector('ul > li > a', 1); -test_selector('a[href=#]', 1); -test_selector('a[href="#"]', 1); -test_selector('div[id="article"]', 1); -test_selector('h2:contains(Article)', 1); -test_selector('h2:contains(Article) + p', 1); -test_selector('h2:contains(Article) + p:contains(Contents)', 1); -test_selector('div p + ul', 1); -test_selector('li ~ li', 4); -test_selector('li ~ li ~ li', 3); -test_selector('li + li', 4); -test_selector('li + li + li', 3); -test_selector('li:first-child', 1); -test_selector('li:last-child', 1); -test_selector('li:contains(One):first-child', 1); -test_selector('li:nth-child(2)', 1); -test_selector('li:nth-child(3)', 1); -test_selector('li:nth-child(4)', 1); -test_selector('li:nth-child(6)', 0); -test_selector('.a', 2); - -$dom = new SelectorDom(get_test_html()); -print (count($dom->select('a')) == 1) - ? '.' - : 'SelectorDOM failed'; -print (count($dom->select('ul li a')) == 1) - ? '.' - : 'SelectorDOM failed'; - -$divs = $dom->select('div'); -print ($divs[0]['attributes']['id'] == 'article') - ? '.' - : 'Attributes failed'; - -print "\n"; - -function test_selector($selector, $count) { - $html = get_test_html(); - $actual = count(SelectorDOM::selectElements($selector, $html)); - print ($actual == $count) - ? '.' - : "\n '$selector' failed, expected $count but got $actual \n\n"; -} - -function test($selector, $expected) { - $actual = SelectorDOM::selectorToXpath($selector); - if ($web = 'cli' !== PHP_SAPI) { - echo '
';
-    }
-    assert($actual == $expected);
-    echo "\nExpected: $expected\n";
-    echo "Actual:   $actual\n";
-    echo str_repeat('-', 80)."\n";
-    if ($web) {
-        echo '
'; - } -} - -function get_test_html() { - return << -

Article Name

-

Contents of article

- - -HTML; -} diff --git a/composer.json b/composer.json new file mode 100644 index 000000000..7ba59af52 --- /dev/null +++ b/composer.json @@ -0,0 +1,24 @@ +{ + "repositories": [ + { + "type": "package", + "package": { + "name": "css-rule-saver", + "version": "dev", + "dist": { + "url": "https://github.com/dmolsen/css-rule-saver/archive/master.zip", + "type": "zip" + } + } + } + ], + "require": { + "mustache/mustache": "2.5.*", + "css-rule-saver": "dev" + }, + "autoload": { + "psr-0": { + "": "builder/lib/" + } + } +} \ No newline at end of file diff --git a/composer.lock b/composer.lock new file mode 100644 index 000000000..98522d8ba --- /dev/null +++ b/composer.lock @@ -0,0 +1,81 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file" + ], + "hash": "1b96d686deafb55d398862893cd1d393", + "packages": [ + { + "name": "css-rule-saver", + "version": "dev", + "dist": { + "type": "zip", + "url": "https://github.com/dmolsen/css-rule-saver/archive/master.zip", + "reference": null, + "shasum": null + }, + "type": "library" + }, + { + "name": "mustache/mustache", + "version": "v2.5.0", + "source": { + "type": "git", + "url": "https://github.com/bobthecow/mustache.php.git", + "reference": "dd528e765afcaaae20ce3bebdda3162456d93b47" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/bobthecow/mustache.php/zipball/dd528e765afcaaae20ce3bebdda3162456d93b47", + "reference": "dd528e765afcaaae20ce3bebdda3162456d93b47", + "shasum": "" + }, + "require": { + "php": ">=5.2.4" + }, + "require-dev": { + "phpunit/phpunit": "*" + }, + "type": "library", + "autoload": { + "psr-0": { + "Mustache": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Justin Hileman", + "email": "justin@justinhileman.info", + "homepage": "http://justinhileman.com" + } + ], + "description": "A Mustache implementation in PHP.", + "homepage": "https://github.com/bobthecow/mustache.php", + "keywords": [ + "mustache", + "templating" + ], + "time": "2013-12-14 20:57:43" + } + ], + "packages-dev": [ + + ], + "aliases": [ + + ], + "minimum-stability": "stable", + "stability-flags": { + "css-rule-saver": 20 + }, + "platform": [ + + ], + "platform-dev": [ + + ] +} From 490aa35d3754976247bde07828fc4d7c56f34ca1 Mon Sep 17 00:00:00 2001 From: Matt Wells Date: Mon, 6 Jan 2014 10:31:35 -0500 Subject: [PATCH 2/8] Configuration refactor -- builder.php loads it and handles issues -- Buildr.php, Watchr.php, Generatr.php expect a config array passed to their constructors --- builder/builder.php | 108 ++-- builder/lib/Buildr.php | 15 +- builder/lib/Generatr.php | 220 ++++----- builder/lib/Mustache/Loader/PatternLoader.php | 40 +- builder/lib/Watchr.php | 460 +++++++++--------- 5 files changed, 415 insertions(+), 428 deletions(-) diff --git a/builder/builder.php b/builder/builder.php index b040c0a3c..b9f80fb39 100644 --- a/builder/builder.php +++ b/builder/builder.php @@ -8,17 +8,17 @@ * * Usage: * - * php builder.php -g - * Iterates over the 'source' directories & files and generates the entire site a single time. - * It also cleans the 'public' directory. - * - * php builder.php -w - * Generates the site like the -g flag and then watches for changes in the 'source' directories & - * files. Will re-generate files if they've changed. + * php builder.php -g + * Iterates over the 'source' directories & files and generates the entire site a single time. + * It also cleans the 'public' directory. + * + * php builder.php -w + * Generates the site like the -g flag and then watches for changes in the 'source' directories & + * files. Will re-generate files if they've changed. * */ -require '../vendor/autoload.php'; +require __DIR__ . '/../vendor/autoload.php'; @@ -26,52 +26,50 @@ // make sure this script is being accessed from the command line -if (php_sapi_name() == 'cli') { - - $args = getopt("gwc"); - - if (isset($args["g"])) { - - // initiate the g (generate) switch - - // iterate over the source directory and generate the site - $g = new Generatr(); - - // check to see if CSS for patterns should be parsed & outputted - (isset($args["c"])) ? $g->generate(true) : $g->generate(); - - print "your site has been generated...\n"; - - } else if (isset($args["w"])) { - - // initiate the w (watch) switch - - // iterate over the source directory and generate the site - $g = new Generatr(); - $g->generate(); - print "your site has been generated...\n"; - - // watch the source directory and regenerate any changed files - $w = new Watchr(); - print "watching your site for changes...\n"; - $w->watch(); - - } else { - - // when in doubt write out the usage - print "\n"; - print "Usage:\n\n"; - print " php ".$_SERVER["PHP_SELF"]." -g\n"; - print " Iterates over the 'source' directories & files and generates the entire site a single time.\n"; - print " It also cleans the 'public' directory.\n\n"; - print " php ".$_SERVER["PHP_SELF"]." -w\n"; - print " Generates the site like the -g flag and then watches for changes in the 'source' directories &\n"; - print " files. Will re-generate files if they've changed.\n\n"; - - } - -} else { - - print "The builder script can only be run from the command line."; +if (php_sapi_name() !== 'cli') { + die('The builder script can only be run from the command line.'); +} + +$configLocation = __DIR__ . '/../config/config.ini'; +if (!file_exists($configLocation)) { + die('A configuration file is required. Look at config/config.ini.default for an example!'); } + +$config = parse_ini_file($configLocation); + +$args = getopt("gwc"); + +if (isset($args['g']) || isset($args['w'])) { + + // initiate the g (generate) switch + + // iterate over the source directory and generate the site + $g = new Generatr($config); + + echo "your site has been generated...\n"; + +} + +if (isset($args['w'])) { + // watch the source directory and regenerate any changed files + $w = new Watchr($config); + echo "watching your site for changes...\n"; + $w->watch(); + +} + + +if (!isset($args['w']) && !isset($args['g'])) { + + // when in doubt write out the usage + echo "\n"; + echo "Usage:\n\n"; + echo " php ".$_SERVER["PHP_SELF"]." -g\n"; + echo " Iterates over the 'source' directories & files and generates the entire site a single time.\n"; + echo " It also cleans the 'public' directory.\n\n"; + echo " php ".$_SERVER["PHP_SELF"]." -w\n"; + echo " Generates the site like the -g flag and then watches for changes in the 'source' directories &\n"; + echo " files. Will re-generate files if they've changed.\n\n"; + +} \ No newline at end of file diff --git a/builder/lib/Buildr.php b/builder/lib/Buildr.php index 862e4586e..800fba385 100644 --- a/builder/lib/Buildr.php +++ b/builder/lib/Buildr.php @@ -36,19 +36,8 @@ class Buildr { * When initializing the Builder class or the sub-classes make sure the base properties are configured * Also, create the config if it doesn't already exist */ - public function __construct() { - - // set-up the configuration options for patternlab - if (!($config = @parse_ini_file(__DIR__."/../../config/config.ini"))) { - // config.ini didn't exist so attempt to create it using the default file - if (!@copy(__DIR__."/../../config/config.ini.default", __DIR__."/../../config/config.ini")) { - print "Please make sure config.ini.default exists before trying to have Pattern Lab build the config.ini file automagically. Check permissions of config/."; - exit; - } else { - $config = parse_ini_file(__DIR__."/../../config/config.ini"); - } - } - + public function __construct($config=array()) { + // populate some standard variables out of the config foreach ($config as $key => $value) { diff --git a/builder/lib/Generatr.php b/builder/lib/Generatr.php index 70cb3b0a6..0176efc5c 100644 --- a/builder/lib/Generatr.php +++ b/builder/lib/Generatr.php @@ -12,114 +12,114 @@ */ class Generatr extends Buildr { - - /** - * Use the Builder __construct to gather the config variables - */ - public function __construct() { - - // construct the parent - parent::__construct(); - - } - - /** - * Pulls together a bunch of functions from builder.lib.php in an order that makes sense - * @param {Boolean} decide if CSS should be parsed and saved. performance hog. - */ - public function generate($enableCSS = false) { - - $timePL = true; // track how long it takes to generate a PL site - - if ($timePL) { - $mtime = microtime(); - $mtime = explode(" ",$mtime); - $mtime = $mtime[1] + $mtime[0]; - $starttime = $mtime; - } - - if ($enableCSS) { - - // enable CSS globally throughout PL - $this->enableCSS = true; - - // initialize CSS rule saver - $this->initializeCSSRuleSaver(); - - print "CSS generation enabled. This could take a few seconds...\n"; - - } - - - - // clean the public directory to remove old files - $this->cleanPublic(); - - // gather data - $this->gatherData(); - - // render out the patterns and move them to public/patterns - $this->generatePatterns(); - - // render out the index and style guide - $this->generateMainPages(); - - // iterate over the data files and regenerate the entire site if they've changed - $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__."/../../source/_data/"), RecursiveIteratorIterator::SELF_FIRST); - - // make sure dots are skipped - $objects->setFlags(FilesystemIterator::SKIP_DOTS); - - foreach($objects as $name => $object) { - - $fileName = str_replace(__DIR__."/../../source/_data".DIRECTORY_SEPARATOR,"",$name); - if (($fileName[0] != "_") && $object->isFile()) { - $this->moveStaticFile("_data/".$fileName,"","_data","data"); - } - - } - - // iterate over all of the other files in the source directory - $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__."/../../source/"), RecursiveIteratorIterator::SELF_FIRST); - - // make sure dots are skipped - $objects->setFlags(FilesystemIterator::SKIP_DOTS); - - foreach($objects as $name => $object) { - - // clean-up the file name and make sure it's not one of the pattern lab files or to be ignored - $fileName = str_replace(__DIR__."/../../source".DIRECTORY_SEPARATOR,"",$name); - if (($fileName[0] != "_") && (!in_array($object->getExtension(),$this->ie)) && (!in_array($object->getFilename(),$this->id))) { - - // catch directories that have the ignored dir in their path - $ignoreDir = $this->ignoreDir($fileName); - - // check to see if it's a new directory - if (!$ignoreDir && $object->isDir() && !is_dir(__DIR__."/../../public/".$fileName)) { - mkdir(__DIR__."/../../public/".$fileName); - } - - // check to see if it's a new file or a file that has changed - if (!$ignoreDir && $object->isFile() && (!file_exists(__DIR__."/../../public/".$fileName))) { - $this->moveStaticFile($fileName); - } - - } - - } - - // update the change time so the auto-reload will fire (doesn't work for the index and style guide) - $this->updateChangeTime(); - - if ($timePL) { - $mtime = microtime(); - $mtime = explode(" ",$mtime); - $mtime = $mtime[1] + $mtime[0]; - $endtime = $mtime; - $totaltime = ($endtime - $starttime); - print "PL site generation took ".$totaltime." seconds...\n"; - } - - } - + + /** + * Use the Builder __construct to gather the config variables + */ + public function __construct($config=array()) { + + // construct the parent + parent::__construct($config); + + } + + /** + * Pulls together a bunch of functions from builder.lib.php in an order that makes sense + * @param {Boolean} decide if CSS should be parsed and saved. performance hog. + */ + public function generate($enableCSS = false) { + + $timePL = true; // track how long it takes to generate a PL site + + if ($timePL) { + $mtime = microtime(); + $mtime = explode(" ",$mtime); + $mtime = $mtime[1] + $mtime[0]; + $starttime = $mtime; + } + + if ($enableCSS) { + + // enable CSS globally throughout PL + $this->enableCSS = true; + + // initialize CSS rule saver + $this->initializeCSSRuleSaver(); + + print "CSS generation enabled. This could take a few seconds...\n"; + + } + + + + // clean the public directory to remove old files + $this->cleanPublic(); + + // gather data + $this->gatherData(); + + // render out the patterns and move them to public/patterns + $this->generatePatterns(); + + // render out the index and style guide + $this->generateMainPages(); + + // iterate over the data files and regenerate the entire site if they've changed + $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__."/../../source/_data/"), RecursiveIteratorIterator::SELF_FIRST); + + // make sure dots are skipped + $objects->setFlags(FilesystemIterator::SKIP_DOTS); + + foreach($objects as $name => $object) { + + $fileName = str_replace(__DIR__."/../../source/_data".DIRECTORY_SEPARATOR,"",$name); + if (($fileName[0] != "_") && $object->isFile()) { + $this->moveStaticFile("_data/".$fileName,"","_data","data"); + } + + } + + // iterate over all of the other files in the source directory + $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__."/../../source/"), RecursiveIteratorIterator::SELF_FIRST); + + // make sure dots are skipped + $objects->setFlags(FilesystemIterator::SKIP_DOTS); + + foreach($objects as $name => $object) { + + // clean-up the file name and make sure it's not one of the pattern lab files or to be ignored + $fileName = str_replace(__DIR__."/../../source".DIRECTORY_SEPARATOR,"",$name); + if (($fileName[0] != "_") && (!in_array($object->getExtension(),$this->ie)) && (!in_array($object->getFilename(),$this->id))) { + + // catch directories that have the ignored dir in their path + $ignoreDir = $this->ignoreDir($fileName); + + // check to see if it's a new directory + if (!$ignoreDir && $object->isDir() && !is_dir(__DIR__."/../../public/".$fileName)) { + mkdir(__DIR__."/../../public/".$fileName); + } + + // check to see if it's a new file or a file that has changed + if (!$ignoreDir && $object->isFile() && (!file_exists(__DIR__."/../../public/".$fileName))) { + $this->moveStaticFile($fileName); + } + + } + + } + + // update the change time so the auto-reload will fire (doesn't work for the index and style guide) + $this->updateChangeTime(); + + if ($timePL) { + $mtime = microtime(); + $mtime = explode(" ",$mtime); + $mtime = $mtime[1] + $mtime[0]; + $endtime = $mtime; + $totaltime = ($endtime - $starttime); + print "PL site generation took ".$totaltime." seconds...\n"; + } + + } + } \ No newline at end of file diff --git a/builder/lib/Mustache/Loader/PatternLoader.php b/builder/lib/Mustache/Loader/PatternLoader.php index c552806a9..a4256693d 100644 --- a/builder/lib/Mustache/Loader/PatternLoader.php +++ b/builder/lib/Mustache/Loader/PatternLoader.php @@ -154,24 +154,24 @@ protected function getFileName($name) } private function getPatternInfo($name) { - - $patternBits = explode("-",$name); - - $i = 1; - $k = 2; - $c = count($patternBits); - $patternType = $patternBits[0]; - while (!isset($this->patternPaths[$patternType]) && ($i < $c)) { - $patternType .= "-".$patternBits[$i]; - $i++; - $k++; - } - - $patternBits = explode("-",$name,$k); - $pattern = $patternBits[count($patternBits)-1]; - - return array($patternType, $pattern); - - } - + + $patternBits = explode("-",$name); + + $i = 1; + $k = 2; + $c = count($patternBits); + $patternType = $patternBits[0]; + while (!isset($this->patternPaths[$patternType]) && ($i < $c)) { + $patternType .= "-".$patternBits[$i]; + $i++; + $k++; + } + + $patternBits = explode("-",$name,$k); + $pattern = $patternBits[count($patternBits)-1]; + + return array($patternType, $pattern); + + } + } diff --git a/builder/lib/Watchr.php b/builder/lib/Watchr.php index 43c0f7b68..d415fc2fc 100644 --- a/builder/lib/Watchr.php +++ b/builder/lib/Watchr.php @@ -15,234 +15,234 @@ */ class Watchr extends Buildr { - - /** - * Use the Builder __construct to gather the config variables - */ - public function __construct() { - - // construct the parent - parent::__construct(); - - } - - /** - * Watch the source/ directory for any changes to existing files. Will run forever if given the chance. - */ - public function watch() { - - $c = false; // track that one loop through the pattern file listing has completed - $o = new stdClass(); // create an object to hold the properties - $cp = new StdClass(); // create an object to hold a clone of $o - - $o->patterns = new stdClass(); - - // run forever - while (true) { - - // clone the patterns so they can be checked in case something gets deleted - $cp = clone $o->patterns; - - // iterate over the patterns & related data and regenerate the entire site if they've changed - $patternObjects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__."/../../source/_patterns/"), RecursiveIteratorIterator::SELF_FIRST); - - // make sure dots are skipped - $patternObjects->setFlags(FilesystemIterator::SKIP_DOTS); - - foreach($patternObjects as $name => $object) { - - // clean-up the file name and make sure it's not one of the pattern lab files or to be ignored - $fileName = str_replace(__DIR__."/../../source/_patterns".DIRECTORY_SEPARATOR,"",$name); - $fileNameClean = str_replace(DIRECTORY_SEPARATOR."_",DIRECTORY_SEPARATOR,$fileName); - - if ($object->isFile() && (($object->getExtension() == "mustache") || ($object->getExtension() == "json"))) { - - // make sure this isn't a hidden pattern - $patternParts = explode(DIRECTORY_SEPARATOR,$fileName); - $pattern = isset($patternParts[2]) ? $patternParts[2] : $patternParts[1]; - if ($pattern[0] != "_") { - - // make sure the pattern still exists in source just in case it's been deleted during the iteration - if (file_exists($name)) { - - $mt = $object->getMTime(); - if (isset($o->patterns->$fileName) && ($o->patterns->$fileName != $mt)) { - $o->patterns->$fileName = $mt; - $this->updateSite($fileName,"changed"); - } else if (!isset($o->patterns->$fileName) && $c) { - $o->patterns->$fileName = $mt; - $this->updateSite($fileName,"added"); - if ($object->getExtension() == "mustache") { - $this->patternPaths[$patternParts[0]][$pattern] = str_replace(".mustache","",$fileName); - } - } else if (!isset($o->patterns->$fileName)) { - $o->patterns->$fileName = $mt; - } - - if ($c && isset($o->patterns->$fileName)) { - unset($cp->$fileName); - } - - } else { - - // the file was removed during the iteration so remove references to the item - unset($o->patterns->$fileName); - unset($cp->$fileName); - unset($this->patternPaths[$patternParts[0]][$pattern]); - $this->updateSite($fileName,"removed"); - - } - - } elseif (isset($o->patterns->$fileNameClean)) { - - // the file was hidden so remove references to the item - $patternParts = explode(DIRECTORY_SEPARATOR,$fileNameClean); - $pattern = isset($patternParts[2]) ? $patternParts[2] : $patternParts[1]; - - unset($o->patterns->$fileNameClean); - unset($cp->$fileNameClean); - unset($this->patternPaths[$patternParts[0]][$pattern]); - $this->updateSite($fileNameClean,"hidden"); - - } - - } - - } - - // make sure old entries are deleted - // will throw "pattern not found" errors if an entire directory is removed at once but that shouldn't be a big deal - if ($c) { - - foreach($cp as $fileName => $mt) { - - unset($o->patterns->$fileName); - $patternParts = explode(DIRECTORY_SEPARATOR,$fileName); - $pattern = isset($patternParts[2]) ? $patternParts[2] : $patternParts[1]; - - unset($this->patternPaths[$patternParts[0]][$pattern]); - $this->updateSite($fileName,"removed"); - - } - - } - - // iterate over the data files and regenerate the entire site if they've changed - $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__."/../../source/_data/"), RecursiveIteratorIterator::SELF_FIRST); - - // make sure dots are skipped - $objects->setFlags(FilesystemIterator::SKIP_DOTS); - - foreach($objects as $name => $object) { - - $fileName = str_replace(__DIR__."/../../source/_data".DIRECTORY_SEPARATOR,"",$name); - $mt = $object->getMTime(); - - if (!isset($o->$fileName)) { - $o->$fileName = $mt; - if (($fileName[0] != "_") && $object->isFile()) { - $this->moveStaticFile("_data/".$fileName,"","_data","data"); - } - } else if ($o->$fileName != $mt) { - $o->$fileName = $mt; - $this->updateSite($fileName,"changed"); - if (($fileName[0] != "_") && $object->isFile()) { - $this->moveStaticFile("_data/".$fileName,"","_data","data"); - } - } - - } - - // iterate over all of the other files in the source directory and move them if their modified time has changed - $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__."/../../source/"), RecursiveIteratorIterator::SELF_FIRST); - - // make sure dots are skipped - $objects->setFlags(FilesystemIterator::SKIP_DOTS); - - foreach($objects as $name => $object) { - - // clean-up the file name and make sure it's not one of the pattern lab files or to be ignored - $fileName = str_replace(__DIR__."/../../source".DIRECTORY_SEPARATOR,"",$name); - if (($fileName[0] != "_") && (!in_array($object->getExtension(),$this->ie)) && (!in_array($object->getFilename(),$this->id))) { - - // catch directories that have the ignored dir in their path - $ignoreDir = $this->ignoreDir($fileName); - - // check to see if it's a new directory - if (!$ignoreDir && $object->isDir() && !isset($o->$fileName) && !is_dir(__DIR__."/../../public/".$fileName)) { - mkdir(__DIR__."/../../public/".$fileName); - $o->$fileName = "dir created"; // placeholder - print $fileName."/ directory was created...\n"; - } - - // check to see if it's a new file or a file that has changed - if (file_exists($name)) { - - $mt = $object->getMTime(); - if (!$ignoreDir && $object->isFile() && !isset($o->$fileName) && !file_exists(__DIR__."/../../public/".$fileName)) { - $o->$fileName = $mt; - $this->moveStaticFile($fileName,"added"); - if ($object->getExtension() == "css") { - $this->updateSite($fileName,"changed",0); // make sure the site is updated for MQ reasons - } - } else if (!$ignoreDir && $object->isFile() && isset($o->$fileName) && ($o->$fileName != $mt)) { - $o->$fileName = $mt; - $this->moveStaticFile($fileName,"changed"); - if ($object->getExtension() == "css") { - $this->updateSite($fileName,"changed",0); // make sure the site is updated for MQ reasons - } - } else if (!isset($o->fileName)) { - $o->$fileName = $mt; - } - - } else { - unset($o->$fileName); - } - - } - - } - - $c = true; - - // taking out the garbage. basically killing mustache after each run. - unset($this->mpl); - unset($this->msf); - if (gc_enabled()) gc_collect_cycles(); - - // pause for .05 seconds to give the CPU a rest - usleep(50000); - - } - - } - - /** - * Updates the Pattern Lab Website and prints the appropriate message - * @param {String} file name to included in the message - * @param {String} a switch for decided which message isn't printed - * - * @return {String} the final message - */ - private function updateSite($fileName,$message,$verbose = true) { - $this->gatherData(); - $this->gatherPatternPaths(); - $this->gatherNavItems(); - $this->generatePatterns(); - $this->generateViewAllPages(); - $this->updateChangeTime(); - $this->generateMainPages(); - if ($verbose) { - if ($message == "added") { - print $fileName." was added to Pattern Lab. Reload the website to see this change in the navigation...\n"; - } elseif ($message == "removed") { - print $fileName." was removed from Pattern Lab. Reload the website to see this change reflected in the navigation...\n"; - } elseif ($message == "hidden") { - print $fileName." was hidden from Pattern Lab. Reload the website to see this change reflected in the navigation...\n"; - } else { - print $fileName." changed...\n"; - } - } - } - + + /** + * Use the Builder __construct to gather the config variables + */ + public function __construct($config=array()) { + + // construct the parent + parent::__construct($config); + + } + + /** + * Watch the source/ directory for any changes to existing files. Will run forever if given the chance. + */ + public function watch() { + + $c = false; // track that one loop through the pattern file listing has completed + $o = new stdClass(); // create an object to hold the properties + $cp = new StdClass(); // create an object to hold a clone of $o + + $o->patterns = new stdClass(); + + // run forever + while (true) { + + // clone the patterns so they can be checked in case something gets deleted + $cp = clone $o->patterns; + + // iterate over the patterns & related data and regenerate the entire site if they've changed + $patternObjects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__."/../../source/_patterns/"), RecursiveIteratorIterator::SELF_FIRST); + + // make sure dots are skipped + $patternObjects->setFlags(FilesystemIterator::SKIP_DOTS); + + foreach($patternObjects as $name => $object) { + + // clean-up the file name and make sure it's not one of the pattern lab files or to be ignored + $fileName = str_replace(__DIR__."/../../source/_patterns".DIRECTORY_SEPARATOR,"",$name); + $fileNameClean = str_replace(DIRECTORY_SEPARATOR."_",DIRECTORY_SEPARATOR,$fileName); + + if ($object->isFile() && (($object->getExtension() == "mustache") || ($object->getExtension() == "json"))) { + + // make sure this isn't a hidden pattern + $patternParts = explode(DIRECTORY_SEPARATOR,$fileName); + $pattern = isset($patternParts[2]) ? $patternParts[2] : $patternParts[1]; + if ($pattern[0] != "_") { + + // make sure the pattern still exists in source just in case it's been deleted during the iteration + if (file_exists($name)) { + + $mt = $object->getMTime(); + if (isset($o->patterns->$fileName) && ($o->patterns->$fileName != $mt)) { + $o->patterns->$fileName = $mt; + $this->updateSite($fileName,"changed"); + } else if (!isset($o->patterns->$fileName) && $c) { + $o->patterns->$fileName = $mt; + $this->updateSite($fileName,"added"); + if ($object->getExtension() == "mustache") { + $this->patternPaths[$patternParts[0]][$pattern] = str_replace(".mustache","",$fileName); + } + } else if (!isset($o->patterns->$fileName)) { + $o->patterns->$fileName = $mt; + } + + if ($c && isset($o->patterns->$fileName)) { + unset($cp->$fileName); + } + + } else { + + // the file was removed during the iteration so remove references to the item + unset($o->patterns->$fileName); + unset($cp->$fileName); + unset($this->patternPaths[$patternParts[0]][$pattern]); + $this->updateSite($fileName,"removed"); + + } + + } elseif (isset($o->patterns->$fileNameClean)) { + + // the file was hidden so remove references to the item + $patternParts = explode(DIRECTORY_SEPARATOR,$fileNameClean); + $pattern = isset($patternParts[2]) ? $patternParts[2] : $patternParts[1]; + + unset($o->patterns->$fileNameClean); + unset($cp->$fileNameClean); + unset($this->patternPaths[$patternParts[0]][$pattern]); + $this->updateSite($fileNameClean,"hidden"); + + } + + } + + } + + // make sure old entries are deleted + // will throw "pattern not found" errors if an entire directory is removed at once but that shouldn't be a big deal + if ($c) { + + foreach($cp as $fileName => $mt) { + + unset($o->patterns->$fileName); + $patternParts = explode(DIRECTORY_SEPARATOR,$fileName); + $pattern = isset($patternParts[2]) ? $patternParts[2] : $patternParts[1]; + + unset($this->patternPaths[$patternParts[0]][$pattern]); + $this->updateSite($fileName,"removed"); + + } + + } + + // iterate over the data files and regenerate the entire site if they've changed + $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__."/../../source/_data/"), RecursiveIteratorIterator::SELF_FIRST); + + // make sure dots are skipped + $objects->setFlags(FilesystemIterator::SKIP_DOTS); + + foreach($objects as $name => $object) { + + $fileName = str_replace(__DIR__."/../../source/_data".DIRECTORY_SEPARATOR,"",$name); + $mt = $object->getMTime(); + + if (!isset($o->$fileName)) { + $o->$fileName = $mt; + if (($fileName[0] != "_") && $object->isFile()) { + $this->moveStaticFile("_data/".$fileName,"","_data","data"); + } + } else if ($o->$fileName != $mt) { + $o->$fileName = $mt; + $this->updateSite($fileName,"changed"); + if (($fileName[0] != "_") && $object->isFile()) { + $this->moveStaticFile("_data/".$fileName,"","_data","data"); + } + } + + } + + // iterate over all of the other files in the source directory and move them if their modified time has changed + $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__."/../../source/"), RecursiveIteratorIterator::SELF_FIRST); + + // make sure dots are skipped + $objects->setFlags(FilesystemIterator::SKIP_DOTS); + + foreach($objects as $name => $object) { + + // clean-up the file name and make sure it's not one of the pattern lab files or to be ignored + $fileName = str_replace(__DIR__."/../../source".DIRECTORY_SEPARATOR,"",$name); + if (($fileName[0] != "_") && (!in_array($object->getExtension(),$this->ie)) && (!in_array($object->getFilename(),$this->id))) { + + // catch directories that have the ignored dir in their path + $ignoreDir = $this->ignoreDir($fileName); + + // check to see if it's a new directory + if (!$ignoreDir && $object->isDir() && !isset($o->$fileName) && !is_dir(__DIR__."/../../public/".$fileName)) { + mkdir(__DIR__."/../../public/".$fileName); + $o->$fileName = "dir created"; // placeholder + print $fileName."/ directory was created...\n"; + } + + // check to see if it's a new file or a file that has changed + if (file_exists($name)) { + + $mt = $object->getMTime(); + if (!$ignoreDir && $object->isFile() && !isset($o->$fileName) && !file_exists(__DIR__."/../../public/".$fileName)) { + $o->$fileName = $mt; + $this->moveStaticFile($fileName,"added"); + if ($object->getExtension() == "css") { + $this->updateSite($fileName,"changed",0); // make sure the site is updated for MQ reasons + } + } else if (!$ignoreDir && $object->isFile() && isset($o->$fileName) && ($o->$fileName != $mt)) { + $o->$fileName = $mt; + $this->moveStaticFile($fileName,"changed"); + if ($object->getExtension() == "css") { + $this->updateSite($fileName,"changed",0); // make sure the site is updated for MQ reasons + } + } else if (!isset($o->fileName)) { + $o->$fileName = $mt; + } + + } else { + unset($o->$fileName); + } + + } + + } + + $c = true; + + // taking out the garbage. basically killing mustache after each run. + unset($this->mpl); + unset($this->msf); + if (gc_enabled()) gc_collect_cycles(); + + // pause for .05 seconds to give the CPU a rest + usleep(50000); + + } + + } + + /** + * Updates the Pattern Lab Website and prints the appropriate message + * @param {String} file name to included in the message + * @param {String} a switch for decided which message isn't printed + * + * @return {String} the final message + */ + private function updateSite($fileName,$message,$verbose = true) { + $this->gatherData(); + $this->gatherPatternPaths(); + $this->gatherNavItems(); + $this->generatePatterns(); + $this->generateViewAllPages(); + $this->updateChangeTime(); + $this->generateMainPages(); + if ($verbose) { + if ($message == "added") { + print $fileName." was added to Pattern Lab. Reload the website to see this change in the navigation...\n"; + } elseif ($message == "removed") { + print $fileName." was removed from Pattern Lab. Reload the website to see this change reflected in the navigation...\n"; + } elseif ($message == "hidden") { + print $fileName." was hidden from Pattern Lab. Reload the website to see this change reflected in the navigation...\n"; + } else { + print $fileName." changed...\n"; + } + } + } + } From 8044bdd7b9803cb8a7f8e9ae04d3289a20bf41d3 Mon Sep 17 00:00:00 2001 From: Matt Griffin Date: Thu, 5 Dec 2013 16:21:06 +0000 Subject: [PATCH 3/8] Fixed a missing curly bracket in static.scss On line 142 of static.scss there is a missing "}" bracket causing an error if you compile the scss. --- public/styleguide/css/static.scss | 1 + 1 file changed, 1 insertion(+) diff --git a/public/styleguide/css/static.scss b/public/styleguide/css/static.scss index 1fbb1bc27..a22d5d744 100644 --- a/public/styleguide/css/static.scss +++ b/public/styleguide/css/static.scss @@ -139,6 +139,7 @@ input[type=search] { padding: 0 1em; margin: 0 auto; overflow: hidden; + } } /*End Footer*/ From 560babe8d749bd52f8ff8e3a6ca63a6dce509a59 Mon Sep 17 00:00:00 2001 From: Matt Griffin Date: Thu, 5 Dec 2013 17:04:53 +0000 Subject: [PATCH 4/8] Fixing no scrolling problem on iOS, iPad etc On line 545 added "-webkit-overflow-scrolling: touch; overflow: scroll;" to enable scrolling on iOS devices. see http://johanbrook.com/browsers/native-momentum-scrolling-ios-5/ --- public/styleguide/css/styleguide.scss | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/public/styleguide/css/styleguide.scss b/public/styleguide/css/styleguide.scss index 80178908c..5b4cd6d07 100644 --- a/public/styleguide/css/styleguide.scss +++ b/public/styleguide/css/styleguide.scss @@ -528,6 +528,8 @@ $animate-quick: 0.2s; height: 100%; text-align: center; margin: 0 auto; + -webkit-overflow-scrolling: touch; + overflow: scroll; &.hay-mode { -webkit-transition: all 40s linear; @@ -864,4 +866,4 @@ $animate-quick: 0.2s; } .icon-eye:before { content: "\e001"; -} \ No newline at end of file +} From ea1694438758bff6598fc67e0cdfbad2818b0e0b Mon Sep 17 00:00:00 2001 From: Dave Olsen Date: Thu, 5 Dec 2013 16:38:24 -0500 Subject: [PATCH 5/8] updating what's fixed in v0.6.2 --- CHANGELOG | 4 ++++ builder/builder.php | 2 +- builder/lib/builder.lib.php | 2 +- builder/lib/generator.lib.php | 2 +- builder/lib/watcher.lib.php | 2 +- 5 files changed, 8 insertions(+), 4 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index 68a8afe7e..373a0135a 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,9 @@ THIS CHANGELOG IS AN ATTEMPT TO DOCUMENT CHANGES TO THIS PROJECT. +PL-v0.6.2 + - FIX: a few small sass and styling tweaks + - THX: thanks to @griffinartworks for the sass and styling fixes + PL-v0.6.1 - FIX: fixed the height of the HTML pre element on the pattern detail view - ADD: added in support for viewing the generated CSS on the pattern detail view diff --git a/builder/builder.php b/builder/builder.php index b00f1d871..92565d6ef 100644 --- a/builder/builder.php +++ b/builder/builder.php @@ -1,7 +1,7 @@ Date: Mon, 6 Jan 2014 11:40:50 -0500 Subject: [PATCH 6/8] Throw exceptions; don't die(). Also, generate() disappeared. That's weird. --- builder/builder.php | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/builder/builder.php b/builder/builder.php index 5c3627d82..41217645a 100644 --- a/builder/builder.php +++ b/builder/builder.php @@ -27,17 +27,21 @@ // make sure this script is being accessed from the command line if (php_sapi_name() !== 'cli') { - die('The builder script can only be run from the command line.'); + throw new Exception('The builder script can only be run from the command line.'); } $configLocation = __DIR__ . '/../config/config.ini'; if (!file_exists($configLocation)) { - die('A configuration file is required. Look at config/config.ini.default for an example!'); + throw new Exception('A configuration file is required. Look at config/config.ini.default for an example!'); } $config = parse_ini_file($configLocation); +if (!$config) { + throw new Exception("The supplied configuration file at {$configLocation} is invalid. Please see config.ini.default in the same directory for an example"); +} + $args = getopt("gwc"); if (isset($args['g']) || isset($args['w'])) { @@ -49,6 +53,8 @@ echo "your site has been generated...\n"; + $g->generate(); + } if (isset($args['w'])) { From 28de7dd17d3234ce67a5f6a1ad9a961e02a1b88f Mon Sep 17 00:00:00 2001 From: Matt Wells Date: Mon, 6 Jan 2014 13:31:51 -0500 Subject: [PATCH 7/8] File structure refactor -- Move generation files out of builder/lib/ and into lib/ -- specify unlimited time in command line --- builder/builder.php | 2 ++ composer.json | 3 ++- composer.lock | 8 ++++---- {builder/lib => lib}/Buildr.php | 0 {builder/lib => lib}/Generatr.php | 0 {builder/lib => lib}/Mustache/Loader/PatternLoader.php | 0 lib/PatternLab/Commands/GenerateCommand.php | 3 +++ {builder/lib => lib}/Watchr.php | 0 8 files changed, 11 insertions(+), 5 deletions(-) rename {builder/lib => lib}/Buildr.php (100%) rename {builder/lib => lib}/Generatr.php (100%) rename {builder/lib => lib}/Mustache/Loader/PatternLoader.php (100%) create mode 100644 lib/PatternLab/Commands/GenerateCommand.php rename {builder/lib => lib}/Watchr.php (100%) diff --git a/builder/builder.php b/builder/builder.php index 41217645a..127ec63ed 100644 --- a/builder/builder.php +++ b/builder/builder.php @@ -18,6 +18,8 @@ * */ +set_time_limit(0); + require __DIR__ . '/../vendor/autoload.php'; diff --git a/composer.json b/composer.json index 7ba59af52..bb010250e 100644 --- a/composer.json +++ b/composer.json @@ -13,12 +13,13 @@ } ], "require": { + "php": ">=5.3.3", "mustache/mustache": "2.5.*", "css-rule-saver": "dev" }, "autoload": { "psr-0": { - "": "builder/lib/" + "": "lib/" } } } \ No newline at end of file diff --git a/composer.lock b/composer.lock index 98522d8ba..031e0e0b2 100644 --- a/composer.lock +++ b/composer.lock @@ -3,7 +3,7 @@ "This file locks the dependencies of your project to a known state", "Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file" ], - "hash": "1b96d686deafb55d398862893cd1d393", + "hash": "9e19fe8d947955060acacb99d292b9f5", "packages": [ { "name": "css-rule-saver", @@ -72,9 +72,9 @@ "stability-flags": { "css-rule-saver": 20 }, - "platform": [ - - ], + "platform": { + "php": ">=5.3.3" + }, "platform-dev": [ ] diff --git a/builder/lib/Buildr.php b/lib/Buildr.php similarity index 100% rename from builder/lib/Buildr.php rename to lib/Buildr.php diff --git a/builder/lib/Generatr.php b/lib/Generatr.php similarity index 100% rename from builder/lib/Generatr.php rename to lib/Generatr.php diff --git a/builder/lib/Mustache/Loader/PatternLoader.php b/lib/Mustache/Loader/PatternLoader.php similarity index 100% rename from builder/lib/Mustache/Loader/PatternLoader.php rename to lib/Mustache/Loader/PatternLoader.php diff --git a/lib/PatternLab/Commands/GenerateCommand.php b/lib/PatternLab/Commands/GenerateCommand.php new file mode 100644 index 000000000..6fe7d98fb --- /dev/null +++ b/lib/PatternLab/Commands/GenerateCommand.php @@ -0,0 +1,3 @@ + Date: Wed, 8 Jan 2014 11:12:30 -0500 Subject: [PATCH 8/8] Switching to Symfony console application --- bin/patternlab.php | 24 ++++++++ composer.json | 3 +- composer.lock | 55 ++++++++++++++++++- lib/{Buildr.php => PatternLab/Builder.php} | 39 +++++++------ lib/PatternLab/Commands/GenerateCommand.php | 3 - lib/PatternLab/Console/Application.php | 43 +++++++++++++++ .../Console/Commands/BuildCommand.php | 33 +++++++++++ .../Console/Commands/WatchCommand.php | 32 +++++++++++ .../Generator.php} | 11 ++-- lib/{Watchr.php => PatternLab/Watcher.php} | 21 +++---- 10 files changed, 227 insertions(+), 37 deletions(-) create mode 100644 bin/patternlab.php rename lib/{Buildr.php => PatternLab/Builder.php} (96%) delete mode 100644 lib/PatternLab/Commands/GenerateCommand.php create mode 100644 lib/PatternLab/Console/Application.php create mode 100644 lib/PatternLab/Console/Commands/BuildCommand.php create mode 100644 lib/PatternLab/Console/Commands/WatchCommand.php rename lib/{Generatr.php => PatternLab/Generator.php} (89%) rename lib/{Watchr.php => PatternLab/Watcher.php} (92%) diff --git a/bin/patternlab.php b/bin/patternlab.php new file mode 100644 index 000000000..6ff5b83ea --- /dev/null +++ b/bin/patternlab.php @@ -0,0 +1,24 @@ +#!/usr/bin/env php +setConfig($config); +$app->run(); diff --git a/composer.json b/composer.json index bb010250e..49aa4ae63 100644 --- a/composer.json +++ b/composer.json @@ -15,7 +15,8 @@ "require": { "php": ">=5.3.3", "mustache/mustache": "2.5.*", - "css-rule-saver": "dev" + "css-rule-saver": "dev", + "symfony/console": "2.4.x" }, "autoload": { "psr-0": { diff --git a/composer.lock b/composer.lock index 031e0e0b2..c48cc24b4 100644 --- a/composer.lock +++ b/composer.lock @@ -3,7 +3,7 @@ "This file locks the dependencies of your project to a known state", "Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file" ], - "hash": "9e19fe8d947955060acacb99d292b9f5", + "hash": "e4179577288cc5f1b27dd7cf8135bc19", "packages": [ { "name": "css-rule-saver", @@ -60,6 +60,59 @@ "templating" ], "time": "2013-12-14 20:57:43" + }, + { + "name": "symfony/console", + "version": "v2.4.1", + "target-dir": "Symfony/Component/Console", + "source": { + "type": "git", + "url": "https://github.com/symfony/Console.git", + "reference": "4c1ed2ff514bd85ee186eebb010ccbdeeab05af7" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/Console/zipball/4c1ed2ff514bd85ee186eebb010ccbdeeab05af7", + "reference": "4c1ed2ff514bd85ee186eebb010ccbdeeab05af7", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "require-dev": { + "symfony/event-dispatcher": "~2.1" + }, + "suggest": { + "symfony/event-dispatcher": "" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.4-dev" + } + }, + "autoload": { + "psr-0": { + "Symfony\\Component\\Console\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "http://symfony.com/contributors" + } + ], + "description": "Symfony Console Component", + "homepage": "http://symfony.com", + "time": "2014-01-01 08:14:50" } ], "packages-dev": [ diff --git a/lib/Buildr.php b/lib/PatternLab/Builder.php similarity index 96% rename from lib/Buildr.php rename to lib/PatternLab/Builder.php index 800fba385..879e961ed 100644 --- a/lib/Buildr.php +++ b/lib/PatternLab/Builder.php @@ -1,5 +1,10 @@ $key = $values; } else { $this->$key = $value; @@ -72,9 +77,9 @@ public function __construct($config=array()) { * @return {Object} an instance of the Mustache engine */ protected function loadMustachePatternLoaderInstance() { - $this->mpl = new Mustache_Engine(array( - "loader" => new Mustache_Loader_PatternLoader(__DIR__.$this->sp,array("patternPaths" => $this->patternPaths)), - "partials_loader" => new Mustache_Loader_PatternLoader(__DIR__.$this->sp,array("patternPaths" => $this->patternPaths)) + $this->mpl = new Engine(array( + "loader" => new PatternLoader(__DIR__.$this->sp,array("patternPaths" => $this->patternPaths)), + "partials_loader" => new PatternLoader(__DIR__.$this->sp,array("patternPaths" => $this->patternPaths)) )); } @@ -84,9 +89,9 @@ protected function loadMustachePatternLoaderInstance() { * @return {Object} an instance of the Mustache engine */ protected function loadMustacheFileSystemLoaderInstance() { - $this->mfs = new Mustache_Engine(array( - "loader" => new Mustache_Loader_FilesystemLoader(__DIR__."/../../source/_patternlab-files/"), - "partials_loader" => new Mustache_Loader_FilesystemLoader(__DIR__."/../../source/_patternlab-files/partials/") + $this->mfs = new Engine(array( + "loader" => new FilesystemLoader(__DIR__."/../../source/_patternlab-files/"), + "partials_loader" => new FilesystemLoader(__DIR__."/../../source/_patternlab-files/partials/") )); } @@ -128,7 +133,7 @@ protected function generateMainPages() { $sd = $this->gatherPartials(); // sort partials by patternLink - usort($sd['partials'], "Buildr::sortPartials"); + usort($sd['partials'], "PatternLab\Builder::sortPartials"); // render the "view all" pages $this->generateViewAllPages(); @@ -289,13 +294,13 @@ protected function gatherData() { $k = 1; $c = count($listItems)+1; - $this->d->listItems = new stdClass(); + $this->d->listItems = new \stdClass(); while ($k < $c) { shuffle($listItems); $itemsArray = array(); - $this->d->listItems->$numbers[$k-1] = new stdClass(); + $this->d->listItems->$numbers[$k-1] = new \stdClass(); while ($i < $k) { $itemsArray[] = $listItems[$i]; @@ -312,7 +317,7 @@ protected function gatherData() { } // add the link names for easy reference, makes 'link' a reserved word - $this->d->link = new stdClass(); + $this->d->link = new \stdClass(); foreach($this->patternPaths as $patternTypeName => $patterns) { foreach($patterns as $pattern => $path) { @@ -325,7 +330,7 @@ protected function gatherData() { // add pattern specific data so it can override when a pattern (not partial!) is rendered // makes 'patternSpecific' a reserved word - $this->d->patternSpecific = new stdClass(); + $this->d->patternSpecific = new \stdClass(); foreach($this->patternTypes as $patternType) { // $this->d->patternSpecific["pattern-name-that-matches-render.mustache"] = array of data; @@ -800,10 +805,10 @@ protected function updateChangeTime() { protected function cleanPublic() { // find all of the patterns in public/. sort by the children first - $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__."/../../public/patterns/"), RecursiveIteratorIterator::CHILD_FIRST); + $objects = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator(__DIR__."/../../public/patterns/"), \RecursiveIteratorIterator::CHILD_FIRST); // make sure dots are skipped - $objects->setFlags(FilesystemIterator::SKIP_DOTS); + $objects->setFlags(\FilesystemIterator::SKIP_DOTS); // for each file figure out what to do with it foreach($objects as $name => $object) { @@ -845,10 +850,10 @@ protected function cleanPublic() { // for the remaining dirs in public delete them and their files foreach ($publicDirs as $dir) { - $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::CHILD_FIRST); + $objects = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir), \RecursiveIteratorIterator::CHILD_FIRST); // make sure dots are skipped - $objects->setFlags(FilesystemIterator::SKIP_DOTS); + $objects->setFlags(\FilesystemIterator::SKIP_DOTS); foreach($objects as $name => $object) { diff --git a/lib/PatternLab/Commands/GenerateCommand.php b/lib/PatternLab/Commands/GenerateCommand.php deleted file mode 100644 index 6fe7d98fb..000000000 --- a/lib/PatternLab/Commands/GenerateCommand.php +++ /dev/null @@ -1,3 +0,0 @@ -addCommands(array( + new Commands\BuildCommand, + new Commands\WatchCommand + )); + } + protected function getDefaultInputDefinition() + { + return new InputDefinition(array( + new InputArgument('command', InputArgument::REQUIRED, 'The command to execute'), + + new InputOption('--help', '-h', InputOption::VALUE_NONE, 'Display this help message.'), + new InputOption('--version', '-V', InputOption::VALUE_NONE, 'Display this application version.'), + )); + } + + public function setConfig($config=array()) + { + $this->config = $config; + } + + public function getConfig() + { + return $this->config; + } +} \ No newline at end of file diff --git a/lib/PatternLab/Console/Commands/BuildCommand.php b/lib/PatternLab/Console/Commands/BuildCommand.php new file mode 100644 index 000000000..38a37860d --- /dev/null +++ b/lib/PatternLab/Console/Commands/BuildCommand.php @@ -0,0 +1,33 @@ +setName('build') + ->setDescription('Build your Pattern Lab') + ->setHelp('No options'); + } + protected function execute(InputInterface $input, OutputInterface $output) + { + + $generator = new Generator($this->getApplication()->getConfig()); + + $output->writeln('generating your site'); + + $generator->generate(); + + } +} \ No newline at end of file diff --git a/lib/PatternLab/Console/Commands/WatchCommand.php b/lib/PatternLab/Console/Commands/WatchCommand.php new file mode 100644 index 000000000..e257f5b1b --- /dev/null +++ b/lib/PatternLab/Console/Commands/WatchCommand.php @@ -0,0 +1,32 @@ +setName('watch') + ->setDescription('Rebuild your Pattern Lab when a change is detected') + ->setHelp('No options'); + } + + protected function execute(InputInterface $input, OutputInterface $output) + { + parent::execute($input, $output); + + $watcher = new Watcher($this->getApplication()->getConfig()); + $output->writeln('now watching for changes...'); + $watcher->watch(); + + } +} \ No newline at end of file diff --git a/lib/Generatr.php b/lib/PatternLab/Generator.php similarity index 89% rename from lib/Generatr.php rename to lib/PatternLab/Generator.php index 0176efc5c..eb2023cad 100644 --- a/lib/Generatr.php +++ b/lib/PatternLab/Generator.php @@ -1,5 +1,6 @@ generateMainPages(); // iterate over the data files and regenerate the entire site if they've changed - $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__."/../../source/_data/"), RecursiveIteratorIterator::SELF_FIRST); + $objects = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator(__DIR__."/../../source/_data/"), \RecursiveIteratorIterator::SELF_FIRST); // make sure dots are skipped - $objects->setFlags(FilesystemIterator::SKIP_DOTS); + $objects->setFlags(\FilesystemIterator::SKIP_DOTS); foreach($objects as $name => $object) { @@ -80,10 +81,10 @@ public function generate($enableCSS = false) { } // iterate over all of the other files in the source directory - $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__."/../../source/"), RecursiveIteratorIterator::SELF_FIRST); + $objects = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator(__DIR__."/../../source/"), \RecursiveIteratorIterator::SELF_FIRST); // make sure dots are skipped - $objects->setFlags(FilesystemIterator::SKIP_DOTS); + $objects->setFlags(\FilesystemIterator::SKIP_DOTS); foreach($objects as $name => $object) { diff --git a/lib/Watchr.php b/lib/PatternLab/Watcher.php similarity index 92% rename from lib/Watchr.php rename to lib/PatternLab/Watcher.php index d415fc2fc..099f707ae 100644 --- a/lib/Watchr.php +++ b/lib/PatternLab/Watcher.php @@ -1,5 +1,6 @@ patterns = new stdClass(); + $o->patterns = new \stdClass(); // run forever while (true) { @@ -44,10 +45,10 @@ public function watch() { $cp = clone $o->patterns; // iterate over the patterns & related data and regenerate the entire site if they've changed - $patternObjects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__."/../../source/_patterns/"), RecursiveIteratorIterator::SELF_FIRST); + $patternObjects = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator(__DIR__."/../../source/_patterns/"), \RecursiveIteratorIterator::SELF_FIRST); // make sure dots are skipped - $patternObjects->setFlags(FilesystemIterator::SKIP_DOTS); + $patternObjects->setFlags(\FilesystemIterator::SKIP_DOTS); foreach($patternObjects as $name => $object) { @@ -128,10 +129,10 @@ public function watch() { } // iterate over the data files and regenerate the entire site if they've changed - $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__."/../../source/_data/"), RecursiveIteratorIterator::SELF_FIRST); + $objects = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator(__DIR__."/../../source/_data/"), \RecursiveIteratorIterator::SELF_FIRST); // make sure dots are skipped - $objects->setFlags(FilesystemIterator::SKIP_DOTS); + $objects->setFlags(\FilesystemIterator::SKIP_DOTS); foreach($objects as $name => $object) { @@ -154,10 +155,10 @@ public function watch() { } // iterate over all of the other files in the source directory and move them if their modified time has changed - $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__."/../../source/"), RecursiveIteratorIterator::SELF_FIRST); + $objects = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator(__DIR__."/../../source/"), \RecursiveIteratorIterator::SELF_FIRST); // make sure dots are skipped - $objects->setFlags(FilesystemIterator::SKIP_DOTS); + $objects->setFlags(\FilesystemIterator::SKIP_DOTS); foreach($objects as $name => $object) {