eee9fce15e85d458920073785c1e5ce842a64216
[core.git] / inc / loader / class_ClassLoader.php
1 <?php
2 // Own namespace
3 namespace CoreFramework\Loader;
4
5 // Import framework stuff
6 use CoreFramework\Configuration\FrameworkConfiguration;
7 use CoreFramework\Object\BaseFrameworkSystem;
8
9 // Import SPL stuff
10 use \InvalidArgumentException;
11 use \RecursiveDirectoryIterator;
12 use \RecursiveIteratorIterator;
13
14 /**
15  * This class loads class include files with a specific prefix and suffix
16  *
17  * @author              Roland Haeder <webmaster@shipsimu.org>
18  * @version             1.5.0
19  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
20  * @license             GNU GPL 3.0 or any newer version
21  * @link                http://www.shipsimu.org
22  *
23  * This program is free software: you can redistribute it and/or modify
24  * it under the terms of the GNU General Public License as published by
25  * the Free Software Foundation, either version 3 of the License, or
26  * (at your option) any later version.
27  *
28  * This program is distributed in the hope that it will be useful,
29  * but WITHOUT ANY WARRANTY; without even the implied warranty of
30  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
31  * GNU General Public License for more details.
32  *
33  * You should have received a copy of the GNU General Public License
34  * along with this program. If not, see <http://www.gnu.org/licenses/>.
35  *
36  * ----------------------------------
37  * 1.5
38  *  - Namespace scheme Project\Package[\SubPackage...] is fully supported and
39  *    throws an InvalidArgumentException if not present. The last part will be
40  *    always the class' name.
41  * 1.4
42  *  - Some comments improved, other minor improvements
43  * 1.3
44  *  - Constructor is now empty and factory method 'createClassLoader' is created
45  *  - renamed loadClasses to scanClassPath
46  *  - Added initLoader()
47  * 1.2
48  *  - ClassLoader rewritten to PHP SPL's own RecursiveIteratorIterator class
49  * 1.1
50  *  - loadClasses rewritten to fix some notices
51  * 1.0
52  *  - Initial release
53  * ----------------------------------
54  */
55 class ClassLoader {
56         /**
57          * Instance of this class
58          */
59         private static $selfInstance = NULL;
60
61         /**
62          * Array with all found classes
63          */
64         private $foundClasses = array();
65
66         /**
67          * List of loaded classes
68          */
69         private $loadedClasses = array();
70
71         /**
72          * Suffix with extension for all class files
73          */
74         private $prefix = 'class_';
75
76         /**
77          * Suffix with extension for all class files
78          */
79         private $suffix = '.php';
80
81         /**
82          * A list for directory names (no leading/trailing slashes!) which not be scanned by the path scanner
83          * @see scanLocalPath
84          */
85         private $ignoreList = array();
86
87         /**
88          * Debug this class loader? (TRUE = yes, FALSE = no)
89          */
90         private $debug = FALSE;
91
92         /**
93          * Whether the file list is cached
94          */
95         private $listCached = FALSE;
96
97         /**
98          * Wethe class content has been cached
99          */
100         private $classesCached = FALSE;
101
102         /**
103          * Filename for the list cache
104          */
105         private $listCacheFQFN = '';
106
107         /**
108          * Cache for class content
109          */
110         private $classCacheFQFN = '';
111
112         /**
113          * Counter for loaded include files
114          */
115         private $total = 0;
116
117         /**
118          * Framework/application paths for classes, etc.
119          */
120         private static $frameworkPaths = array(
121                 'exceptions', // Exceptions
122                 'interfaces', // Interfaces
123                 'classes',    // Classes
124                 'middleware'  // The middleware
125         );
126
127
128         /**
129          * The protected constructor. Please use the factory method below, or use
130          * getSelfInstance() for singleton
131          *
132          * @return      void
133          */
134         protected function __construct () {
135                 // Is currently empty
136         }
137
138         /**
139          * The destructor makes it sure all caches got flushed
140          *
141          * @return      void
142          */
143         public function __destruct () {
144                 // Skip here if dev-mode
145                 if (defined('DEVELOPER')) {
146                         return;
147                 } // END - if
148
149                 // Skip here if already cached
150                 if ($this->listCached === FALSE) {
151                         // Writes the cache file of our list away
152                         $cacheContent = json_encode($this->foundClasses);
153                         file_put_contents($this->listCacheFQFN, $cacheContent);
154                 } // END - if
155
156                 // Skip here if already cached
157                 if ($this->classesCached === FALSE) {
158                         // Generate a full-cache of all classes
159                         $cacheContent = '';
160                         foreach (array_keys($this->loadedClasses) as $fqfn) {
161                                 // Load the file
162                                 $cacheContent .= file_get_contents($fqfn);
163                         } // END - foreach
164
165                         // And write it away
166                         file_put_contents($this->classCacheFQFN, $cacheContent);
167                 } // END - if
168         }
169
170         /**
171          * Creates an instance of this class loader for given configuration instance
172          *
173          * @param       $configInstance         Configuration class instance
174          * @return      void
175          */
176         public static final function createClassLoader (FrameworkConfiguration $configInstance) {
177                 // Get a new instance
178                 $loaderInstance = new ClassLoader();
179
180                 // Init the instance
181                 $loaderInstance->initLoader($configInstance);
182
183                 // Return the prepared instance
184                 return $loaderInstance;
185         }
186
187         /**
188          * Scans for all framework classes, exceptions and interfaces.
189          *
190          * @return      void
191          */
192         public static function scanFrameworkClasses () {
193                 // Trace message
194                 /* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
195
196                 // Cache loader instance
197                 $loaderInstance = self::getSelfInstance();
198
199                 // Load all classes
200                 foreach (self::$frameworkPaths as $pathName) {
201                         // Debug message
202                         /* NOISY-DEBUG: */ printf('[%s:%d]: pathName=%s' . PHP_EOL, __METHOD__, __LINE__, $pathName);
203
204                         // Try to load the framework classes
205                         $loaderInstance->scanClassPath('inc/main/' . $pathName . '/');
206                 } // END - foreach
207         }
208
209         /**
210          * Scans for application's classes, etc.
211          *
212          * @return      void
213          */
214         public static function scanApplicationClasses () {
215                 // Trace message
216                 /* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
217
218                 // Get config instance
219                 $cfg = FrameworkConfiguration::getSelfInstance();
220
221                 // Load all classes for the application
222                 foreach (self::$frameworkPaths as $class) {
223                         // Create path name
224                         $pathName = sprintf('%s/%s/%s', $cfg->getConfigEntry('application_path'), $cfg->getConfigEntry('app_name'), $class);
225
226                         // Debug message
227                         /* NOISY-DEBUG: */ printf('[%s:%d]: pathName=%s' . PHP_EOL, __METHOD__, __LINE__, $pathName);
228
229                         // Is the path readable?
230                         if (is_dir($pathName)) {
231                                 // Try to load the application classes
232                                 ClassLoader::getSelfInstance()->scanClassPath($pathName);
233                         } // END - if
234                 } // END - foreach
235         }
236
237         /**
238          * Initializes our loader class
239          *
240          * @param       $configInstance Configuration class instance
241          * @return      void
242          */
243         protected function initLoader (FrameworkConfiguration $configInstance) {
244                 // Set configuration instance
245                 $this->configInstance = $configInstance;
246
247                 // Construct the FQFN for the cache
248                 if (!defined('DEVELOPER')) {
249                         $this->listCacheFQFN  = $this->configInstance->getConfigEntry('local_db_path') . 'list-' . $this->configInstance->getConfigEntry('app_name') . '.cache';
250                         $this->classCacheFQFN = $this->configInstance->getConfigEntry('local_db_path') . 'class-' . $this->configInstance->getConfigEntry('app_name') . '.cache';
251                 } // END - if
252
253                 // Set suffix and prefix from configuration
254                 $this->suffix = $configInstance->getConfigEntry('class_suffix');
255                 $this->prefix = $configInstance->getConfigEntry('class_prefix');
256
257                 // Set own instance
258                 self::$selfInstance = $this;
259
260                 // Skip here if no dev-mode
261                 if (defined('DEVELOPER')) {
262                         return;
263                 } // END - if
264
265                 // IS the cache there?
266                 if (BaseFrameworkSystem::isReadableFile($this->listCacheFQFN)) {
267                         // Get content
268                         $cacheContent = file_get_contents($this->listCacheFQFN);
269
270                         // And convert it
271                         $this->foundClasses = json_decode($cacheContent);
272
273                         // List has been restored from cache!
274                         $this->listCached = TRUE;
275                 } // END - if
276
277                 // Does the class cache exist?
278                 if (BaseFrameworkSystem::isReadableFile($this->listCacheFQFN)) {
279                         // Then include it
280                         require($this->classCacheFQFN);
281
282                         // Mark the class cache as loaded
283                         $this->classesCached = TRUE;
284                 } // END - if
285         }
286
287         /**
288          * Autoload-function
289          *
290          * @param       $className      Name of the class to load
291          * @return      void
292          */
293         public static function autoLoad ($className) {
294                 // Try to include this class
295                 self::getSelfInstance()->loadClassFile($className);
296         }
297
298         /**
299          * Singleton getter for an instance of this class
300          *
301          * @return      $selfInstance   A singleton instance of this class
302          */
303         public static final function getSelfInstance () {
304                 // Is the instance there?
305                 if (is_null(self::$selfInstance)) {
306                         // Get a new one
307                         self::$selfInstance = ClassLoader::createClassLoader(FrameworkConfiguration::getSelfInstance());
308                 } // END - if
309
310                 // Return the instance
311                 return self::$selfInstance;
312         }
313
314         /**
315          * Scans recursively a local path for class files which must have a prefix and a suffix as given by $this->suffix and $this->prefix
316          *
317          * @param       $basePath               The relative base path to 'base_path' constant for all classes
318          * @param       $ignoreList             An optional list (array forced) of directory and file names which shall be ignored
319          * @return      void
320          */
321         public function scanClassPath ($basePath, array $ignoreList = array() ) {
322                 // Is a list has been restored from cache, don't read it again
323                 if ($this->listCached === TRUE) {
324                         // Abort here
325                         return;
326                 } // END - if
327
328                 // Keep it in class for later usage
329                 $this->ignoreList = $ignoreList;
330
331                 /*
332                  * Ignore .htaccess by default as it is for protection of directories
333                  * on Apache servers.
334                  */
335                 array_push($ignoreList, '.htaccess');
336
337                 /*
338                  * Set base directory which holds all our classes, an absolute path
339                  * should be used here so is_dir(), is_file() and so on will always
340                  * find the correct files and dirs.
341                  */
342                 $basePath2 = realpath($basePath);
343
344                 // If the basePath is FALSE it is invalid
345                 if ($basePath2 === FALSE) {
346                         /* @TODO: Do not exit here. */
347                         exit(__METHOD__ . ': Cannot read ' . $basePath . ' !' . PHP_EOL);
348                 } else {
349                         // Set base path
350                         $basePath = $basePath2;
351                 }
352
353                 // Get a new iterator
354                 /* NOISY-DEBUG: */ printf('[%s:%d] basePath=%s' . PHP_EOL, __METHOD__, __LINE__, $basePath);
355                 $iteratorInstance = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($basePath), RecursiveIteratorIterator::CHILD_FIRST);
356
357                 // Load all entries
358                 while ($iteratorInstance->valid()) {
359                         // Get current entry
360                         $currentEntry = $iteratorInstance->current();
361
362                         // Get filename from iterator
363                         $fileName = $currentEntry->getFileName();
364
365                         // Get the "FQFN" (path and file name)
366                         $fqfn = $currentEntry->getRealPath();
367
368                         // Current entry must be a file, not smaller than 100 bytes and not on ignore list 
369                         if ((!$currentEntry->isFile()) || (in_array($fileName, $this->ignoreList)) || (filesize($fqfn) < 100)) {
370                                 // Advance to next entry
371                                 $iteratorInstance->next();
372
373                                 // Skip non-file entries
374                                 /* NOISY-DEBUG: */ printf('[%s:%d] SKIP: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
375                                 continue;
376                         } // END - if
377
378                         // Is this file wanted?
379                         /* NOISY-DEBUG: */ printf('[%s:%d] FOUND: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
380                         if ((substr($fileName, 0, strlen($this->prefix)) == $this->prefix) && (substr($fileName, -strlen($this->suffix), strlen($this->suffix)) == $this->suffix)) {
381                                 // Add it to the list
382                                 /* NOISY-DEBUG: */ printf('[%s:%d] ADD: %s,fqfn=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName, $fqfn);
383                                 $this->foundClasses[$fileName] = $fqfn;
384                         } else {
385                                 // Not added
386                                 /* NOISY-DEBUG: */ printf('[%s:%d] NOT ADDED: %s,fqfn=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName, $fqfn);
387                         }
388
389                         // Advance to next entry
390                         /* NOISY-DEBUG: */ printf('[%s:%d] NEXT: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
391                         $iteratorInstance->next();
392                 } // END - while
393         }
394
395         /**
396          * Load extra config files
397          *
398          * @return      void
399          */
400         public function loadExtraConfigs () {
401                 // Backup old prefix
402                 $oldPrefix = $this->prefix;
403
404                 // Set new prefix (temporary!)
405                 $this->prefix = 'config-';
406
407                 // Set base directory
408                 $basePath = $this->configInstance->getConfigEntry('base_path') . 'inc/config/';
409
410                 // Load all classes from the config directory
411                 $this->scanClassPath($basePath);
412
413                 // Include these extra configs now
414                 $this->includeExtraConfigs();
415
416                 // Set back the old prefix
417                 $this->prefix = $oldPrefix;
418         }
419
420         /**
421          * Tries to find the given class in our list. This method ignores silently
422          * missing classes or interfaces. So if you use class_exists() this method
423          * does not interrupt your program.
424          *
425          * @param       $className      The class that shall be loaded
426          * @return      void
427          */
428         private function loadClassFile ($className) {
429                 // Trace message
430                 /* NOISY-DEBUG: */ printf('[%s:%d] className=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $className);
431
432                 // The class name should contain at least 2 back-slashes, so split at them
433                 $classNameParts = explode("\\", $className);
434
435                 // At least 3 parts should be there
436                 if (count($classNameParts) < 3) {
437                         // Namespace scheme is: Project\Package[\SubPackage...]
438                         throw new InvalidArgumentException(sprintf('Class name "%s" is not conform to naming-convention: Project\Package[\SubPackage...]\SomeFooBar', $className));
439                 } // END - if
440
441                 // Get last element
442                 $shortClassName = array_pop($classNameParts);
443
444                 // Create a name with prefix and suffix
445                 $fileName = $this->prefix . $shortClassName . $this->suffix;
446
447                 // Now look it up in our index
448                 /* NOISY-DEBUG: */ printf('[%s:%d] ISSET: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
449                 if ((isset($this->foundClasses[$fileName])) && (!isset($this->loadedClasses[$this->foundClasses[$fileName]]))) {
450                         // File is found and not loaded so load it only once
451                         /* NOISY-DEBUG: */ printf('[%s:%d] LOAD: %s - START' . PHP_EOL, __METHOD__, __LINE__, $fileName);
452                         require($this->foundClasses[$fileName]);
453                         /* NOISY-DEBUG: */ printf('[%s:%d] LOAD: %s - END' . PHP_EOL, __METHOD__, __LINE__, $fileName);
454
455                         // Count this loaded class/interface/exception
456                         $this->total++;
457
458                         // Mark this class as loaded for other purposes than loading it.
459                         $this->loadedClasses[$this->foundClasses[$fileName]] = TRUE;
460
461                         // Remove it from classes list so it won't be found twice.
462                         /* NOISY-DEBUG: */ printf('[%s:%d] UNSET: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
463                         unset($this->foundClasses[$fileName]);
464
465                         // Developer mode excludes caching (better debugging)
466                         if (!defined('DEVELOPER')) {
467                                 // Reset cache
468                                 /* NOISY-DEBUG: */ printf('[%s:%d] classesCached=FALSE' . PHP_EOL, __METHOD__, __LINE__);
469                                 $this->classesCached = FALSE;
470                         } // END - if
471                 } else {
472                         // Not found
473                         /* NOISY-DEBUG: */ printf('[%s:%d] 404: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
474                 }
475         }
476
477         /**
478          * Includes all extra config files
479          *
480          * @return      void
481          */
482         private function includeExtraConfigs () {
483                 // Run through all class names (should not be much)
484                 foreach ($this->foundClasses as $fileName => $fqfn) {
485                         // Is this a config?
486                         if (substr($fileName, 0, strlen($this->prefix)) == $this->prefix) {
487                                 // Then include it
488                                 /* NOISY-DEBUG: */ printf('[%s:%d] LOAD: %s - START' . PHP_EOL, __METHOD__, __LINE__, $fileName);
489                                 require($fqfn);
490                                 /* NOISY-DEBUG: */ printf('[%s:%d] LOAD: %s - END' . PHP_EOL, __METHOD__, __LINE__, $fileName);
491
492                                 // Remove it from the list
493                                 /* NOISY-DEBUG: */ printf('[%s:%d] UNSET: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
494                                 unset($this->foundClasses[$fileName]);
495                         } // END - if
496                 } // END - foreach
497         }
498
499         /**
500          * Getter for total include counter
501          *
502          * @return      $total  Total loaded include files
503          */
504         public final function getTotal () {
505                 return $this->total;
506         }
507
508         /**
509          * Getter for a printable list of included main/interfaces/exceptions
510          *
511          * @param       $includeList    A printable include list
512          */
513         public function getPrintableIncludeList () {
514                 // Prepare the list
515                 $includeList = '';
516                 foreach ($this->loadedClasses as $classFile) {
517                         $includeList .= basename($classFile) . '<br />' . PHP_EOL;
518                 } // END - foreach
519
520                 // And return it
521                 return $includeList;
522         }
523
524 }