Loader.php 7.14 KB
Newer Older
Jordi Boggiano's avatar
Jordi Boggiano committed
1
2
<?php
/**
3
 * Copyright (c) 2013-2017
Jordi Boggiano's avatar
Jordi Boggiano committed
4
 *
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 * @category  Library
 * @package   Dwoo
 * @author    Jordi Boggiano <j.boggiano@seld.be>
 * @author    David Sanchez <david38sanchez@gmail.com>
 * @copyright 2008-2013 Jordi Boggiano
 * @copyright 2013-2017 David Sanchez
 * @license   http://dwoo.org/LICENSE LGPLv3
 * @version   1.4.0
 * @date      2017-03-16
 * @link      http://dwoo.org/
 */

namespace Dwoo;

/**
 * Handles plugin loading and caching of plugins names/paths relationships.
Jordi Boggiano's avatar
Jordi Boggiano committed
21
22
23
 * This software is provided 'as-is', without any express or implied warranty.
 * In no event will the authors be held liable for any damages arising from the use of this software.
 */
24
class Loader implements ILoader
Jordi Boggiano's avatar
Jordi Boggiano committed
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
    /**
     * Stores the plugin directories.
     *
     * @see addDirectory
     * @var array
     */
    protected $paths = array();

    /**
     * Stores the plugins names/paths relationships
     * don't edit this on your own, use addDirectory.
     *
     * @see addDirectory
     * @var array
     */
    protected $classPath = array();

    /**
     * Path where class paths cache files are written.
     *
     * @var string
     */
    protected $cacheDir;

    /**
     * Path where builtin plugins are stored.
     *
     * @var string
     */
    protected $corePluginDir;

    /**
     * Loader constructor.
     *
     * @param $cacheDir
     */
    public function __construct($cacheDir)
    {
        $this->corePluginDir = __DIR__ . DIRECTORY_SEPARATOR . 'Plugins';
        $this->cacheDir      = rtrim($cacheDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;

        // include class paths or rebuild paths if the cache file isn't there
        $cacheFile = $this->cacheDir . 'classpath.cache.d' . Core::RELEASE_TAG . '.php';

        $chachedClassPath = null;

        if (file_exists($cacheFile)) {

74
            $chachedClassPath = @unserialize(file_get_contents($cacheFile));
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182

            if (is_array($chachedClassPath)) {
                $this->classPath = $chachedClassPath + $this->classPath;
            }
        }

        if (!is_array($chachedClassPath)) {
            $this->rebuildClassPathCache($this->corePluginDir, $cacheFile);
        }
    }

    /**
     * Rebuilds class paths, scans the given directory recursively and saves all paths in the given file.
     *
     * @param string         $path      the plugin path to scan
     * @param string|boolean $cacheFile the file where to store the plugin paths cache, it will be overwritten
     *
     * @throws Exception
     */
    protected function rebuildClassPathCache($path, $cacheFile)
    {
        $tmp = array();
        if ($cacheFile !== false) {
            $tmp             = $this->classPath;
            $this->classPath = array();
        }

        // iterates over all files/folders
        foreach (new \DirectoryIterator($path) as $fileInfo) {
            if (!$fileInfo->isDot()) {
                if ($fileInfo->isDir()) {
                    $this->rebuildClassPathCache($fileInfo->getPathname(), false);
                } else {
                    $this->classPath[$fileInfo->getBasename('.php')] = $fileInfo->getPathname();
                }
            }
        }

        // save in file if it's the first call (not recursed)
        if ($cacheFile !== false) {
            if (!file_put_contents($cacheFile, serialize($this->classPath), LOCK_EX)) {
                throw new Exception('Could not write into ' . $cacheFile . ', either because the folder is not there (create it) or because of the chmod configuration (please ensure this directory is writable by php), alternatively you can change the directory used with $dwoo->setCompileDir() or provide a custom loader object with $dwoo->setLoader()');
            }
            $this->classPath += $tmp;
        }
    }

    /**
     * Loads a plugin file.
     *
     * @param string $class       the plugin name, without the `Plugin` prefix
     * @param bool   $forceRehash if true, the class path caches will be rebuilt if the plugin is not found, in case it
     *                            has just been added, defaults to true
     *
     * @throws Exception
     */
    public function loadPlugin($class, $forceRehash = true)
    {
        /**
         * An unknown class was requested (maybe newly added) or the
         * include failed so we rebuild the cache. include() will fail
         * with an uncatchable error if the file doesn't exist, which
         * usually means that the cache is stale and must be rebuilt,
         * so we check for that before trying to include() the plugin.
         */
        if ((!isset($this->classPath[$class]) || !is_readable($this->classPath[$class])) || (!isset
                ($this->classPath[$class . 'Compile']) || !is_readable($this->classPath[$class . 'Compile']))) {
            if ($forceRehash) {
                $this->rebuildClassPathCache($this->corePluginDir, $this->cacheDir . 'classpath.cache.d' .
                    Core::RELEASE_TAG . '.php');
                foreach ($this->paths as $path => $file) {
                    $this->rebuildClassPathCache($path, $file);
                }
                if (isset($this->classPath[$class])) {
                    include_once $this->classPath[$class];
                } elseif (isset($this->classPath[$class . 'Compile'])) {
                    include_once $this->classPath[$class . 'Compile'];
                } else {
                    throw new Exception('Plugin "' . $class . '" can not be found, maybe you forgot to bind it if it\'s a custom plugin ?', E_USER_NOTICE);
                }
            } else {
                throw new Exception('Plugin "' . $class . '" can not be found, maybe you forgot to bind it if it\'s a custom plugin ?', E_USER_NOTICE);
            }
        }
    }

    /**
     * Adds a plugin directory, the plugins found in the new plugin directory
     * will take precedence over the other directories (including the default
     * dwoo plugin directory), you can use this for example to override plugins
     * in a specific directory for a specific application while keeping all your
     * usual plugins in the same place for all applications.
     * TOCOM don't forget that php functions overrides are not rehashed so you
     * need to clear the classpath caches by hand when adding those.
     *
     * @param string $pluginDirectory the plugin path to scan
     *
     * @throws Exception
     */
    public function addDirectory($pluginDirectory)
    {
        $pluginDir = realpath($pluginDirectory);
        if (!$pluginDir) {
            throw new Exception('Plugin directory does not exist or can not be read : ' . $pluginDirectory);
        }
        $cacheFile = $this->cacheDir . 'classpath-' . substr(strtr($pluginDir, '/\\:' . PATH_SEPARATOR, '----'),
                strlen($pluginDir) > 80 ? - 80 : 0) . '.d' . Core::RELEASE_TAG . '.php';
        $this->paths[$pluginDir] = $cacheFile;
183
184
185

        $chachedClassPath = null;

186
        if (file_exists($cacheFile)) {
187
188
189
190
191
            $chachedClassPath = @unserialize(file_get_contents($cacheFile));
        }

        if (is_array($chachedClassPath)) {
            $this->classPath = $chachedClassPath + $this->classPath;
192
193
194
195
        } else {
            $this->rebuildClassPathCache($pluginDir, $cacheFile);
        }
    }
Jordi Boggiano's avatar
Jordi Boggiano committed
196
}