f4a69ab6e6297889384d583b9811a43886dc2d40
[core.git] / framework / 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          * Registered paths where test classes can be found. These are all relative
129          * to base_path .
130          */
131         private static $testPaths = array();
132
133         /**
134          * The protected constructor. Please use the factory method below, or use
135          * getSelfInstance() for singleton
136          *
137          * @return      void
138          */
139         protected function __construct () {
140                 // This is empty for now
141         }
142
143         /**
144          * The destructor makes it sure all caches got flushed
145          *
146          * @return      void
147          */
148         public function __destruct () {
149                 // Skip here if dev-mode
150                 if (defined('DEVELOPER')) {
151                         return;
152                 } // END - if
153
154                 // Skip here if already cached
155                 if ($this->listCached === FALSE) {
156                         // Writes the cache file of our list away
157                         $cacheContent = json_encode($this->foundClasses);
158                         file_put_contents($this->listCacheFQFN, $cacheContent);
159                 } // END - if
160
161                 // Skip here if already cached
162                 if ($this->classesCached === FALSE) {
163                         // Generate a full-cache of all classes
164                         $cacheContent = '';
165                         foreach (array_keys($this->loadedClasses) as $fqfn) {
166                                 // Load the file
167                                 $cacheContent .= file_get_contents($fqfn);
168                         } // END - foreach
169
170                         // And write it away
171                         file_put_contents($this->classCacheFQFN, $cacheContent);
172                 } // END - if
173         }
174
175         /**
176          * Creates an instance of this class loader for given configuration instance
177          *
178          * @param       $configInstance         Configuration class instance
179          * @return      void
180          */
181         public static final function createClassLoader (FrameworkConfiguration $configInstance) {
182                 // Get a new instance
183                 $loaderInstance = new ClassLoader();
184
185                 // Init the instance
186                 $loaderInstance->initLoader($configInstance);
187
188                 // Return the prepared instance
189                 return $loaderInstance;
190         }
191
192         /**
193          * Scans for all framework classes, exceptions and interfaces.
194          *
195          * @return      void
196          */
197         public static function scanFrameworkClasses () {
198                 // Trace message
199                 //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
200
201                 // Cache loader instance
202                 $loaderInstance = self::getSelfInstance();
203
204                 // Load all classes
205                 foreach (self::$frameworkPaths as $shortPath) {
206                         // Debug message
207                         //* NOISY-DEBUG: */ printf('[%s:%d]: shortPath=%s' . PHP_EOL, __METHOD__, __LINE__, $shortPath);
208
209                         // Try to load the framework classes
210                         $loaderInstance->scanClassPath(sprintf('framework/main/%s/', $shortPath));
211                 } // END - foreach
212
213                 // Trace message
214                 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
215         }
216
217         /**
218          * Scans for application's classes, etc.
219          *
220          * @return      void
221          */
222         public static function scanApplicationClasses () {
223                 // Trace message
224                 //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
225
226                 // Get config instance
227                 $cfg = FrameworkConfiguration::getSelfInstance();
228
229                 // Load all classes for the application
230                 foreach (self::$frameworkPaths as $shortPath) {
231                         // Debug message
232                         //* NOISY-DEBUG: */ printf('[%s:%d]: shortPath=%s' . PHP_EOL, __METHOD__, __LINE__, $shortPath);
233
234                         // Create path name
235                         $pathName = realpath(sprintf(
236                                 '%s/%s/%s',
237                                 $cfg->getConfigEntry('application_path'),
238                                 $cfg->getConfigEntry('app_name'),
239                                 $shortPath
240                         ));
241
242                         // Debug message
243                         //* NOISY-DEBUG: */ printf('[%s:%d]: pathName[%s]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype($pathName), $pathName);
244
245                         // Is the path readable?
246                         if (is_dir($pathName)) {
247                                 // Try to load the application classes
248                                 ClassLoader::getSelfInstance()->scanClassPath($pathName);
249                         } // END - if
250                 } // END - foreach
251
252                 // Trace message
253                 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
254         }
255
256         /**
257          * Scans for test classes, etc.
258          *
259          * @return      void
260          */
261         public static function scanTestsClasses () {
262                 // Trace message
263                 //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
264
265                 // Get config instance
266                 $cfg = FrameworkConfiguration::getSelfInstance();
267
268                 // Load all classes for the application
269                 foreach (self::$testPaths as $shortPath) {
270                         // Debug message
271                         //* NOISY-DEBUG: */ printf('[%s:%d]: shortPath=%s' . PHP_EOL, __METHOD__, __LINE__, $shortPath);
272
273                         // Create path name
274                         $pathName = realpath(sprintf(
275                                 '%s/%s',
276                                 $cfg->getConfigEntry('base_path'),
277                                 $shortPath
278                         ));
279
280                         // Debug message
281                         //* NOISY-DEBUG: */ printf('[%s:%d]: pathName[%s]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype($pathName), $pathName);
282
283                         // Is the path readable?
284                         if (is_dir($pathName)) {
285                                 // Try to load the application classes
286                                 ClassLoader::getSelfInstance()->scanClassPath($pathName);
287                         } // END - if
288                 } // END - foreach
289
290                 // Trace message
291                 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
292         }
293
294         /**
295          * Registeres given relative path where test classes reside. For regular
296          * framework uses, they should not be loaded (and used).
297          *
298          * @param       $relativePath   Relative path to test classes
299          * @return      void
300          */
301         public static function registerTestsPath ($relativePath) {
302                 // "Register" it
303                 self::$testPaths[$relativePath] = $relativePath;
304         }
305
306         /**
307          * Autoload-function
308          *
309          * @param       $className      Name of the class to load
310          * @return      void
311          */
312         public static function autoLoad ($className) {
313                 // Try to include this class
314                 self::getSelfInstance()->loadClassFile($className);
315         }
316
317         /**
318          * Singleton getter for an instance of this class
319          *
320          * @return      $selfInstance   A singleton instance of this class
321          */
322         public static final function getSelfInstance () {
323                 // Is the instance there?
324                 if (is_null(self::$selfInstance)) {
325                         // Get a new one
326                         self::$selfInstance = ClassLoader::createClassLoader(FrameworkConfiguration::getSelfInstance());
327                 } // END - if
328
329                 // Return the instance
330                 return self::$selfInstance;
331         }
332
333         /**
334          * Scans recursively a local path for class files which must have a prefix and a suffix as given by $this->suffix and $this->prefix
335          *
336          * @param       $basePath               The relative base path to 'base_path' constant for all classes
337          * @param       $ignoreList             An optional list (array forced) of directory and file names which shall be ignored
338          * @return      void
339          */
340         public function scanClassPath ($basePath, array $ignoreList = array() ) {
341                 // Is a list has been restored from cache, don't read it again
342                 if ($this->listCached === TRUE) {
343                         // Abort here
344                         return;
345                 } // END - if
346
347                 // Keep it in class for later usage
348                 $this->ignoreList = $ignoreList;
349
350                 /*
351                  * Ignore .htaccess by default as it is for protection of directories
352                  * on Apache servers.
353                  */
354                 array_push($ignoreList, '.htaccess');
355
356                 /*
357                  * Set base directory which holds all our classes, an absolute path
358                  * should be used here so is_dir(), is_file() and so on will always
359                  * find the correct files and dirs.
360                  */
361                 $basePath2 = realpath($basePath);
362
363                 // If the basePath is FALSE it is invalid
364                 if ($basePath2 === FALSE) {
365                         /* @TODO: Do not exit here. */
366                         exit(__METHOD__ . ': Cannot read ' . $basePath . ' !' . PHP_EOL);
367                 } else {
368                         // Set base path
369                         $basePath = $basePath2;
370                 }
371
372                 // Get a new iterator
373                 //* NOISY-DEBUG: */ printf('[%s:%d] basePath=%s' . PHP_EOL, __METHOD__, __LINE__, $basePath);
374                 $iteratorInstance = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($basePath), RecursiveIteratorIterator::CHILD_FIRST);
375
376                 // Load all entries
377                 while ($iteratorInstance->valid()) {
378                         // Get current entry
379                         $currentEntry = $iteratorInstance->current();
380
381                         // Get filename from iterator
382                         $fileName = $currentEntry->getFileName();
383
384                         // Get the "FQFN" (path and file name)
385                         $fqfn = $currentEntry->getRealPath();
386
387                         // Current entry must be a file, not smaller than 100 bytes and not on ignore list 
388                         if ((!$currentEntry->isFile()) || (in_array($fileName, $this->ignoreList)) || (filesize($fqfn) < 100)) {
389                                 // Advance to next entry
390                                 $iteratorInstance->next();
391
392                                 // Skip non-file entries
393                                 //* NOISY-DEBUG: */ printf('[%s:%d] SKIP: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
394                                 continue;
395                         } // END - if
396
397                         // Is this file wanted?
398                         //* NOISY-DEBUG: */ printf('[%s:%d] FOUND: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
399                         if ((substr($fileName, 0, strlen($this->prefix)) == $this->prefix) && (substr($fileName, -strlen($this->suffix), strlen($this->suffix)) == $this->suffix)) {
400                                 // Add it to the list
401                                 //* NOISY-DEBUG: */ printf('[%s:%d] ADD: %s,fqfn=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName, $fqfn);
402                                 $this->foundClasses[$fileName] = $fqfn;
403                         } else {
404                                 // Not added
405                                 //* NOISY-DEBUG: */ printf('[%s:%d] NOT ADDED: %s,fqfn=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName, $fqfn);
406                         }
407
408                         // Advance to next entry
409                         //* NOISY-DEBUG: */ printf('[%s:%d] NEXT: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
410                         $iteratorInstance->next();
411                 } // END - while
412         }
413
414         /**
415          * Load extra config files
416          *
417          * @return      void
418          */
419         public function loadExtraConfigs () {
420                 // Backup old prefix
421                 $oldPrefix = $this->prefix;
422
423                 // Set new prefix (temporary!)
424                 $this->prefix = 'config-';
425
426                 // Set base directory
427                 $basePath = $this->configInstance->getConfigEntry('base_path') . 'framework/config/';
428
429                 // Load all classes from the config directory
430                 $this->scanClassPath($basePath);
431
432                 // Include these extra configs now
433                 $this->includeExtraConfigs();
434
435                 // Set back the old prefix
436                 $this->prefix = $oldPrefix;
437         }
438
439         /**
440          * Initializes our loader class
441          *
442          * @param       $configInstance Configuration class instance
443          * @return      void
444          */
445         private function initLoader (FrameworkConfiguration $configInstance) {
446                 // Set configuration instance
447                 $this->configInstance = $configInstance;
448
449                 // Construct the FQFN for the cache
450                 if (!defined('DEVELOPER')) {
451                         $this->listCacheFQFN  = $this->configInstance->getConfigEntry('local_db_path') . 'list-' . $this->configInstance->getConfigEntry('app_name') . '.cache';
452                         $this->classCacheFQFN = $this->configInstance->getConfigEntry('local_db_path') . 'class-' . $this->configInstance->getConfigEntry('app_name') . '.cache';
453                 } // END - if
454
455                 // Set suffix and prefix from configuration
456                 $this->suffix = $configInstance->getConfigEntry('class_suffix');
457                 $this->prefix = $configInstance->getConfigEntry('class_prefix');
458
459                 // Set own instance
460                 self::$selfInstance = $this;
461
462                 // Skip here if no dev-mode
463                 if (defined('DEVELOPER')) {
464                         return;
465                 } // END - if
466
467                 // IS the cache there?
468                 if (BaseFrameworkSystem::isReadableFile($this->listCacheFQFN)) {
469                         // Get content
470                         $cacheContent = file_get_contents($this->listCacheFQFN);
471
472                         // And convert it
473                         $this->foundClasses = json_decode($cacheContent);
474
475                         // List has been restored from cache!
476                         $this->listCached = TRUE;
477                 } // END - if
478
479                 // Does the class cache exist?
480                 if (BaseFrameworkSystem::isReadableFile($this->listCacheFQFN)) {
481                         // Then include it
482                         require($this->classCacheFQFN);
483
484                         // Mark the class cache as loaded
485                         $this->classesCached = TRUE;
486                 } // END - if
487         }
488
489         /**
490          * Tries to find the given class in our list. This method ignores silently
491          * missing classes or interfaces. So if you use class_exists() this method
492          * does not interrupt your program.
493          *
494          * @param       $className      The class that shall be loaded
495          * @return      void
496          */
497         private function loadClassFile ($className) {
498                 // Trace message
499                 //* NOISY-DEBUG: */ printf('[%s:%d] className=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $className);
500
501                 // The class name should contain at least 2 back-slashes, so split at them
502                 $classNameParts = explode("\\", $className);
503
504                 // At least 3 parts should be there
505                 if (count($classNameParts) < 3) {
506                         // Namespace scheme is: Project\Package[\SubPackage...]
507                         throw new InvalidArgumentException(sprintf('Class name "%s" is not conform to naming-convention: Project\Package[\SubPackage...]\SomeFooBar', $className));
508                 } // END - if
509
510                 // Get last element
511                 $shortClassName = array_pop($classNameParts);
512
513                 // Create a name with prefix and suffix
514                 $fileName = $this->prefix . $shortClassName . $this->suffix;
515
516                 // Now look it up in our index
517                 //* NOISY-DEBUG: */ printf('[%s:%d] ISSET: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
518                 if ((isset($this->foundClasses[$fileName])) && (!isset($this->loadedClasses[$this->foundClasses[$fileName]]))) {
519                         // File is found and not loaded so load it only once
520                         //* NOISY-DEBUG: */ printf('[%s:%d] LOAD: %s - START' . PHP_EOL, __METHOD__, __LINE__, $fileName);
521                         require($this->foundClasses[$fileName]);
522                         //* NOISY-DEBUG: */ printf('[%s:%d] LOAD: %s - END' . PHP_EOL, __METHOD__, __LINE__, $fileName);
523
524                         // Count this loaded class/interface/exception
525                         $this->total++;
526
527                         // Mark this class as loaded for other purposes than loading it.
528                         $this->loadedClasses[$this->foundClasses[$fileName]] = TRUE;
529
530                         // Remove it from classes list so it won't be found twice.
531                         //* NOISY-DEBUG: */ printf('[%s:%d] UNSET: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
532                         unset($this->foundClasses[$fileName]);
533
534                         // Developer mode excludes caching (better debugging)
535                         if (!defined('DEVELOPER')) {
536                                 // Reset cache
537                                 //* NOISY-DEBUG: */ printf('[%s:%d] classesCached=FALSE' . PHP_EOL, __METHOD__, __LINE__);
538                                 $this->classesCached = FALSE;
539                         } // END - if
540                 } else {
541                         // Not found
542                         //* NOISY-DEBUG: */ printf('[%s:%d] 404: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
543                 }
544         }
545
546         /**
547          * Includes all extra config files
548          *
549          * @return      void
550          */
551         private function includeExtraConfigs () {
552                 // Run through all class names (should not be much)
553                 foreach ($this->foundClasses as $fileName => $fqfn) {
554                         // Is this a config?
555                         if (substr($fileName, 0, strlen($this->prefix)) == $this->prefix) {
556                                 // Then include it
557                                 //* NOISY-DEBUG: */ printf('[%s:%d] LOAD: %s - START' . PHP_EOL, __METHOD__, __LINE__, $fileName);
558                                 require($fqfn);
559                                 //* NOISY-DEBUG: */ printf('[%s:%d] LOAD: %s - END' . PHP_EOL, __METHOD__, __LINE__, $fileName);
560
561                                 // Remove it from the list
562                                 //* NOISY-DEBUG: */ printf('[%s:%d] UNSET: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
563                                 unset($this->foundClasses[$fileName]);
564                         } // END - if
565                 } // END - foreach
566         }
567
568         /**
569          * Getter for total include counter
570          *
571          * @return      $total  Total loaded include files
572          */
573         public final function getTotal () {
574                 return $this->total;
575         }
576
577         /**
578          * Getter for a printable list of included main/interfaces/exceptions
579          *
580          * @param       $includeList    A printable include list
581          */
582         public function getPrintableIncludeList () {
583                 // Prepare the list
584                 $includeList = '';
585                 foreach ($this->loadedClasses as $classFile) {
586                         $includeList .= basename($classFile) . '<br />' . PHP_EOL;
587                 } // END - foreach
588
589                 // And return it
590                 return $includeList;
591         }
592
593 }