Continued:
[core.git] / framework / loader / class_ClassLoader.php
1 <?php
2 // Own namespace
3 namespace CoreFramework\Loader;
4
5 // Import framework stuff
6 use CoreFramework\Bootstrap\FrameworkBootstrap;
7 use CoreFramework\Configuration\FrameworkConfiguration;
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 $strictNamingConvention = 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                 $configInstance = 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                         $realPathName = realpath(sprintf(
219                                 '%smain%s%s%s',
220                                 $configInstance->getConfigEntry('framework_base_path'),
221                                 DIRECTORY_SEPARATOR,
222                                 $shortPath,
223                                 DIRECTORY_SEPARATOR
224                         ));
225
226                         // Debug message
227                         //* NOISY-DEBUG: */ printf('[%s:%d]: realPathName=%s' . PHP_EOL, __METHOD__, __LINE__, $realPathName);
228
229                         // Is it not false and accessible?
230                         if (is_bool($realPathName)) {
231                                 // Skip this
232                                 continue;
233                         } elseif (!is_readable($realPathName)) {
234                                 // @TODO Throw exception instead of break
235                                 break;
236                         }
237
238                         // Try to load the framework classes
239                         $loaderInstance->scanClassPath($realPathName);
240                 } // END - foreach
241
242                 // Trace message
243                 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
244         }
245
246         /**
247          * Scans for application's classes, etc.
248          *
249          * @return      void
250          */
251         public static function scanApplicationClasses () {
252                 // Trace message
253                 //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
254
255                 // Get loader instance
256                 $loaderInstance = self::getSelfInstance();
257
258                 // Get config instance
259                 $configInstance = FrameworkConfiguration::getSelfInstance();
260
261                 // Load all classes for the application
262                 foreach (self::$frameworkPaths as $shortPath) {
263                         // Debug message
264                         //* NOISY-DEBUG: */ printf('[%s:%d]: shortPath=%s' . PHP_EOL, __METHOD__, __LINE__, $shortPath);
265
266                         // Create path name
267                         $pathName = realpath(sprintf(
268                                 '%s%s%s%s%s',
269                                 $configInstance->getConfigEntry('application_base_path'),
270                                 DIRECTORY_SEPARATOR,
271                                 $configInstance->getConfigEntry('detected_app_name'),
272                                 DIRECTORY_SEPARATOR,
273                                 $shortPath
274                         ));
275
276                         // Debug message
277                         //* NOISY-DEBUG: */ printf('[%s:%d]: pathName[%s]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype($pathName), $pathName);
278
279                         // Is the path readable?
280                         if (is_dir($pathName)) {
281                                 // Try to load the application classes
282                                 $loaderInstance->scanClassPath($pathName);
283                         } // END - if
284                 } // END - foreach
285
286                 // Trace message
287                 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
288         }
289
290         /**
291          * Scans for test classes, etc.
292          *
293          * @return      void
294          */
295         public static function scanTestsClasses () {
296                 // Trace message
297                 //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
298
299                 // Get config instance
300                 $configInstance = FrameworkConfiguration::getSelfInstance();
301
302                 // Load all classes for the application
303                 foreach (self::$testPaths as $shortPath) {
304                         // Debug message
305                         //* NOISY-DEBUG: */ printf('[%s:%d]: shortPath=%s' . PHP_EOL, __METHOD__, __LINE__, $shortPath);
306
307                         // Construct path name
308                         $pathName = sprintf(
309                                 '%s%s%s',
310                                 $configInstance->getConfigEntry('root_base_path'),
311                                 DIRECTORY_SEPARATOR,
312                                 $shortPath
313                         );
314
315                         // Debug message
316                         //* NOISY-DEBUG: */ printf('[%s:%d]: pathName[%s]=%s - BEFORE!' . PHP_EOL, __METHOD__, __LINE__, gettype($pathName), $pathName);
317
318                         // Try to find it
319                         $realPathName = realpath($pathName);
320
321                         // Debug message
322                         //* NOISY-DEBUG: */ printf('[%s:%d]: realPathName[%s]=%s - AFTER!' . PHP_EOL, __METHOD__, __LINE__, gettype($realPathName), $realPathName);
323
324                         // Is the path readable?
325                         if ((is_dir($realPathName)) && (is_readable($realPathName))) {
326                                 // Try to load the application classes
327                                 ClassLoader::getSelfInstance()->scanClassPath($realPathName);
328                         } // END - if
329                 } // END - foreach
330
331                 // Trace message
332                 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
333         }
334
335         /**
336          * Enables or disables strict naming-convention tests on class loading
337          *
338          * @param       $strictNamingConvention Whether to strictly check naming-convention
339          * @return      void
340          */
341         public static function enableStrictNamingConventionCheck ($strictNamingConvention = true) {
342                 self::$strictNamingConvention = $strictNamingConvention;
343         }
344
345         /**
346          * Registeres given relative path where test classes reside. For regular
347          * framework uses, they should not be loaded (and used).
348          *
349          * @param       $relativePath   Relative path to test classes
350          * @return      void
351          */
352         public static function registerTestsPath ($relativePath) {
353                 // Trace message
354                 //* NOISY-DEBUG: */ printf('[%s:%d]: relativePath=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $relativePath);
355
356                 // "Register" it
357                 self::$testPaths[$relativePath] = $relativePath;
358
359                 // Trace message
360                 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
361         }
362
363         /**
364          * Autoload-function
365          *
366          * @param       $className      Name of the class to load
367          * @return      void
368          */
369         public static function autoLoad ($className) {
370                 // Trace message
371                 //* NOISY-DEBUG: */ printf('[%s:%d]: className=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $className);
372
373                 // Try to include this class
374                 self::getSelfInstance()->loadClassFile($className);
375
376                 // Trace message
377                 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
378         }
379
380         /**
381          * Singleton getter for an instance of this class
382          *
383          * @return      $selfInstance   A singleton instance of this class
384          */
385         public static final function getSelfInstance () {
386                 // Is the instance there?
387                 if (is_null(self::$selfInstance)) {
388                         // Get a new one
389                         self::$selfInstance = ClassLoader::createClassLoader(FrameworkConfiguration::getSelfInstance());
390                 } // END - if
391
392                 // Return the instance
393                 return self::$selfInstance;
394         }
395
396         /**
397          * Scans recursively a local path for class files which must have a prefix and a suffix as given by $this->suffix and $this->prefix
398          *
399          * @param       $basePath               The relative base path to 'framework_base_path' constant for all classes
400          * @param       $ignoreList             An optional list (array forced) of directory and file names which shall be ignored
401          * @return      void
402          */
403         public function scanClassPath ($basePath, array $ignoreList = array() ) {
404                 // Is a list has been restored from cache, don't read it again
405                 if ($this->listCached === true) {
406                         // Abort here
407                         return;
408                 } // END - if
409
410                 // Keep it in class for later usage
411                 $this->ignoreList = $ignoreList;
412
413                 /*
414                  * Ignore .htaccess by default as it is for protection of directories
415                  * on Apache servers.
416                  */
417                 array_push($ignoreList, '.htaccess');
418
419                 /*
420                  * Set base directory which holds all our classes, an absolute path
421                  * should be used here so is_dir(), is_file() and so on will always
422                  * find the correct files and dirs.
423                  */
424                 $basePath2 = realpath($basePath);
425
426                 // If the basePath is false it is invalid
427                 if ($basePath2 === false) {
428                         /* @TODO: Do not exit here. */
429                         exit(__METHOD__ . ': Cannot read ' . $basePath . ' !' . PHP_EOL);
430                 } else {
431                         // Set base path
432                         $basePath = $basePath2;
433                 }
434
435                 // Get a new iterator
436                 //* NOISY-DEBUG: */ printf('[%s:%d] basePath=%s' . PHP_EOL, __METHOD__, __LINE__, $basePath);
437                 $iteratorInstance = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($basePath), RecursiveIteratorIterator::CHILD_FIRST);
438
439                 // Load all entries
440                 while ($iteratorInstance->valid()) {
441                         // Get current entry
442                         $currentEntry = $iteratorInstance->current();
443
444                         // Get filename from iterator which is the class' name (according naming-convention)
445                         $fileName = $currentEntry->getFileName();
446
447                         // Get the "FQFN" (path and file name)
448                         $fqfn = $currentEntry->getRealPath();
449
450                         // Current entry must be a file, not smaller than 100 bytes and not on ignore list
451                         if ((!$currentEntry->isFile()) || (in_array($fileName, $this->ignoreList)) || (filesize($fqfn) < 100)) {
452                                 // Advance to next entry
453                                 $iteratorInstance->next();
454
455                                 // Skip non-file entries
456                                 //* NOISY-DEBUG: */ printf('[%s:%d] SKIP: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
457                                 continue;
458                         } // END - if
459
460                         // Is this file wanted?
461                         //* NOISY-DEBUG: */ printf('[%s:%d] FOUND: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
462                         if ((substr($fileName, 0, strlen($this->prefix)) == $this->prefix) && (substr($fileName, -strlen($this->suffix), strlen($this->suffix)) == $this->suffix)) {
463                                 // Add it to the list
464                                 //* NOISY-DEBUG: */ printf('[%s:%d] ADD: %s,fqfn=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName, $fqfn);
465                                 $this->foundClasses[$fileName] = $fqfn;
466                         } else {
467                                 // Not added
468                                 //* NOISY-DEBUG: */ printf('[%s:%d] NOT ADDED: %s,fqfn=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName, $fqfn);
469                         }
470
471                         // Advance to next entry
472                         //* NOISY-DEBUG: */ printf('[%s:%d] NEXT: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
473                         $iteratorInstance->next();
474                 } // END - while
475         }
476
477         /**
478          * Initializes our loader class
479          *
480          * @param       $configInstance Configuration class instance
481          * @return      void
482          */
483         private function initLoader (FrameworkConfiguration $configInstance) {
484                 // Set configuration instance
485                 $this->configInstance = $configInstance;
486
487                 // Construct the FQFN for the cache
488                 if (!defined('DEVELOPER')) {
489                         $this->listCacheFQFN  = $this->configInstance->getConfigEntry('local_database_path') . 'list-' . $this->configInstance->getConfigEntry('detected_app_name') . '.cache';
490                         $this->classCacheFQFN = $this->configInstance->getConfigEntry('local_database_path') . 'class-' . $this->configInstance->getConfigEntry('detected_app_name') . '.cache';
491                 } // END - if
492
493                 // Set suffix and prefix from configuration
494                 $this->suffix = $configInstance->getConfigEntry('class_suffix');
495                 $this->prefix = $configInstance->getConfigEntry('class_prefix');
496
497                 // Set own instance
498                 self::$selfInstance = $this;
499
500                 // Skip here if no dev-mode
501                 if (defined('DEVELOPER')) {
502                         return;
503                 } // END - if
504
505                 // IS the cache there?
506                 if (FrameworkBootstrap::isReadableFile($this->listCacheFQFN)) {
507                         // Load and convert it
508                         $this->foundClasses = json_decode(file_get_contents($this->listCacheFQFN));
509
510                         // List has been restored from cache!
511                         $this->listCached = true;
512                 } // END - if
513
514                 // Does the class cache exist?
515                 if (FrameworkBootstrap::isReadableFile($this->listCacheFQFN)) {
516                         // Then include it
517                         FrameworkBootstrap::loadInclude($this->classCacheFQFN);
518
519                         // Mark the class cache as loaded
520                         $this->classesCached = true;
521                 } // END - if
522         }
523
524         /**
525          * Tries to find the given class in our list. This method ignores silently
526          * missing classes or interfaces. So if you use class_exists() this method
527          * does not interrupt your program.
528          *
529          * @param       $className      The class that shall be loaded
530          * @return      void
531          * @throws      InvalidArgumentException        If strict-checking is enabled and class name is not following naming-convention
532          */
533         private function loadClassFile ($className) {
534                 // Trace message
535                 //* NOISY-DEBUG: */ printf('[%s:%d] className=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $className);
536
537                 // The class name should contain at least 2 back-slashes, so split at them
538                 $classNameParts = explode("\\", $className);
539
540                 // At least 3 parts should be there
541                 if ((self::$strictNamingConvention === true) && (count($classNameParts) < 3)) {
542                         // Namespace scheme is: Project\Package[\SubPackage...]
543                         throw new InvalidArgumentException(sprintf('Class name "%s" is not conform to naming-convention: Project\Package[\SubPackage...]\SomeFooBar', $className));
544                 } // END - if
545
546                 // Get last element
547                 $shortClassName = array_pop($classNameParts);
548
549                 // Create a name with prefix and suffix
550                 $fileName = $this->prefix . $shortClassName . $this->suffix;
551
552                 // Now look it up in our index
553                 //* NOISY-DEBUG: */ printf('[%s:%d] ISSET: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
554                 if ((isset($this->foundClasses[$fileName])) && (!isset($this->loadedClasses[$this->foundClasses[$fileName]]))) {
555                         // File is found and not loaded so load it only once
556                         //* NOISY-DEBUG: */ printf('[%s:%d] LOAD: %s - START' . PHP_EOL, __METHOD__, __LINE__, $fileName);
557                         FrameworkBootstrap::loadInclude($this->foundClasses[$fileName]);
558                         //* NOISY-DEBUG: */ printf('[%s:%d] LOAD: %s - END' . PHP_EOL, __METHOD__, __LINE__, $fileName);
559
560                         // Count this loaded class/interface/exception
561                         $this->total++;
562
563                         // Mark this class as loaded for other purposes than loading it.
564                         $this->loadedClasses[$this->foundClasses[$fileName]] = true;
565
566                         // Remove it from classes list so it won't be found twice.
567                         //* NOISY-DEBUG: */ printf('[%s:%d] UNSET: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
568                         unset($this->foundClasses[$fileName]);
569
570                         // Developer mode excludes caching (better debugging)
571                         if (!defined('DEVELOPER')) {
572                                 // Reset cache
573                                 //* NOISY-DEBUG: */ printf('[%s:%d] classesCached=false' . PHP_EOL, __METHOD__, __LINE__);
574                                 $this->classesCached = false;
575                         } // END - if
576                 } else {
577                         // Not found
578                         //* NOISY-DEBUG: */ printf('[%s:%d] 404: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
579                 }
580         }
581
582         /**
583          * Getter for total include counter
584          *
585          * @return      $total  Total loaded include files
586          */
587         public final function getTotal () {
588                 return $this->total;
589         }
590
591         /**
592          * Getter for a printable list of included main/interfaces/exceptions
593          *
594          * @param       $includeList    A printable include list
595          */
596         public function getPrintableIncludeList () {
597                 // Prepare the list
598                 $includeList = '';
599                 foreach ($this->loadedClasses as $classFile) {
600                         $includeList .= basename($classFile) . '<br />' . PHP_EOL;
601                 } // END - foreach
602
603                 // And return it
604                 return $includeList;
605         }
606
607 }