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