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