Just a space removed
[shipsimu.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                         die("Cannot read {$basePath} !");
240                 } else {
241                         // Set base path
242                         $basePath = $basePath2;
243                 }
244
245                 // Get a new iterator
246                 //* DEBUG: */ echo "<strong>Base path: {$basePath}</strong><br />\n";
247                 $iterator = new RecursiveDirectoryIterator($basePath);
248                 $recursive = new RecursiveIteratorIterator($iterator);
249                 foreach ($recursive as $entry) {
250                         // Get filename from iterator
251                         $fileName = $entry->getFileName();
252
253                         // Is this file wanted?
254                         //* DEBUG: */ echo "FOUND:{$fileName}<br />\n";
255                         if ((!in_array($fileName, $this->ignoreList)) && (substr($fileName, 0, $this->prefixLen) == $this->prefix) && (substr($fileName, -$this->suffixLen, $this->suffixLen) == $this->suffix)) {
256                                 // Get the FQFN and add it to our class list
257                                 $fqfn = $entry->getRealPath();
258                                 //* DEBUG: */ echo "ADD: {$fileName}<br />\n";
259                                 $this->classes[$fileName] = $fqfn;
260                         } // END - if
261                 } // END - foreach
262         }
263
264         /**
265          * Load extra config files
266          *
267          * @return      void
268          */
269         public function loadExtraConfigs () {
270                 // Backup old prefix
271                 $oldPrefix = $this->prefix;
272
273                 // Set new prefix (temporary!)
274                 $this->prefix = "config-";
275                 $this->prefixLen = strlen($this->prefix);
276
277                 // Set base directory
278                 $basePath = sprintf("%sinc/config/", PATH);
279
280                 // Load all classes from the config directory
281                 $this->loadClasses($basePath);
282
283                 // Include these extra configs now
284                 $this->includeExtraConfigs();
285
286                 // Set the prefix back
287                 $this->prefix = $oldPrefix;
288                 $this->prefixLen = strlen($this->prefix);
289
290         }
291
292         /**
293          * Tries to find the given class in our list. This method ignores silently
294          * missing classes or interfaces. So if you use class_exists() this method
295          * does not interrupt your program.
296          *
297          * @param       $className      The class we shall load
298          * @return      void
299          */
300         public function includeClass ($className) {
301                 // Create a name with prefix and suffix
302                 $fileName = $this->prefix . $className . $this->suffix;
303
304                 // Now look it up in our index
305                 if (isset($this->classes[$fileName])) {
306                         // File is found so load it only once
307                         require($this->classes[$fileName]);
308
309                         // Developer mode excludes caching (better debugging)
310                         if (!defined('DEVELOPER')) {
311                                 // Mark this class as loaded
312                                 $this->loadedClasses[] = $this->classes[$fileName];
313
314                                 // Reset cache
315                                 $this->classesCached = false;
316                         } // END - if
317                 } // END - if
318         }
319
320         /**
321          * Includes all extra config files
322          *
323          * @return      void
324          */
325         private function includeExtraConfigs () {
326                 // Run through all class names (should not be much)
327                 foreach ($this->classes as $fileName=>$fqfn) {
328                         // Is this a config?
329                         if (substr($fileName, 0, $this->prefixLen) == $this->prefix) {
330                                 // Then include it
331                                 require($fqfn);
332
333                                 // Remove it from the list
334                                 unset($this->classes[$fileName]);
335                         } // END - if
336                 } // END - foreach
337         }
338 }
339
340 // [EOF]
341 ?>