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