1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
<?php
/*
* This file is part of the ICanBoogie package.
*
* (c) Olivier Laviale <olivier.laviale@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ICanBoogie\Render;
/**
* Support functions for template resolvers.
*/
trait TemplateResolverTrait
{
/**
* Resolves path tries.
*
* The method resolves a try path collection from a collection of roots, template name, and
* extension collection.
*
* @param array $paths Template directories paths.
* @param string $name Template name.
* @param array $extensions Supported extensions.
*
* @return array A collection of candidate template pathnames.
*/
protected function resolve_tries(array $paths, $name, array $extensions)
{
$extension = pathinfo($name, PATHINFO_EXTENSION);
if ($extension && in_array('.' . $extension, $extensions))
{
$name = substr($name, 0, -strlen($extension) - 1);
}
$tries = [];
$dirname = dirname($name);
$basename = basename($name);
foreach ($paths as $path)
{
$parent_dir = basename(dirname($path));
foreach ($extensions as $extension)
{
$filename = $name;
if ($dirname && $dirname == $parent_dir)
{
$filename = $basename;
}
$filename = $filename . $extension;
$pathname = $path . $filename;
$tries[] = $pathname;
}
}
return $tries;
}
/**
* Resolves a template path.
*
* The method returns the pathname of the first file matching the path collection. The tried
* paths are collected in `$tried`.
*
* @param array $tries Pathname collection, as returned by {@link resolve_tries()}.
* @param array $tried Tried pathname collection.
*
* @return string|null
*/
protected function resolve_path(array $tries, &$tried)
{
foreach ($tries as $pathname)
{
$tried[] = $pathname;
if (file_exists($pathname))
{
return $pathname;
}
}
return null;
}
}