3 namespace Org\Mxchange\CoreFramework\Loader;
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
9 use \InvalidArgumentException;
10 use \RecursiveDirectoryIterator;
11 use \RecursiveIteratorIterator;
15 * This class loads class include files with a specific prefix and suffix
17 * @author Roland Haeder <webmaster@shipsimu.org>
19 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2022 Core Developer Team
20 * @license GNU GPL 3.0 or any newer version
21 * @link http://www.shipsimu.org
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.
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.
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/>.
36 * ----------------------------------
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
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.
50 * - Some comments improved, other minor improvements
52 * - Constructor is now empty and factory method 'createClassLoader' is created
53 * - renamed loadClasses to scanClassPath
54 * - Added initLoader()
56 * - ClassLoader rewritten to PHP SPL's own RecursiveIteratorIterator class
58 * - loadClasses rewritten to fix some notices
61 * ----------------------------------
63 final class ClassLoader {
65 * Instance of this class
67 private static $selfInstance = NULL;
70 * Cached configuration entry 'developer_mode_enabled'
72 private static $developerModeEnabled = false;
75 * Array with all valid but pending for loading file names (class,
76 * interfaces, traits must start with below prefix).
78 private $pendingFiles = [];
81 * List of loaded classes
83 private $loadedClasses = [];
86 * Suffix with extension for all class files
88 private $prefix = 'class_';
91 * Suffix with extension for all class files
93 private $suffix = '.php';
96 * A list for directory names (no leading/trailing slashes!) which not be scanned by the path scanner
99 private $ignoreList = [];
102 * Debug this class loader? (true = yes, false = no)
104 private $debug = false;
107 * Whether the file list is cached
109 private $listCached = false;
112 * Wethe class content has been cached
114 private $classesCached = false;
117 * SplFileInfo for the list cache
119 private $listCacheFile = NULL;
122 * SplFileInfo for class content
124 private $classCacheFile = NULL;
127 * Counter for loaded include files
132 * By default the class loader is strict with naming-convention check
134 private static $strictNamingConvention = true;
137 * Framework/application paths for classes, etc.
139 private static $frameworkPaths = [
140 'classes', // Classes
141 'exceptions', // Exceptions
142 'interfaces', // Interfaces
143 'middleware', // The middleware
148 * Registered paths where test classes can be found. These are all relative
151 private static $testPaths = [];
154 * The protected constructor. Please use the factory method below, or use
155 * getSelfInstance() for singleton
159 private function __construct () {
160 // Cache config entry
161 self::$developerModeEnabled = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('developer_mode_enabled');
165 * The destructor makes it sure all caches got flushed
169 public function __destruct () {
170 // Skip here if dev-mode
171 if (self::$developerModeEnabled) {
175 // Skip here if already cached
176 if ($this->listCached === false) {
177 // Writes the cache file of our list away
178 $cacheContent = json_encode($this->pendingFiles);
180 // Open cache instance
181 $fileObject = $this->listCacheFile->openFile('w');
183 // And write whole list
184 $fileObject->fwrite($cacheContent);
187 // Skip here if already cached
188 if ($this->classesCached === false) {
189 // Generate a full-cache of all classes
191 foreach (array_keys($this->loadedClasses) as $fileInstance) {
193 $fileObject = $fileInstance->openFile('r');
196 // @TODO Add some uglifying code (compress) here
197 $cacheContent .= $fileObject->fread($fileInstance->getSize());
201 $fileObject = $this->classCacheFile->openFile('w');
204 $fileObject->fwrite($cacheContent);
209 * Scans for all framework classes, exceptions and interfaces.
213 public static function scanFrameworkClasses () {
214 // Get loader instance
215 //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
216 $loaderInstance = self::getSelfInstance();
218 // "Cache" configuration instance and framework base path
219 $configInstance = FrameworkBootstrap::getConfigurationInstance();
220 $frameworkBasePath = $configInstance->getConfigEntry('framework_base_path');
223 //* NOISY-DEBUG: */ printf('[%s:%d]: frameworkBasePath=%s,self::$frameworkPaths()=%d,' . PHP_EOL, __METHOD__, __LINE__, $frameworkBasePath, count(self::$frameworkPaths));
224 foreach (self::$frameworkPaths as $shortPath) {
225 // Generate full path from it
226 //* NOISY-DEBUG: */ printf('[%s:%d]: shortPath[%s]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype($shortPath), $shortPath);
227 $realPathName = realpath(sprintf(
235 // Is it not false and accessible?
236 //* NOISY-DEBUG: */ printf('[%s:%d]: realPathName[%s]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype($realPathName), $realPathName);
237 if (is_bool($realPathName)) {
238 // Skip this, it is not accessible
240 } elseif (!is_readable($realPathName)) {
241 // @TODO Throw exception instead of break
245 // Try to load the framework classes
246 $loaderInstance->scanClassPath($realPathName);
250 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
254 * Scans for application's classes, etc.
258 public static function scanApplicationClasses () {
259 // Get loader instance
260 //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
261 $loaderInstance = self::getSelfInstance();
263 // "Cache" configuration instance
264 $configInstance = FrameworkBootstrap::getConfigurationInstance();
266 // Load all classes for the application
267 foreach (self::$frameworkPaths as $shortPath) {
269 //* NOISY-DEBUG: */ printf('[%s:%d]: shortPath=%s' . PHP_EOL, __METHOD__, __LINE__, $shortPath);
270 $pathName = realpath(sprintf(
272 $configInstance->getConfigEntry('application_base_path'),
274 FrameworkBootstrap::getDetectedApplicationName(),
279 // Is the path readable?
280 //* NOISY-DEBUG: */ printf('[%s:%d]: pathName[%s]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype($pathName), $pathName);
281 if (is_dir($pathName)) {
282 // Try to load the application classes
283 $loaderInstance->scanClassPath($pathName);
288 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
292 * Scans for test classes, etc.
296 public static function scanTestsClasses () {
297 // "Cache" configuration instance
298 //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
299 $configInstance = FrameworkBootstrap::getConfigurationInstance();
301 // Load all classes for the application
302 foreach (self::$testPaths as $shortPath) {
303 // Construct path name
304 //* NOISY-DEBUG: */ printf('[%s:%d]: shortPath=%s' . PHP_EOL, __METHOD__, __LINE__, $shortPath);
307 $configInstance->getConfigEntry('root_base_path'),
313 //* NOISY-DEBUG: */ printf('[%s:%d]: pathName[%s]=%s - BEFORE!' . PHP_EOL, __METHOD__, __LINE__, gettype($pathName), $pathName);
314 $realPathName = realpath($pathName);
316 // Is the path readable?
317 //* NOISY-DEBUG: */ printf('[%s:%d]: realPathName[%s]=%s - AFTER!' . PHP_EOL, __METHOD__, __LINE__, gettype($realPathName), $realPathName);
318 if ((is_dir($realPathName)) && (is_readable($realPathName))) {
319 // Try to load the application classes
320 ClassLoader::getSelfInstance()->scanClassPath($realPathName);
325 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
329 * Enables or disables strict naming-convention tests on class loading
331 * @param $strictNamingConvention Whether to strictly check naming-convention
334 public static function enableStrictNamingConventionCheck (bool $strictNamingConvention = true) {
335 self::$strictNamingConvention = $strictNamingConvention;
339 * Registeres given relative path where test classes reside. For regular
340 * framework uses, they should not be loaded (and used).
342 * @param $relativePath Relative path to test classes
344 * @throws InvalidArgumentException If a parameter is invalid
346 public static function registerTestsPath (string $relativePath) {
347 // Validate parameter
348 if (empty($relativePath)) {
349 // Should not be empty
350 throw new InvalidArgumentException('Parameter "relativePath" is empty');
354 //* NOISY-DEBUG: */ printf('[%s:%d]: relativePath=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $relativePath);
355 self::$testPaths[$relativePath] = $relativePath;
358 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
364 * @param $className Name of the class to load
366 * @throws InvalidArgumentException If the class' name does not contain a namespace: Tld\Domain\Project is AT LEAST recommended!
368 public static function autoLoad (string $className) {
369 // Validate parameter
370 //* NOISY-DEBUG: */ printf('[%s:%d] className=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $className);
371 if (empty($className)) {
372 // Should not be empty
373 throw new InvalidArgumentException('Parameter "className" is empty');
376 // The class name MUST be at least Tld\Domain\Project\Package\SomeFooBar so split at them
377 $classNameParts = explode("\\", $className);
379 // At least 3 parts should be there
380 //* NOISY-DEBUG: */ printf('[%s:%d]: self::strictNamingConvention=%d,classNameParts()=%d' . PHP_EOL, __METHOD__, __LINE__, intval(self::$strictNamingConvention), count($classNameParts));
381 if ((self::$strictNamingConvention === true) && (count($classNameParts) < 5)) {
382 // Namespace scheme is: Tld\Domain\Project\Package[\SubPackage...]
383 throw new InvalidArgumentException(sprintf('Class name "%s" is not conform to naming-convention: Tld\Domain\Project\Package[\SubPackage...]\SomeFooBar', $className));
386 // Try to include this class
387 //* NOISY-DEBUG: */ printf('[%s:%d]: Calling self->loadClassFile(%s) ...' . PHP_EOL, __METHOD__, __LINE__, $className);
388 self::getSelfInstance()->loadClassFile($className);
391 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
395 * Singleton getter for an instance of this class
397 * @return $selfInstance A singleton instance of this class
399 public static final function getSelfInstance () {
400 // Is the instance there?
401 if (is_null(self::$selfInstance)) {
402 // Get a new one and initialize it
403 self::$selfInstance = new ClassLoader();
404 self::$selfInstance->initClassLoader();
407 // Return the instance
408 return self::$selfInstance;
412 * Getter for total include counter
414 * @return $total Total loaded include files
416 public final function getTotal () {
421 * Getter for a printable list of included main/interfaces/exceptions
423 * @param $includeList A printable include list
425 public function getPrintableIncludeList () {
428 foreach ($this->loadedClasses as $classFile) {
429 $includeList .= basename($classFile) . '<br />' . PHP_EOL;
437 * Scans recursively a local path for class files which must have a prefix and a suffix as given by $this->suffix and $this->prefix
439 * @param $basePath The relative base path to 'framework_base_path' constant for all classes
440 * @param $ignoreList An optional list (array forced) of directory and file names which shall be ignored
442 * @throws InvalidArgumentException If a parameter is invalid
444 protected function scanClassPath (string $basePath, array $ignoreList = [] ) {
445 // Is a list has been restored from cache, don't read it again
446 //* NOISY-DEBUG: */ printf('[%s:%d] basePath=%s,ignoreList()=%d - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $basePath, count($ignoreList));
447 if (empty($basePath)) {
449 throw new InvalidArgumentException('Parameter "basePath" is empty');
450 } elseif ($this->listCached === true) {
452 //* NOISY-DEBUG: */ printf('[%s:%d] this->listCache=true - EXIT!' . PHP_EOL, __METHOD__, __LINE__);
456 // Keep it in class for later usage, but flip index<->value
457 $this->ignoreList = array_flip($ignoreList);
460 * Set base directory which holds all our classes, an absolute path
461 * should be used here so is_dir(), is_file() and so on will always
462 * find the correct files and dirs.
464 $basePath2 = realpath($basePath);
466 // If the basePath is false it is invalid
467 //* NOISY-DEBUG: */ printf('[%s:%d] basePath2[%s]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype($basePath2), $basePath2);
468 if ($basePath2 === false) {
469 /* @TODO: Do not exit here. */
470 exit(__METHOD__ . ': Cannot read ' . $basePath . ' !' . PHP_EOL);
473 $basePath = $basePath2;
476 // Get a new iterator
477 //* NOISY-DEBUG: */ printf('[%s:%d] basePath=%s' . PHP_EOL, __METHOD__, __LINE__, $basePath);
478 $iteratorInstance = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($basePath), RecursiveIteratorIterator::CHILD_FIRST);
481 while ($iteratorInstance->valid()) {
483 $currentEntry = $iteratorInstance->current();
485 // Get filename from iterator which is the class' name (according naming-convention)
486 $fileName = $currentEntry->getFilename();
488 // Current entry must be a file, not smaller than 100 bytes and not on ignore list
489 if (!$currentEntry->isFile() || isset($this->ignoreList[$fileName]) || $currentEntry->getSize() < 100) {
490 // Advance to next entry
491 $iteratorInstance->next();
493 // Skip non-file entries
494 //* NOISY-DEBUG: */ printf('[%s:%d] SKIP: fileName=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
498 // Is this file wanted?
499 //* NOISY-DEBUG: */ printf('[%s:%d] FOUND: fileName=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
500 if ((substr($fileName, 0, strlen($this->prefix)) == $this->prefix) && (substr($fileName, -strlen($this->suffix), strlen($this->suffix)) == $this->suffix)) {
501 // Add it to the list
502 //* NOISY-DEBUG: */ printf('[%s:%d] ADD: fileName=%s,currentEntry=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName, $currentEntry);
503 $this->pendingFiles[$fileName] = $currentEntry;
506 //* NOISY-DEBUG: */ printf('[%s:%d] NOT ADDED: fileName=%s,currentEntry=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName, $currentEntry);
509 // Advance to next entry
510 //* NOISY-DEBUG: */ printf('[%s:%d] NEXT: fileName=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
511 $iteratorInstance->next();
515 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
519 * Initializes our loader class
523 private function initClassLoader () {
524 // Construct the FQFN for the cache
525 if (!self::$developerModeEnabled) {
526 // Init cache instances
527 $this->listCacheFile = new SplFileInfo(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . 'list-' . FrameworkBootstrap::getDetectedApplicationName() . '.cache');
528 $this->classCacheFile = new SplFileInfo(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . 'class-' . FrameworkBootstrap::getDetectedApplicationName() . '.cache');
531 // Set suffix and prefix from configuration
532 $this->suffix = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('class_suffix');
533 $this->prefix = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('class_prefix');
536 self::$selfInstance = $this;
538 // Skip here if no dev-mode
539 if (self::$developerModeEnabled) {
543 // Is the cache there?
544 if (FrameworkBootstrap::isReadableFile($this->listCacheFile)) {
545 // Load and convert it
546 $this->pendingFiles = json_decode(file_get_contents($this->listCacheFile->getPathname()));
548 // List has been restored from cache!
549 $this->listCached = true;
552 // Does the class cache exist?
553 if (FrameworkBootstrap::isReadableFile($this->classCacheFile)) {
555 FrameworkBootstrap::loadInclude($this->classCacheFile);
557 // Mark the class cache as loaded
558 $this->classesCached = true;
563 * Tries to find the given class in our list. It will ignore already loaded
564 * (to the program available) class/interface/trait files. But you SHOULD
565 * save below "expensive" code by pre-checking this->loadedClasses[], if
568 * @param $className The class that shall be loaded
571 private function loadClassFile (string $className) {
572 // The class name should contain at least 2 back-slashes, so split at them
573 //* NOISY-DEBUG: */ printf('[%s:%d] className=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $className);
574 $classNameParts = explode("\\", $className);
577 $shortClassName = array_pop($classNameParts);
579 // Create a name with prefix and suffix
580 $fileName = sprintf('%s%s%s', $this->prefix, $shortClassName, $this->suffix);
582 // Now look it up in our index
583 //* NOISY-DEBUG: */ printf('[%s:%d] ISSET: fileName=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
584 if ((isset($this->pendingFiles[$fileName])) && (!isset($this->loadedClasses[$this->pendingFiles[$fileName]->getPathname()]))) {
585 // File is found and not loaded so load it only once
586 //* NOISY-DEBUG: */ printf('[%s:%d] LOAD: fileName=%s - START' . PHP_EOL, __METHOD__, __LINE__, $fileName);
587 FrameworkBootstrap::loadInclude($this->pendingFiles[$fileName]);
588 //* NOISY-DEBUG: */ printf('[%s:%d] LOAD: fileName=%s - END' . PHP_EOL, __METHOD__, __LINE__, $fileName);
590 // Count this loaded class/interface/exception
593 // Mark this class as loaded for other purposes than loading it.
594 $this->loadedClasses[$this->pendingFiles[$fileName]->getPathname()] = true;
596 // Remove it from classes list so it won't be found twice.
597 //* NOISY-DEBUG: */ printf('[%s:%d] UNSET: fileName=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
598 unset($this->pendingFiles[$fileName]);
600 // Developer mode excludes caching (better debugging)
601 if (!self::$developerModeEnabled) {
603 //* NOISY-DEBUG: */ printf('[%s:%d] classesCached=false' . PHP_EOL, __METHOD__, __LINE__);
604 $this->classesCached = false;
608 //* NOISY-DEBUG: */ printf('[%s:%d] 404: fileName=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
612 //* NOISY-DEBUG: */ printf('[%s:%d] EXIT!' . PHP_EOL, __METHOD__, __LINE__);