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