ae5eb6fe08c8acf4f896ee09eead5550a74f3a06
[core.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, 2009 - 2011 Core Developer Team
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.3
26  *  - Constructor is now empty and factory method 'createClassLoader' is created
27  *  - renamed loadClasses to scanClassPath
28  *  - Added initLoader()
29  * 1.2
30  *  - ClassLoader rewritten to PHP SPL's own RecursiveIteratorIterator class
31  * 1.1
32  *  - loadClasses rewritten to fix some notices
33  * 1.0
34  *  - Initial release
35  * ----------------------------------
36  */
37 class ClassLoader {
38         /**
39          * Instance of this class
40          */
41         private static $selfInstance = NULL;
42
43         /**
44          * Array with all classes
45          */
46         private $classes = array();
47
48         /**
49          * List of loaded classes
50          */
51         private $loadedClasses = array();
52
53         /**
54          * Suffix with extension for all class files
55          */
56         private $prefix = 'class_';
57
58         /**
59          * Suffix with extension for all class files
60          */
61         private $suffix = '.php';
62
63         /**
64          * A list for directory names (no leading/trailing slashes!) which not be scanned by the path scanner
65          * @see scanLocalPath
66          */
67         private $ignoreList = array();
68
69         /**
70          * Debug this class loader? (true = yes, false = no)
71          */
72         private $debug = false;
73
74         /**
75          * Wether the file list is cached or not
76          */
77         private $listCached = false;
78
79         /**
80          * Wethe class content has been cached
81          */
82         private $classesCached = false;
83
84         /**
85          * Filename for the list cache
86          */
87         private $listCacheFQFN = '';
88
89         /**
90          * Cache for class content
91          */
92         private $classCacheFQFN = '';
93
94         /**
95          * Counter for loaded include files
96          */
97         private $total = 0;
98
99         /**
100          * The protected constructor. Please use the factory method below, or use
101          * getSelfInstance() for singleton
102          *
103          * @return      void
104          */
105         protected function __construct () {
106                 // Is currently empty
107         }
108
109         /**
110          * The destructor makes it sure all caches got flushed
111          *
112          * @return      void
113          */
114         public function __destruct () {
115                 // Skip here if dev-mode
116                 if (defined('DEVELOPER')) {
117                         return;
118                 } // END - if
119
120                 // Skip here if already cached
121                 if ($this->listCached === false) {
122                         // Writes the cache file of our list away
123                         $cacheContent = serialize($this->classes);
124                         file_put_contents($this->listCacheFQFN, $cacheContent);
125                 } // END - if
126
127                 // Skip here if already cached
128                 if ($this->classesCached === false) {
129                         // Generate a full-cache of all classes
130                         $cacheContent = '';
131                         foreach ($this->loadedClasses as $fqfn) {
132                                 // Load the file
133                                 $cacheContent .= file_get_contents($fqfn);
134                         } // END - foreach
135
136                         // And write it away
137                         file_put_contents($this->classCacheFQFN, $cacheContent);
138                 } // END - if
139         }
140
141         /**
142          * Our renamed factory method
143          *
144          * @param       $configInstance Configuration class instance
145          * @return      void
146          */
147         public static final function createClassLoader (FrameworkConfiguration $configInstance) {
148                 // Get a new instance
149                 $loaderInstance = new ClassLoader();
150
151                 // Init the instance
152                 $loaderInstance->initLoader($configInstance);
153
154                 // Return the prepared instance
155                 return $loaderInstance;
156         }
157
158         /**
159          * Initializes our loader class
160          *
161          * @param       $configInstance Configuration class instance
162          * @return      void
163          */
164         protected function initLoader (FrameworkConfiguration $configInstance) {
165                 // Set configuration instance
166                 $this->configInstance = $configInstance;
167
168                 // Construct the FQFN for the cache
169                 if (!defined('DEVELOPER')) {
170                         $this->listCacheFQFN  = $this->configInstance->getConfigEntry('local_db_path') . 'list-' . $this->configInstance->getConfigEntry('app_name') . '.cache';
171                         $this->classCacheFQFN = $this->configInstance->getConfigEntry('local_db_path') . 'class-' . $this->configInstance->getConfigEntry('app_name') . '.cache';
172                 } // END - if
173
174                 // Set suffix and prefix from configuration
175                 $this->suffix = $configInstance->getConfigEntry('class_suffix');
176                 $this->prefix = $configInstance->getConfigEntry('class_prefix');
177
178                 // Set own instance
179                 self::$selfInstance = $this;
180
181                 // Skip here if no dev-mode
182                 if (defined('DEVELOPER')) {
183                         return;
184                 } // END - if
185
186                 // IS the cache there?
187                 if (file_exists($this->listCacheFQFN)) {
188                         // Get content
189                         $cacheContent = file_get_contents($this->listCacheFQFN);
190
191                         // And convert it
192                         $this->classes = unserialize($cacheContent);
193
194                         // List has been restored from cache!
195                         $this->listCached = true;
196                 } // END - if
197
198                 // Does the class cache exist?
199                 if (file_exists($this->classCacheFQFN)) {
200                         // Then include it
201                         require($this->classCacheFQFN);
202
203                         // Mark the class cache as loaded
204                         $this->classesCached = true;
205                 } // END - if
206         }
207
208         /**
209          * Autoload-function
210          *
211          * @param       $className      Name of the class to load
212          * @return      void
213          */
214         public static function autoLoad ($className) {
215                 // Try to include this class
216                 self::getSelfInstance()->includeClass($className);
217         }
218
219         /**
220          * Singleton getter for an instance of this class
221          *
222          * @return      $selfInstance           A singleton instance of this class
223          */
224         public static final function getSelfInstance () {
225                 // Is the instance there?
226                 if (is_null(self::$selfInstance)) {
227                         // Get a new one
228                         self::$selfInstance = ClassLoader::createClassLoader(FrameworkConfiguration::getSelfInstance());
229                 } // END - if
230
231                 // Return the instance
232                 return self::$selfInstance;
233         }
234
235         /**
236          * Scans recursively a local path for class files which must have a prefix and a suffix as given by $this->suffix and $this->prefix
237          *
238          * @param       $basePath               The relative base path to 'base_path' constant for all classes
239          * @param       $ignoreList             An optional list (array forced) of directory and file names which shall be ignored
240          * @return      void
241          */
242         public function scanClassPath ($basePath, array $ignoreList = array() ) {
243                 // Is a list has been restored from cache, don't read it again
244                 if ($this->listCached === true) {
245                         // Abort here
246                         return;
247                 } // END - if
248
249                 // Directories which our class loader ignores by default while
250                 // deep-scanning the directory structure.
251                 $ignoreList[] = '.';
252                 $ignoreList[] = '..';
253                 $ignoreList[] = '.htaccess';
254                 $ignoreList[] = '.svn';
255
256                 // Keep it in class for later usage
257                 $this->ignoreList = $ignoreList;
258
259                 // Set base directory which holds all our classes, we should use an
260                 // absolute path here so is_dir(), is_file() and so on will always
261                 // find the correct files and dirs.
262                 $basePath2 = realpath($basePath);
263
264                 // If the basePath is false it is invalid
265                 if ($basePath2 === false) {
266                         /* @todo: Do not die here. */
267                         die('Cannot read ' . $basePath . ' !');
268                 } else {
269                         // Set base path
270                         $basePath = $basePath2;
271                 }
272
273                 // Get a new iterator
274                 //* DEBUG: */ echo "<strong>Base path: {$basePath}</strong><br />\n";
275                 $iterator = new RecursiveDirectoryIterator($basePath);
276                 $recursive = new RecursiveIteratorIterator($iterator);
277                 foreach ($recursive as $entry) {
278                         // Get filename from iterator
279                         $fileName = $entry->getFileName();
280
281                         // Get the FQFN and add it to our class list
282                         $fqfn = $entry->getRealPath();
283
284                         // Is this file wanted?
285                         //* DEBUG: */ echo "FOUND:{$fileName}<br />\n";
286                         if ((!in_array($fileName, $this->ignoreList)) && (filesize($fqfn) > 100) && (substr($fileName, 0, strlen($this->prefix)) == $this->prefix) && (substr($fileName, -strlen($this->suffix), strlen($this->suffix)) == $this->suffix)) {
287                                 //* DEBUG: */ echo "ADD: {$fileName}<br />\n";
288                                 // Add it to the list
289                                 $this->classes[$fileName] = $fqfn;
290                         } // END - if
291                 } // END - foreach
292         }
293
294         /**
295          * Load extra config files
296          *
297          * @return      void
298          */
299         public function loadExtraConfigs () {
300                 // Backup old prefix
301                 $oldPrefix = $this->prefix;
302
303                 // Set new prefix (temporary!)
304                 $this->prefix = 'config-';
305
306                 // Set base directory
307                 $basePath = $this->configInstance->getConfigEntry('base_path') . 'inc/config/';
308
309                 // Load all classes from the config directory
310                 $this->scanClassPath($basePath);
311
312                 // Include these extra configs now
313                 $this->includeExtraConfigs();
314
315                 // Set the prefix back
316                 $this->prefix = $oldPrefix;
317         }
318
319         /**
320          * Tries to find the given class in our list. This method ignores silently
321          * missing classes or interfaces. So if you use class_exists() this method
322          * does not interrupt your program.
323          *
324          * @param       $className      The class we shall load
325          * @return      void
326          */
327         public function includeClass ($className) {
328                 // Create a name with prefix and suffix
329                 $fileName = $this->prefix . $className . $this->suffix;
330
331                 // Now look it up in our index
332                 if ((isset($this->classes[$fileName])) && (!in_array($this->classes[$fileName], $this->loadedClasses))) {
333                         // File is found and not loaded so load it only once
334                         //* DEBUG: */ echo "LOAD: ".$fileName." - Start<br />\n";
335                         require($this->classes[$fileName]);
336                         //* DEBUG: */ echo "LOAD: ".$fileName." - End<br />\n";
337
338                         // Count this include
339                         $this->total++;
340
341                         // Mark this class as loaded
342                         $this->loadedClasses[] = $this->classes[$fileName];
343
344                         // Remove it from classes list
345                         unset($this->classes[$fileName]);
346
347                         // Developer mode excludes caching (better debugging)
348                         if (!defined('DEVELOPER')) {
349                                 // Reset cache
350                                 $this->classesCached = false;
351                         } // END - if
352                 } // END - if
353         }
354
355         /**
356          * Includes all extra config files
357          *
358          * @return      void
359          */
360         private function includeExtraConfigs () {
361                 // Run through all class names (should not be much)
362                 foreach ($this->classes as $fileName => $fqfn) {
363                         // Is this a config?
364                         if (substr($fileName, 0, strlen($this->prefix)) == $this->prefix) {
365                                 // Then include it
366                                 require($fqfn);
367
368                                 // Remove it from the list
369                                 unset($this->classes[$fileName]);
370                         } // END - if
371                 } // END - foreach
372         }
373
374         /**
375          * Getter for total include counter
376          *
377          * @return      $total  Total loaded include files
378          */
379         public final function getTotal () {
380                 return $this->total;
381         }
382
383         /**
384          * Getter for a printable list of included classes/interfaces/exceptions
385          *
386          * @param       $includeList    A printable include list
387          */
388         public function getPrintableIncludeList () {
389                 // Prepare the list
390                 $includeList = '';
391                 foreach ($this->loadedClasses as $classFile) {
392                         $includeList .= basename($classFile)."<br />\n";
393                 } // END - foreach
394
395                 // And return it
396                 return $includeList;
397         }
398 }
399
400 // [EOF]
401 ?>