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