3 namespace Org\Mxchange\CoreFramework\Loader;
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
7 use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
10 use \InvalidArgumentException;
11 use \RecursiveDirectoryIterator;
12 use \RecursiveIteratorIterator;
16 * This class loads class include files with a specific prefix and suffix
18 * @author Roland Haeder <webmaster@shipsimu.org>
20 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2022 Core Developer Team
21 * @license GNU GPL 3.0 or any newer version
22 * @link http://www.shipsimu.org
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.
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.
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/>.
37 * ----------------------------------
39 * - This class loader is now 100% singleton, no other instance is really
40 * required, therefore the factory method can be removed safely
41 * - renamed initLoader() to initClassLoader()
42 * - An instance of a FrameworkConfiguration is no longer set here as this
43 * violated the rule that there shall be no instance set of that class
44 * - .htaccess is marked as deprecated as this should be no longer done
45 * - scanClassPath() is now protected, please use other scan*() methods
47 * - Namespace scheme Project\Package[\SubPackage...] is fully supported and
48 * throws an InvalidArgumentException if not present. The last part will be
49 * always the class' name.
51 * - Some comments improved, other minor improvements
53 * - Constructor is now empty and factory method 'createClassLoader' is created
54 * - renamed loadClasses to scanClassPath
55 * - Added initLoader()
57 * - ClassLoader rewritten to PHP SPL's own RecursiveIteratorIterator class
59 * - loadClasses rewritten to fix some notices
62 * ----------------------------------
64 final class ClassLoader {
66 * Instance of this class
68 private static $selfInstance = NULL;
71 * Cached configuration entry 'developer_mode_enabled'
73 private static $developerModeEnabled = false;
76 * Array with all valid but pending for loading file names (class,
77 * interfaces, traits must start with below prefix).
79 private $pendingFiles = [];
82 * List of loaded classes
84 private $loadedClasses = [];
87 * Suffix with extension for all class files
89 private $prefix = 'class_';
92 * Suffix with extension for all class files
94 private $suffix = '.php';
97 * A list for directory names (no leading/trailing slashes!) which not be scanned by the path scanner
100 private $ignoreList = [];
103 * Debug this class loader? (true = yes, false = no)
105 private $debug = false;
108 * Whether the file list is cached
110 private $listCached = false;
113 * Wethe class content has been cached
115 private $classesCached = false;
118 * SplFileInfo for the list cache
120 private $listCacheFile = NULL;
123 * SplFileInfo for class content
125 private $classCacheFile = NULL;
128 * Counter for loaded include files
133 * By default the class loader is strict with naming-convention check
135 private static $strictNamingConvention = true;
138 * Framework/application paths for classes, etc.
140 private static $frameworkPaths = [
141 'classes', // Classes
142 'exceptions', // Exceptions
143 'interfaces', // Interfaces
144 'middleware', // The middleware
149 * Registered paths where test classes can be found. These are all relative
152 private static $testPaths = [];
155 * The protected constructor. Please use the factory method below, or use
156 * getSelfInstance() for singleton
160 private function __construct () {
161 // Cache config entry
162 self::$developerModeEnabled = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('developer_mode_enabled');
166 * The destructor makes it sure all caches got flushed
170 public function __destruct () {
171 // Skip here if dev-mode
172 if (self::$developerModeEnabled) {
176 // Skip here if already cached
177 if ($this->listCached === false) {
178 // Writes the cache file of our list away
179 $cacheContent = json_encode($this->pendingFiles);
181 // Open cache instance
182 $fileObject = $this->listCacheFile->openFile('w');
184 // And write whole list
185 $fileObject->fwrite($cacheContent);
188 // Skip here if already cached
189 if ($this->classesCached === false) {
190 // Generate a full-cache of all classes
192 foreach (array_keys($this->loadedClasses) as $fileInstance) {
194 $fileObject = $fileInstance->openFile('r');
197 // @TODO Add some uglifying code (compress) here
198 $cacheContent .= $fileObject->fread($fileInstance->getSize());
202 $fileObject = $this->classCacheFile->openFile('w');
205 $fileObject->fwrite($cacheContent);
210 * Scans for all framework classes, exceptions and interfaces.
214 public static function scanFrameworkClasses () {
215 // Get loader instance
216 //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
217 $loaderInstance = self::getSelfInstance();
219 // "Cache" configuration instance and framework base path
220 $configInstance = FrameworkBootstrap::getConfigurationInstance();
221 $frameworkBasePath = $configInstance->getConfigEntry('framework_base_path');
224 //* NOISY-DEBUG: */ printf('[%s:%d]: frameworkBasePath=%s,self::$frameworkPaths()=%d,' . PHP_EOL, __METHOD__, __LINE__, $frameworkBasePath, count(self::$frameworkPaths));
225 foreach (self::$frameworkPaths as $shortPath) {
226 // Generate full path from it
227 //* NOISY-DEBUG: */ printf('[%s:%d]: shortPath[%s]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype($shortPath), $shortPath);
228 $realPathName = realpath(sprintf(
236 // Is it not false and accessible?
237 //* NOISY-DEBUG: */ printf('[%s:%d]: realPathName[%s]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype($realPathName), $realPathName);
238 if (is_bool($realPathName)) {
239 // Skip this, it is not accessible
241 } elseif (!is_readable($realPathName)) {
242 // @TODO Throw exception instead of break
246 // Try to load the framework classes
247 $loaderInstance->scanClassPath($realPathName);
251 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
255 * Scans for application's classes, etc.
259 public static function scanApplicationClasses () {
260 // Get loader instance
261 //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
262 $loaderInstance = self::getSelfInstance();
264 // "Cache" configuration instance
265 $configInstance = FrameworkBootstrap::getConfigurationInstance();
267 // Load all classes for the application
268 foreach (self::$frameworkPaths as $shortPath) {
270 //* NOISY-DEBUG: */ printf('[%s:%d]: shortPath=%s' . PHP_EOL, __METHOD__, __LINE__, $shortPath);
271 $pathName = realpath(sprintf(
273 $configInstance->getConfigEntry('application_base_path'),
275 FrameworkBootstrap::getDetectedApplicationName(),
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);
289 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
293 * Scans for test classes, etc.
297 public static function scanTestsClasses () {
298 // "Cache" configuration instance
299 //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
300 $configInstance = FrameworkBootstrap::getConfigurationInstance();
302 // Load all classes for the application
303 foreach (self::$testPaths as $shortPath) {
304 // Construct path name
305 //* NOISY-DEBUG: */ printf('[%s:%d]: shortPath=%s' . PHP_EOL, __METHOD__, __LINE__, $shortPath);
308 $configInstance->getConfigEntry('root_base_path'),
314 //* NOISY-DEBUG: */ printf('[%s:%d]: pathName[%s]=%s - BEFORE!' . PHP_EOL, __METHOD__, __LINE__, gettype($pathName), $pathName);
315 $realPathName = realpath($pathName);
317 // Is the path readable?
318 //* NOISY-DEBUG: */ printf('[%s:%d]: realPathName[%s]=%s - AFTER!' . PHP_EOL, __METHOD__, __LINE__, gettype($realPathName), $realPathName);
319 if ((is_dir($realPathName)) && (is_readable($realPathName))) {
320 // Try to load the application classes
321 ClassLoader::getSelfInstance()->scanClassPath($realPathName);
326 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
330 * Enables or disables strict naming-convention tests on class loading
332 * @param $strictNamingConvention Whether to strictly check naming-convention
335 public static function enableStrictNamingConventionCheck (bool $strictNamingConvention = true) {
336 self::$strictNamingConvention = $strictNamingConvention;
340 * Registeres given relative path where test classes reside. For regular
341 * framework uses, they should not be loaded (and used).
343 * @param $relativePath Relative path to test classes
345 * @throws InvalidArgumentException If a parameter is invalid
347 public static function registerTestsPath (string $relativePath) {
348 // Validate parameter
349 if (empty($relativePath)) {
350 // Should not be empty
351 throw new InvalidArgumentException('Parameter "relativePath" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
355 //* NOISY-DEBUG: */ printf('[%s:%d]: relativePath=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $relativePath);
356 self::$testPaths[$relativePath] = $relativePath;
359 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
365 * @param $className Name of the class to load
367 * @throws InvalidArgumentException If the class' name does not contain a namespace: Tld\Domain\Project is AT LEAST recommended!
369 public static function autoLoad (string $className) {
370 // Validate parameter
371 //* NOISY-DEBUG: */ printf('[%s:%d] className=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $className);
372 if (empty($className)) {
373 // Should not be empty
374 throw new InvalidArgumentException('Parameter "className" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
377 // The class name MUST be at least Tld\Domain\Project\Package\SomeFooBar so split at them
378 $classNameParts = explode("\\", $className);
380 // At least 3 parts should be there
381 //* NOISY-DEBUG: */ printf('[%s:%d]: self::strictNamingConvention=%d,classNameParts()=%d' . PHP_EOL, __METHOD__, __LINE__, intval(self::$strictNamingConvention), count($classNameParts));
382 if ((self::$strictNamingConvention === true) && (count($classNameParts) < 5)) {
383 // Namespace scheme is: Tld\Domain\Project\Package[\SubPackage...]
384 throw new InvalidArgumentException(sprintf('Class name "%s" is not conform to naming-convention: Tld\Domain\Project\Package[\SubPackage...]\SomeFooBar', $className));
387 // Try to include this class
388 //* NOISY-DEBUG: */ printf('[%s:%d]: Calling self->loadClassFile(%s) ...' . PHP_EOL, __METHOD__, __LINE__, $className);
389 self::getSelfInstance()->loadClassFile($className);
392 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
396 * Singleton getter for an instance of this class
398 * @return $selfInstance A singleton instance of this class
400 public static final function getSelfInstance () {
401 // Is the instance there?
402 if (is_null(self::$selfInstance)) {
403 // Get a new one and initialize it
404 self::$selfInstance = new ClassLoader();
405 self::$selfInstance->initClassLoader();
408 // Return the instance
409 return self::$selfInstance;
413 * Getter for total include counter
415 * @return $total Total loaded include files
417 public final function getTotal () {
422 * Getter for a printable list of included main/interfaces/exceptions
424 * @param $includeList A printable include list
426 public function getPrintableIncludeList () {
429 foreach ($this->loadedClasses as $classFile) {
430 $includeList .= basename($classFile) . '<br />' . PHP_EOL;
438 * Scans recursively a local path for class files which must have a prefix and a suffix as given by $this->suffix and $this->prefix
440 * @param $basePath The relative base path to 'framework_base_path' constant for all classes
441 * @param $ignoreList An optional list (array forced) of directory and file names which shall be ignored
443 * @throws InvalidArgumentException If a parameter is invalid
445 protected function scanClassPath (string $basePath, array $ignoreList = [] ) {
446 // Is a list has been restored from cache, don't read it again
447 //* NOISY-DEBUG: */ printf('[%s:%d] basePath=%s,ignoreList()=%d - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $basePath, count($ignoreList));
448 if (empty($basePath)) {
450 throw new InvalidArgumentException('Parameter "basePath" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
451 } elseif ($this->listCached === true) {
453 //* NOISY-DEBUG: */ printf('[%s:%d] this->listCache=true - EXIT!' . PHP_EOL, __METHOD__, __LINE__);
457 // Keep it in class for later usage, but flip index<->value
458 $this->ignoreList = array_flip($ignoreList);
461 * Set base directory which holds all our classes, an absolute path
462 * should be used here so is_dir(), is_file() and so on will always
463 * find the correct files and dirs.
465 $basePath2 = realpath($basePath);
467 // If the basePath is false it is invalid
468 //* NOISY-DEBUG: */ printf('[%s:%d] basePath2[%s]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype($basePath2), $basePath2);
469 if ($basePath2 === false) {
470 /* @TODO: Do not exit here. */
471 exit(__METHOD__ . ': Cannot read ' . $basePath . ' !' . PHP_EOL);
474 $basePath = $basePath2;
477 // Get a new iterator
478 //* NOISY-DEBUG: */ printf('[%s:%d] basePath=%s' . PHP_EOL, __METHOD__, __LINE__, $basePath);
479 $iteratorInstance = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($basePath), RecursiveIteratorIterator::CHILD_FIRST);
482 while ($iteratorInstance->valid()) {
484 $currentEntry = $iteratorInstance->current();
486 // Get filename from iterator which is the class' name (according naming-convention)
487 $fileName = $currentEntry->getFilename();
489 // Current entry must be a file, not smaller than 100 bytes and not on ignore list
490 if (!$currentEntry->isFile() || isset($this->ignoreList[$fileName]) || $currentEntry->getSize() < 100) {
491 // Advance to next entry
492 $iteratorInstance->next();
494 // Skip non-file entries
495 //* NOISY-DEBUG: */ printf('[%s:%d] SKIP: fileName=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
499 // Is this file wanted?
500 //* NOISY-DEBUG: */ printf('[%s:%d] FOUND: fileName=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
501 if ((substr($fileName, 0, strlen($this->prefix)) == $this->prefix) && (substr($fileName, -strlen($this->suffix), strlen($this->suffix)) == $this->suffix)) {
502 // Add it to the list
503 //* NOISY-DEBUG: */ printf('[%s:%d] ADD: fileName=%s,currentEntry=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName, $currentEntry);
504 $this->pendingFiles[$fileName] = $currentEntry;
507 //* NOISY-DEBUG: */ printf('[%s:%d] NOT ADDED: fileName=%s,currentEntry=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName, $currentEntry);
510 // Advance to next entry
511 //* NOISY-DEBUG: */ printf('[%s:%d] NEXT: fileName=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
512 $iteratorInstance->next();
516 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
520 * Initializes our loader class
524 private function initClassLoader () {
525 // Construct the FQFN for the cache
526 if (!self::$developerModeEnabled) {
527 // Init cache instances
528 $this->listCacheFile = new SplFileInfo(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . 'list-' . FrameworkBootstrap::getDetectedApplicationName() . '.cache');
529 $this->classCacheFile = new SplFileInfo(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . 'class-' . FrameworkBootstrap::getDetectedApplicationName() . '.cache');
532 // Set suffix and prefix from configuration
533 $this->suffix = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('class_suffix');
534 $this->prefix = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('class_prefix');
537 self::$selfInstance = $this;
539 // Skip here if no dev-mode
540 if (self::$developerModeEnabled) {
544 // Is the cache there?
545 if (FrameworkBootstrap::isReadableFile($this->listCacheFile)) {
546 // Load and convert it
547 $this->pendingFiles = json_decode(file_get_contents($this->listCacheFile->getPathname()));
549 // List has been restored from cache!
550 $this->listCached = true;
553 // Does the class cache exist?
554 if (FrameworkBootstrap::isReadableFile($this->classCacheFile)) {
556 FrameworkBootstrap::loadInclude($this->classCacheFile);
558 // Mark the class cache as loaded
559 $this->classesCached = true;
564 * Tries to find the given class in our list. It will ignore already loaded
565 * (to the program available) class/interface/trait files. But you SHOULD
566 * save below "expensive" code by pre-checking this->loadedClasses[], if
569 * @param $className The class that shall be loaded
572 private function loadClassFile (string $className) {
573 // The class name should contain at least 2 back-slashes, so split at them
574 //* NOISY-DEBUG: */ printf('[%s:%d] className=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $className);
575 $classNameParts = explode("\\", $className);
578 $shortClassName = array_pop($classNameParts);
580 // Create a name with prefix and suffix
581 $fileName = sprintf('%s%s%s', $this->prefix, $shortClassName, $this->suffix);
583 // Now look it up in our index
584 //* NOISY-DEBUG: */ printf('[%s:%d] ISSET: fileName=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
585 if ((isset($this->pendingFiles[$fileName])) && (!isset($this->loadedClasses[$this->pendingFiles[$fileName]->getPathname()]))) {
586 // File is found and not loaded so load it only once
587 //* NOISY-DEBUG: */ printf('[%s:%d] LOAD: fileName=%s - START' . PHP_EOL, __METHOD__, __LINE__, $fileName);
588 FrameworkBootstrap::loadInclude($this->pendingFiles[$fileName]);
589 //* NOISY-DEBUG: */ printf('[%s:%d] LOAD: fileName=%s - END' . PHP_EOL, __METHOD__, __LINE__, $fileName);
591 // Count this loaded class/interface/exception
594 // Mark this class as loaded for other purposes than loading it.
595 $this->loadedClasses[$this->pendingFiles[$fileName]->getPathname()] = true;
597 // Remove it from classes list so it won't be found twice.
598 //* NOISY-DEBUG: */ printf('[%s:%d] UNSET: fileName=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
599 unset($this->pendingFiles[$fileName]);
601 // Developer mode excludes caching (better debugging)
602 if (!self::$developerModeEnabled) {
604 //* NOISY-DEBUG: */ printf('[%s:%d] classesCached=false' . PHP_EOL, __METHOD__, __LINE__);
605 $this->classesCached = false;
609 //* NOISY-DEBUG: */ printf('[%s:%d] 404: fileName=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
613 //* NOISY-DEBUG: */ printf('[%s:%d] EXIT!' . PHP_EOL, __METHOD__, __LINE__);