Skip to content

Commit

Permalink
minor twigphp#1403 Refactor namespace/shortname parsing into own meth…
Browse files Browse the repository at this point in the history
…od (anlutro)

This PR was merged into the 1.15-dev branch.

Discussion
----------

Refactor namespace/shortname parsing into own method

I've written a custom file loader in order for the namespace syntax to match across different resource loading classes. To achieve this I have to replace the loadTemplate method, which includes a lot of logic. While this logic may not be likely to change anytime soon, I'd feel better if the namespace parsing was extracted into its own method so I can replace just that bit.

Commits
-------

9dd3bb8 Refactor namespace/shortname parsing into own method
  • Loading branch information
fabpot committed May 25, 2014
2 parents fce3b8a + 9dd3bb8 commit e6156e2
Showing 1 changed file with 17 additions and 10 deletions.
27 changes: 17 additions & 10 deletions lib/Twig/Loader/Filesystem.php
Expand Up @@ -176,16 +176,7 @@ protected function findTemplate($name)

$this->validateName($name);

$namespace = self::MAIN_NAMESPACE;
$shortname = $name;
if (isset($name[0]) && '@' == $name[0]) {
if (false === $pos = strpos($name, '/')) {
throw new Twig_Error_Loader(sprintf('Malformed namespaced template name "%s" (expecting "@namespace/template_name").', $name));
}

$namespace = substr($name, 1, $pos - 1);
$shortname = substr($name, $pos + 1);
}
list($namespace, $shortname) = $this->parseName($name);

if (!isset($this->paths[$namespace])) {
throw new Twig_Error_Loader(sprintf('There are no registered paths for namespace "%s".', $namespace));
Expand All @@ -200,6 +191,22 @@ protected function findTemplate($name)
throw new Twig_Error_Loader(sprintf('Unable to find template "%s" (looked into: %s).', $name, implode(', ', $this->paths[$namespace])));
}

protected function parseName($name, $default = self::MAIN_NAMESPACE)
{
if (isset($name[0]) && '@' == $name[0]) {
if (false === $pos = strpos($name, '/')) {
throw new Twig_Error_Loader(sprintf('Malformed namespaced template name "%s" (expecting "@namespace/template_name").', $name));
}

$namespace = substr($name, 1, $pos - 1);
$shortname = substr($name, $pos + 1);

return array($namespace, $shortname);
}

return array($default, $name);
}

protected function normalizeName($name)
{
return preg_replace('#/{2,}#', '/', strtr((string) $name, '\\', '/'));
Expand Down

0 comments on commit e6156e2

Please sign in to comment.