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 - 2021 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 * Array with all valid but pending for loading file names (class,
71 * interfaces, traits must start with below prefix).
73 private $pendingFiles = [];
76 * List of loaded classes
78 private $loadedClasses = [];
81 * Suffix with extension for all class files
83 private $prefix = 'class_';
86 * Suffix with extension for all class files
88 private $suffix = '.php';
91 * A list for directory names (no leading/trailing slashes!) which not be scanned by the path scanner
94 private $ignoreList = [];
97 * Debug this class loader? (true = yes, false = no)
99 private $debug = false;
102 * Whether the file list is cached
104 private $listCached = false;
107 * Wethe class content has been cached
109 private $classesCached = false;
112 * SplFileInfo for the list cache
114 private $listCacheFile = NULL;
117 * SplFileInfo for class content
119 private $classCacheFile = NULL;
122 * Counter for loaded include files
127 * By default the class loader is strict with naming-convention check
129 private static $strictNamingConvention = true;
132 * Framework/application paths for classes, etc.
134 private static $frameworkPaths = [
135 'classes', // Classes
136 'exceptions', // Exceptions
137 'interfaces', // Interfaces
138 'middleware', // The middleware
143 * Registered paths where test classes can be found. These are all relative
146 private static $testPaths = [];
149 * The protected constructor. Please use the factory method below, or use
150 * getSelfInstance() for singleton
154 private function __construct () {
155 // This is empty for now
159 * The destructor makes it sure all caches got flushed
163 public function __destruct () {
164 // Skip here if dev-mode
165 if (FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('developer_mode_enabled')) {
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);
174 // Open cache instance
175 $fileObject = $this->listCacheFile->openFile('w');
177 // And write whole list
178 $fileObject->fwrite($cacheContent);
181 // Skip here if already cached
182 if ($this->classesCached === false) {
183 // Generate a full-cache of all classes
185 foreach (array_keys($this->loadedClasses) as $fileInstance) {
187 $fileObject = $fileInstance->openFile('r');
190 // @TODO Add some uglifying code (compress) here
191 $cacheContent .= $fileObject->fread($fileInstance->getSize());
195 $fileObject = $this->classCacheFile->openFile('w');
198 $fileObject->fwrite($cacheContent);
203 * Scans for all framework classes, exceptions and interfaces.
207 public static function scanFrameworkClasses () {
208 // Get loader instance
209 //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
210 $loaderInstance = self::getSelfInstance();
212 // "Cache" configuration instance and framework base path
213 $configInstance = FrameworkBootstrap::getConfigurationInstance();
214 $frameworkBasePath = $configInstance->getConfigEntry('framework_base_path');
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(
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
234 } elseif (!is_readable($realPathName)) {
235 // @TODO Throw exception instead of break
239 // Try to load the framework classes
240 $loaderInstance->scanClassPath($realPathName);
244 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
248 * Scans for application's classes, etc.
252 public static function scanApplicationClasses () {
253 // Get loader instance
254 //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
255 $loaderInstance = self::getSelfInstance();
257 // "Cache" configuration instance
258 $configInstance = FrameworkBootstrap::getConfigurationInstance();
260 // Load all classes for the application
261 foreach (self::$frameworkPaths as $shortPath) {
263 //* NOISY-DEBUG: */ printf('[%s:%d]: shortPath=%s' . PHP_EOL, __METHOD__, __LINE__, $shortPath);
264 $pathName = realpath(sprintf(
266 $configInstance->getConfigEntry('application_base_path'),
268 FrameworkBootstrap::getDetectedApplicationName(),
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);
282 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
286 * Scans for test classes, etc.
290 public static function scanTestsClasses () {
291 // "Cache" configuration instance
292 //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
293 $configInstance = FrameworkBootstrap::getConfigurationInstance();
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);
301 $configInstance->getConfigEntry('root_base_path'),
307 //* NOISY-DEBUG: */ printf('[%s:%d]: pathName[%s]=%s - BEFORE!' . PHP_EOL, __METHOD__, __LINE__, gettype($pathName), $pathName);
308 $realPathName = realpath($pathName);
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);
319 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
323 * Enables or disables strict naming-convention tests on class loading
325 * @param $strictNamingConvention Whether to strictly check naming-convention
328 public static function enableStrictNamingConventionCheck (bool $strictNamingConvention = true) {
329 self::$strictNamingConvention = $strictNamingConvention;
333 * Registeres given relative path where test classes reside. For regular
334 * framework uses, they should not be loaded (and used).
336 * @param $relativePath Relative path to test classes
339 public static function registerTestsPath (string $relativePath) {
341 //* NOISY-DEBUG: */ printf('[%s:%d]: relativePath=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $relativePath);
342 self::$testPaths[$relativePath] = $relativePath;
345 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
351 * @param $className Name of the class to load
353 * @throws InvalidArgumentException If the class' name does not contain a namespace: Tld\Domain\Project is AT LEAST recommended!
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');
363 // The class name MUST be at least Tld\Domain\Project\Package\SomeFooBar so split at them
364 $classNameParts = explode("\\", $className);
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));
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);
377 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
381 * Singleton getter for an instance of this class
383 * @return $selfInstance A singleton instance of this class
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();
393 // Return the instance
394 return self::$selfInstance;
398 * Getter for total include counter
400 * @return $total Total loaded include files
402 public final function getTotal () {
407 * Getter for a printable list of included main/interfaces/exceptions
409 * @param $includeList A printable include list
411 public function getPrintableIncludeList () {
414 foreach ($this->loadedClasses as $classFile) {
415 $includeList .= basename($classFile) . '<br />' . PHP_EOL;
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
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
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) {
434 /* NOISY-DEBUG: */ printf('[%s:%d] this->listCache=true - EXIT!' . PHP_EOL, __METHOD__, __LINE__);
438 // Keep it in class for later usage
439 $this->ignoreList = $ignoreList;
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.
446 $basePath2 = realpath($basePath);
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);
455 $basePath = $basePath2;
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);
463 while ($iteratorInstance->valid()) {
465 $currentEntry = $iteratorInstance->current();
467 // Get filename from iterator which is the class' name (according naming-convention)
468 $fileName = $currentEntry->getFilename();
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();
475 // Skip non-file entries
476 //* NOISY-DEBUG: */ printf('[%s:%d] SKIP: fileName=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
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;
488 //* NOISY-DEBUG: */ printf('[%s:%d] NOT ADDED: fileName=%s,currentEntry=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName, $currentEntry);
491 // Advance to next entry
492 //* NOISY-DEBUG: */ printf('[%s:%d] NEXT: fileName=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
493 $iteratorInstance->next();
498 * Initializes our loader class
502 private function initClassLoader () {
503 // Construct the FQFN for the cache
504 if (!FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('developer_mode_enabled')) {
505 // Init cache instances
506 $this->listCacheFile = new SplFileInfo(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . 'list-' . FrameworkBootstrap::getDetectedApplicationName() . '.cache');
507 $this->classCacheFile = new SplFileInfo(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . 'class-' . FrameworkBootstrap::getDetectedApplicationName() . '.cache');
510 // Set suffix and prefix from configuration
511 $this->suffix = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('class_suffix');
512 $this->prefix = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('class_prefix');
515 self::$selfInstance = $this;
517 // Skip here if no dev-mode
518 if (FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('developer_mode_enabled')) {
522 // Is the cache there?
523 if (FrameworkBootstrap::isReadableFile($this->listCacheFile)) {
524 // Load and convert it
525 $this->pendingFiles = json_decode(file_get_contents($this->listCacheFile->getPathname()));
527 // List has been restored from cache!
528 $this->listCached = true;
531 // Does the class cache exist?
532 if (FrameworkBootstrap::isReadableFile($this->classCacheFile)) {
534 FrameworkBootstrap::loadInclude($this->classCacheFile);
536 // Mark the class cache as loaded
537 $this->classesCached = true;
542 * Tries to find the given class in our list. It will ignore already loaded
543 * (to the program available) class/interface/trait files. But you SHOULD
544 * save below "expensive" code by pre-checking this->loadedClasses[], if
547 * @param $className The class that shall be loaded
550 private function loadClassFile (string $className) {
551 // The class name should contain at least 2 back-slashes, so split at them
552 //* NOISY-DEBUG: */ printf('[%s:%d] className=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $className);
553 $classNameParts = explode("\\", $className);
556 $shortClassName = array_pop($classNameParts);
558 // Create a name with prefix and suffix
559 $fileName = sprintf('%s%s%s', $this->prefix, $shortClassName, $this->suffix);
561 // Now look it up in our index
562 //* NOISY-DEBUG: */ printf('[%s:%d] ISSET: fileName=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
563 if ((isset($this->pendingFiles[$fileName])) && (!isset($this->loadedClasses[$this->pendingFiles[$fileName]->getPathname()]))) {
564 // File is found and not loaded so load it only once
565 //* NOISY-DEBUG: */ printf('[%s:%d] LOAD: fileName=%s - START' . PHP_EOL, __METHOD__, __LINE__, $fileName);
566 FrameworkBootstrap::loadInclude($this->pendingFiles[$fileName]);
567 //* NOISY-DEBUG: */ printf('[%s:%d] LOAD: fileName=%s - END' . PHP_EOL, __METHOD__, __LINE__, $fileName);
569 // Count this loaded class/interface/exception
572 // Mark this class as loaded for other purposes than loading it.
573 $this->loadedClasses[$this->pendingFiles[$fileName]->getPathname()] = true;
575 // Remove it from classes list so it won't be found twice.
576 //* NOISY-DEBUG: */ printf('[%s:%d] UNSET: fileName=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
577 unset($this->pendingFiles[$fileName]);
579 // Developer mode excludes caching (better debugging)
580 if (!FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('developer_mode_enabled')) {
582 //* NOISY-DEBUG: */ printf('[%s:%d] classesCached=false' . PHP_EOL, __METHOD__, __LINE__);
583 $this->classesCached = false;
587 //* NOISY-DEBUG: */ printf('[%s:%d] 404: fileName=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
591 //* NOISY-DEBUG: */ printf('[%s:%d] EXIT!' . PHP_EOL, __METHOD__, __LINE__);