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