More code merged from ship-simu
[mailer.git] / inc / loader / class_ClassLoader.php
1 <?php
2 /**
3  * This class loads class include files with a specific prefix and suffix
4  *
5  * @author              Roland Haeder <webmaster@ship-simu.org>
6  * @version             0.0.0
7  * @copyright   Copyright(c) 2007, 2008 Roland Haeder, this is free software
8  * @license             GNU GPL 3.0 or any newer version
9  * @link                http://www.ship-simu.org
10  *
11  * This program is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation, either version 3 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program. If not, see <http://www.gnu.org/licenses/>.
23  *
24  * ----------------------------------
25  * 1.2
26  *  - ClassLoader rewritten to PHP SPL's own RecursiveIteratorIterator class
27  * 1.1
28  *  - loadClasses rewritten to fix some notices
29  * 1.0
30  *  - Initial release
31  * ----------------------------------
32  */
33 class ClassLoader {
34         /**
35          * Instance of this class
36          */
37         private static $selfInstance = null;
38
39         /**
40          * Configuration array
41          */
42         private $cfg = array();
43
44         /**
45          * Array with all classes
46          */
47         private $classes = array();
48
49         /**
50          * List of loaded classes
51          */
52         private $loadedClasses = array();
53
54         /**
55          * Suffix with extension for all class files
56          */
57         private $prefix = "class_";
58
59         /**
60          * Suffix with extension for all class files
61          */
62         private $suffix = ".php";
63
64         /**
65          * Length of the suffix. Will be overwritten later.
66          */
67         private $suffixLen = 0;
68
69         /**
70          * Length of the prefix. Will be overwritten later.
71          */
72         private $prefixLen = 0;
73
74         /**
75          * A list for directory names (no leading/trailing slashes!) which not be scanned by the path scanner
76          * @see scanLocalPath
77          */
78         private $ignoreList = array();
79
80         /**
81          * Debug this class loader? (true = yes, false = no)
82          */
83         private $debug = false;
84
85         /**
86          * Wether the file list is cached or not
87          */
88         private $listCached = false;
89
90         /**
91          * Wethe class content has been cached
92          */
93         private $classesCached = false;
94
95         /**
96          * Filename for the list cache
97          */
98         private $listCacheFQFN = "";
99
100         /**
101          * Cache for class content
102          */
103         private $classCacheFQFN = "";
104
105         /**
106          * The *public* constructor
107          *
108          * @param               $cfgInstance            Configuration class instance
109          * @return      void
110          */
111         public function __construct (FrameworkConfiguration $cfgInstance) {
112                 // Set configuration instance
113                 $this->cfgInstance = $cfgInstance;
114
115                 // Construct the FQFN for the cache
116                 if (!defined('DEVELOPER')) {
117                         $this->listCacheFQFN  = PATH . $this->cfgInstance->readConfig('local_db_path') . "list-" . $this->cfgInstance->readConfig('app_name') . ".cache";
118                         $this->classCacheFQFN = PATH . $this->cfgInstance->readConfig('local_db_path') . "class-" . $this->cfgInstance->readConfig('app_name') . ".cache";
119                 } // END - if
120
121                 // Set suffix and prefix from configuration
122                 $this->suffix = $cfgInstance->readConfig('class_suffix');
123                 $this->prefix = $cfgInstance->readConfig('class_prefix');
124
125                 // Estimate length of prefix and suffix for substr() function (cache)
126                 $this->suffixLen = strlen($this->suffix);
127                 $this->prefixLen = strlen($this->prefix);
128
129                 // Set own instance
130                 self::$selfInstance = $this;
131
132                 // Skip here if no dev-mode
133                 if (defined('DEVELOPER')) return;
134
135                 // IS the cache there?
136                 if (file_exists($this->listCacheFQFN)) {
137                         // Get content
138                         $cacheContent = file_get_contents($this->listCacheFQFN);
139
140                         // And convert it
141                         $this->classes = unserialize($cacheContent);
142
143                         // List has been restored from cache!
144                         $this->listCached = true;
145                 } // END - if
146
147                 // Does the class cache exist?
148                 if (file_exists($this->classCacheFQFN)) {
149                         // Then include it
150                         require($this->classCacheFQFN);
151
152                         // Mark the class cache as loaded
153                         $this->classesCached = true;
154                 } // END - if
155         }
156
157         /**
158          * The destructor makes it sure all caches got flushed
159          *
160          * @return      void
161          */
162         public function __destruct () {
163                 // Skip here if dev-mode
164                 if (defined('DEVELOPER')) return;
165
166                 // Skip here if already cached
167                 if ($this->listCached === false) {
168                         // Writes the cache file of our list away
169                         $cacheContent = serialize($this->classes);
170                         file_put_contents($this->listCacheFQFN, $cacheContent);
171                 } // END - if
172
173                 // Skip here if already cached
174                 if ($this->classesCached === false) {
175                         // Generate a full-cache of all classes
176                         $cacheContent = "";
177                         foreach ($this->loadedClasses as $fqfn) {
178                                 // Load the file
179                                 $cacheContent .= file_get_contents($fqfn);
180                         } // END - foreach
181
182                         // And write it away
183                         file_put_contents($this->classCacheFQFN, $cacheContent);
184                 } // END - if
185         }
186
187         /**
188          * Getter for an instance of this class
189          *
190          * @return      $selfInstance           An instance of this class
191          */
192         public final static function getInstance () {
193                 // Is the instance there?
194                 if (is_null(self::$selfInstance)) {
195                         // Get a new one
196                         self::$selfInstance = new ClassLoader(FrameworkConfiguration::getInstance());
197                 } // END - if
198
199                 // Return the instance
200                 return self::$selfInstance;
201         }
202
203         /**
204          * Scans recursively a local path for class files which must have a prefix and a suffix as given by $this->suffix and $this->prefix
205          *
206          * @param               $basePath               The relative base path to PATH constant for all classes
207          * @param               $ignoreList     An optional list (array or string) of directory names which shall be ignored
208          * @return      void
209          */
210         public function loadClasses ($basePath, $ignoreList = array() ) {
211                 // Is a list has been restored from cache, don't read it again
212                 if ($this->listCached === true) {
213                         // Abort here
214                         return;
215                 }
216
217                 // Convert string to array
218                 if (!is_array($ignoreList)) $ignoreList = array($ignoreList);
219
220                 // Directories which our class loader ignores by default while
221                 // deep-scanning the directory structure. See scanLocalPath() for
222                 // details.
223                 $ignoreList[] = ".";
224                 $ignoreList[] = "..";
225                 $ignoreList[] = ".htaccess";
226                 $ignoreList[] = ".svn";
227
228                 // Keep it in class for later usage
229                 $this->ignoreList = $ignoreList;
230
231                 // Set base directory which holds all our classes, we should use an
232                 // absolute path here so is_dir(), is_file() and so on will always
233                 // find the correct files and dirs.
234                 $basePath2 = realpath($basePath);
235
236                 // If the basePath is false it is invalid
237                 if ($basePath2 === false) {
238                         // TODO: Do not die here.
239                         debug_print_backtrace();
240                         die("Cannot read {$basePath} !");
241                 } else {
242                         // Set base path
243                         $basePath = $basePath2;
244                 }
245
246                 // Get a new iterator
247                 //* DEBUG: */ echo "<strong>Base path: {$basePath}</strong><br />\n";
248                 $iterator = new RecursiveDirectoryIterator($basePath);
249                 $recursive = new RecursiveIteratorIterator($iterator);
250                 foreach ($recursive as $entry) {
251                         // Get filename from iterator
252                         $fileName = $entry->getFileName();
253
254                         // Is this file wanted?
255                         //* DEBUG: */ echo "FOUND:{$fileName}<br />\n";
256                         if ((!in_array($fileName, $this->ignoreList)) && (substr($fileName, 0, $this->prefixLen) == $this->prefix) && (substr($fileName, -$this->suffixLen, $this->suffixLen) == $this->suffix)) {
257                                 // Get the FQFN and add it to our class list
258                                 $fqfn = $entry->getRealPath();
259                                 //* DEBUG: */ echo "ADD: {$fileName}<br />\n";
260                                 $this->classes[$fileName] = $fqfn;
261                         } // END - if
262                 } // END - foreach
263         }
264
265         /**
266          * Load extra config files
267          *
268          * @return      void
269          */
270         public function loadExtraConfigs () {
271                 // Backup old prefix
272                 $oldPrefix = $this->prefix;
273
274                 // Set new prefix (temporary!)
275                 $this->prefix = "config-";
276                 $this->prefixLen = strlen($this->prefix);
277
278                 // Set base directory
279                 $basePath = sprintf("%sinc/config/", PATH);
280
281                 // Load all classes from the config directory
282                 $this->loadClasses($basePath);
283
284                 // Include these extra configs now
285                 $this->includeExtraConfigs();
286
287                 // Set the prefix back
288                 $this->prefix = $oldPrefix;
289                 $this->prefixLen = strlen($this->prefix);
290
291         }
292
293         /**
294          * Tries to find the given class in our list. This method ignores silently
295          * missing classes or interfaces. So if you use class_exists() this method
296          * does not interrupt your program.
297          *
298          * @param       $className      The class we shall load
299          * @return      void
300          */
301         public function includeClass ($className) {
302                 // Create a name with prefix and suffix
303                 $fileName = $this->prefix . $className . $this->suffix;
304
305                 // Now look it up in our index
306                 if (isset($this->classes[$fileName])) {
307                         // File is found so load it only once
308                         require($this->classes[$fileName]);
309
310                         // Developer mode excludes caching (better debugging)
311                         if (!defined('DEVELOPER')) {
312                                 // Mark this class as loaded
313                                 $this->loadedClasses[] = $this->classes[$fileName];
314
315                                 // Reset cache
316                                 $this->classesCached = false;
317                         } // END - if
318                 } // END - if
319         }
320
321         /**
322          * Includes all extra config files
323          *
324          * @return      void
325          */
326         private function includeExtraConfigs () {
327                 // Run through all class names (should not be much)
328                 foreach ($this->classes as $fileName=>$fqfn) {
329                         // Is this a config?
330                         if (substr($fileName, 0, $this->prefixLen) == $this->prefix) {
331                                 // Then include it
332                                 require($fqfn);
333
334                                 // Remove it from the list
335                                 unset($this->classes[$fileName]);
336                         } // END - if
337                 } // END - foreach
338         }
339 }
340
341 // [EOF]
342 ?>