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 or path not found
347 public static function registerTestsPath (string $relativePath) {
348 // Validate parameter
349 //* NOISY-DEBUG: */ printf('[%s:%d]: relativePath=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $relativePath);
350 if (empty($relativePath)) {
351 // Should not be empty
352 throw new InvalidArgumentException('Parameter "relativePath" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
355 // Get real path from it
356 $fullQualifiedPath = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('root_base_path') . $relativePath;
359 //* NOISY-DEBUG: */ printf('[%s:%d]: fullQualifiedPath=%s' . PHP_EOL, __METHOD__, __LINE__, $fullQualifiedPath);
360 if (!is_dir($fullQualifiedPath)) {
362 throw new InvalidArgumentException(sprintf('fullQualifiedPath=%s cannot be found', $fullQualifiedPath));
363 } elseif (!is_readable($fullQualifiedPath)) {
365 throw new InvalidArgumentException(sprintf('fullQualifiedPath=%s is not readable', $fullQualifiedPath));
369 //* NOISY-DEBUG: */ printf('[%s:%d]: Adding relativePath=%s ...' . PHP_EOL, __METHOD__, __LINE__, $relativePath);
370 self::$testPaths[$relativePath] = $relativePath;
373 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
379 * @param $className Name of the class to load
381 * @throws InvalidArgumentException If the class' name does not contain a namespace: Tld\Domain\Project is AT LEAST recommended!
383 public static function autoLoad (string $className) {
384 // Validate parameter
385 //* NOISY-DEBUG: */ printf('[%s:%d] className=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $className);
386 if (empty($className)) {
387 // Should not be empty
388 throw new InvalidArgumentException('Parameter "className" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
391 // The class name MUST be at least Tld\Domain\Project\Package\SomeFooBar so split at them
392 $classNameParts = explode("\\", $className);
394 // At least 3 parts should be there
395 //* NOISY-DEBUG: */ printf('[%s:%d]: self::strictNamingConvention=%d,classNameParts()=%d' . PHP_EOL, __METHOD__, __LINE__, intval(self::$strictNamingConvention), count($classNameParts));
396 if ((self::$strictNamingConvention === true) && (count($classNameParts) < 5)) {
397 // Namespace scheme is: Tld\Domain\Project\Package[\SubPackage...]
398 throw new InvalidArgumentException(sprintf('Class name "%s" is not conform to naming-convention: Tld\Domain\Project\Package[\SubPackage...]\SomeFooBar', $className));
401 // Try to include this class
402 //* NOISY-DEBUG: */ printf('[%s:%d]: Invoking self->loadClassFile(%s) ...' . PHP_EOL, __METHOD__, __LINE__, $className);
403 self::getSelfInstance()->loadClassFile($className);
406 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
410 * Singleton getter for an instance of this class
412 * @return $selfInstance A singleton instance of this class
414 public static final function getSelfInstance () {
415 // Is the instance there?
416 if (is_null(self::$selfInstance)) {
417 // Get a new one and initialize it
418 self::$selfInstance = new ClassLoader();
419 self::$selfInstance->initClassLoader();
422 // Return the instance
423 return self::$selfInstance;
427 * Getter for total include counter
429 * @return $total Total loaded include files
431 public final function getTotal () {
436 * Getter for a printable list of included main/interfaces/exceptions
438 * @param $includeList A printable include list
440 public function getPrintableIncludeList () {
443 foreach ($this->loadedClasses as $classFile) {
444 $includeList .= basename($classFile) . '<br />' . PHP_EOL;
452 * Scans recursively a local path for class files which must have a prefix and a suffix as given by $this->suffix and $this->prefix
454 * @param $basePath The relative base path to 'framework_base_path' constant for all classes
455 * @param $ignoreList An optional list (array forced) of directory and file names which shall be ignored
457 * @throws InvalidArgumentException If a parameter is invalid
459 protected function scanClassPath (string $basePath, array $ignoreList = [] ) {
460 // Is a list has been restored from cache, don't read it again
461 //* NOISY-DEBUG: */ printf('[%s:%d] basePath=%s,ignoreList()=%d - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $basePath, count($ignoreList));
462 if (empty($basePath)) {
464 throw new InvalidArgumentException('Parameter "basePath" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
465 } elseif ($this->listCached === true) {
467 //* NOISY-DEBUG: */ printf('[%s:%d] this->listCache=true - EXIT!' . PHP_EOL, __METHOD__, __LINE__);
471 // Keep it in class for later usage, but flip index<->value
472 $this->ignoreList = array_flip($ignoreList);
475 * Set base directory which holds all our classes, an absolute path
476 * should be used here so is_dir(), is_file() and so on will always
477 * find the correct files and dirs.
479 $basePath2 = realpath($basePath);
481 // If the basePath is false it is invalid
482 //* NOISY-DEBUG: */ printf('[%s:%d] basePath2[%s]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype($basePath2), $basePath2);
483 if ($basePath2 === false) {
484 /* @TODO: Do not exit here. */
485 exit(__METHOD__ . ': Cannot read ' . $basePath . ' !' . PHP_EOL);
488 $basePath = $basePath2;
491 // Get a new iterator
492 //* NOISY-DEBUG: */ printf('[%s:%d] basePath=%s' . PHP_EOL, __METHOD__, __LINE__, $basePath);
493 $iteratorInstance = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($basePath), RecursiveIteratorIterator::CHILD_FIRST);
496 while ($iteratorInstance->valid()) {
498 $currentEntry = $iteratorInstance->current();
500 // Get filename from iterator which is the class' name (according naming-convention)
501 $fileName = $currentEntry->getFilename();
503 // Current entry must be a file, not smaller than 100 bytes and not on ignore list
504 if (!$currentEntry->isFile() || isset($this->ignoreList[$fileName]) || $currentEntry->getSize() < 100) {
505 // Advance to next entry
506 $iteratorInstance->next();
508 // Skip non-file entries
509 //* NOISY-DEBUG: */ printf('[%s:%d] SKIP: fileName=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
513 // Is this file wanted?
514 //* NOISY-DEBUG: */ printf('[%s:%d] FOUND: fileName=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
515 if ((substr($fileName, 0, strlen($this->prefix)) == $this->prefix) && (substr($fileName, -strlen($this->suffix), strlen($this->suffix)) == $this->suffix)) {
516 // Add it to the list
517 //* NOISY-DEBUG: */ printf('[%s:%d] ADD: fileName=%s,currentEntry=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName, $currentEntry);
518 $this->pendingFiles[$fileName] = $currentEntry;
521 //* NOISY-DEBUG: */ printf('[%s:%d] NOT ADDED: fileName=%s,currentEntry=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName, $currentEntry);
524 // Advance to next entry
525 //* NOISY-DEBUG: */ printf('[%s:%d] NEXT: fileName=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
526 $iteratorInstance->next();
530 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
534 * Initializes our loader class
538 private function initClassLoader () {
539 // Construct the FQFN for the cache
540 if (!self::$developerModeEnabled) {
541 // Init cache instances
542 $this->listCacheFile = new SplFileInfo(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . 'list-' . FrameworkBootstrap::getDetectedApplicationName() . '.cache');
543 $this->classCacheFile = new SplFileInfo(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . 'class-' . FrameworkBootstrap::getDetectedApplicationName() . '.cache');
546 // Set suffix and prefix from configuration
547 $this->suffix = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('class_suffix');
548 $this->prefix = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('class_prefix');
551 self::$selfInstance = $this;
553 // Skip here if no dev-mode
554 if (self::$developerModeEnabled) {
558 // Is the cache there?
559 if (FrameworkBootstrap::isReadableFile($this->listCacheFile)) {
560 // Load and convert it
561 $this->pendingFiles = json_decode(file_get_contents($this->listCacheFile->getPathname()));
563 // List has been restored from cache!
564 $this->listCached = true;
567 // Does the class cache exist?
568 if (FrameworkBootstrap::isReadableFile($this->classCacheFile)) {
570 FrameworkBootstrap::loadInclude($this->classCacheFile);
572 // Mark the class cache as loaded
573 $this->classesCached = true;
578 * Tries to find the given class in our list. It will ignore already loaded
579 * (to the program available) class/interface/trait files. But you SHOULD
580 * save below "expensive" code by pre-checking this->loadedClasses[], if
583 * @param $className The class that shall be loaded
586 private function loadClassFile (string $className) {
587 // The class name should contain at least 2 back-slashes, so split at them
588 //* NOISY-DEBUG: */ printf('[%s:%d] className=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $className);
589 $classNameParts = explode("\\", $className);
592 $shortClassName = array_pop($classNameParts);
594 // Create a name with prefix and suffix
595 $fileName = sprintf('%s%s%s', $this->prefix, $shortClassName, $this->suffix);
597 // Now look it up in our index
598 //* NOISY-DEBUG: */ printf('[%s:%d] ISSET: fileName=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
599 if ((isset($this->pendingFiles[$fileName])) && (!isset($this->loadedClasses[$this->pendingFiles[$fileName]->getPathname()]))) {
600 // File is found and not loaded so load it only once
601 //* NOISY-DEBUG: */ printf('[%s:%d] LOAD: fileName=%s - START' . PHP_EOL, __METHOD__, __LINE__, $fileName);
602 FrameworkBootstrap::loadInclude($this->pendingFiles[$fileName]);
603 //* NOISY-DEBUG: */ printf('[%s:%d] LOAD: fileName=%s - END' . PHP_EOL, __METHOD__, __LINE__, $fileName);
605 // Count this loaded class/interface/exception
608 // Mark this class as loaded for other purposes than loading it.
609 $this->loadedClasses[$this->pendingFiles[$fileName]->getPathname()] = true;
611 // Remove it from classes list so it won't be found twice.
612 //* NOISY-DEBUG: */ printf('[%s:%d] UNSET: fileName=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
613 unset($this->pendingFiles[$fileName]);
615 // Developer mode excludes caching (better debugging)
616 if (!self::$developerModeEnabled) {
618 //* NOISY-DEBUG: */ printf('[%s:%d] classesCached=false' . PHP_EOL, __METHOD__, __LINE__);
619 $this->classesCached = false;
623 //* NOISY-DEBUG: */ printf('[%s:%d] 404: fileName=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
627 //* NOISY-DEBUG: */ printf('[%s:%d] EXIT!' . PHP_EOL, __METHOD__, __LINE__);