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