1<?php
2
3/*
4 * This file is part of Mustache.php.
5 *
6 * (c) 2010-2017 Justin Hileman
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12/**
13 * Mustache class autoloader.
14 */
15class Mustache_Autoloader
16{
17    private $baseDir;
18
19    /**
20     * An array where the key is the baseDir and the key is an instance of this
21     * class.
22     *
23     * @var array
24     */
25    private static $instances;
26
27    /**
28     * Autoloader constructor.
29     *
30     * @param string $baseDir Mustache library base directory (default: dirname(__FILE__).'/..')
31     */
32    public function __construct($baseDir = null)
33    {
34        if ($baseDir === null) {
35            $baseDir = dirname(__FILE__) . '/..';
36        }
37
38        // realpath doesn't always work, for example, with stream URIs
39        $realDir = realpath($baseDir);
40        if (is_dir($realDir)) {
41            $this->baseDir = $realDir;
42        } else {
43            $this->baseDir = $baseDir;
44        }
45    }
46
47    /**
48     * Register a new instance as an SPL autoloader.
49     *
50     * @param string $baseDir Mustache library base directory (default: dirname(__FILE__).'/..')
51     *
52     * @return Mustache_Autoloader Registered Autoloader instance
53     */
54    public static function register($baseDir = null)
55    {
56        $key = $baseDir ? $baseDir : 0;
57
58        if (!isset(self::$instances[$key])) {
59            self::$instances[$key] = new self($baseDir);
60        }
61
62        $loader = self::$instances[$key];
63        spl_autoload_register(array($loader, 'autoload'));
64
65        return $loader;
66    }
67
68    /**
69     * Autoload Mustache classes.
70     *
71     * @param string $class
72     */
73    public function autoload($class)
74    {
75        if ($class[0] === '\\') {
76            $class = substr($class, 1);
77        }
78
79        if (strpos($class, 'Mustache') !== 0) {
80            return;
81        }
82
83        $file = sprintf('%s/%s.php', $this->baseDir, str_replace('_', '/', $class));
84        if (is_file($file)) {
85            require $file;
86        }
87    }
88}
89