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