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 * ----------------------------------
65 * Instance of this class
67 private static $selfInstance = NULL;
70 * Array with all found classes
72 private $foundClasses = [];
75 * List of loaded classes
77 private $loadedClasses = [];
80 * Suffix with extension for all class files
82 private $prefix = 'class_';
85 * Suffix with extension for all class files
87 private $suffix = '.php';
90 * A list for directory names (no leading/trailing slashes!) which not be scanned by the path scanner
93 private $ignoreList = [];
96 * Debug this class loader? (true = yes, false = no)
98 private $debug = false;
101 * Whether the file list is cached
103 private $listCached = false;
106 * Wethe class content has been cached
108 private $classesCached = false;
111 * SplFileInfo for the list cache
113 private $listCacheFile = NULL;
116 * SplFileInfo for class content
118 private $classCacheFile = NULL;
121 * Counter for loaded include files
126 * By default the class loader is strict with naming-convention check
128 private static $strictNamingConvention = true;
131 * Framework/application paths for classes, etc.
133 private static $frameworkPaths = [
134 'classes', // Classes
135 'exceptions', // Exceptions
136 'interfaces', // Interfaces
137 'middleware', // The middleware
142 * Registered paths where test classes can be found. These are all relative
145 private static $testPaths = [];
148 * The protected constructor. Please use the factory method below, or use
149 * getSelfInstance() for singleton
153 private function __construct () {
154 // This is empty for now
158 * The destructor makes it sure all caches got flushed
162 public function __destruct () {
163 // Skip here if dev-mode
164 if (FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('developer_mode_enabled')) {
168 // Skip here if already cached
169 if ($this->listCached === false) {
170 // Writes the cache file of our list away
171 $cacheContent = json_encode($this->foundClasses);
173 // Open cache instance
174 $fileObject = $this->listCacheFile->openFile('w');
176 // And write whole list
177 $fileObject->fwrite($cacheContent);
180 // Skip here if already cached
181 if ($this->classesCached === false) {
182 // Generate a full-cache of all classes
184 foreach (array_keys($this->loadedClasses) as $fileInstance) {
186 $fileObject = $fileInstance->openFile('r');
189 // @TODO Add some uglifying code (compress) here
190 $cacheContent .= $fileObject->fread($fileInstance->getSize());
194 $fileObject = $this->classCacheFile->openFile('w');
197 $fileObject->fwrite($cacheContent);
202 * Scans for all framework classes, exceptions and interfaces.
206 public static function scanFrameworkClasses () {
207 // Get loader instance
208 //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
209 $loaderInstance = self::getSelfInstance();
211 // "Cache" configuration instance
212 $configInstance = FrameworkBootstrap::getConfigurationInstance();
215 foreach (self::$frameworkPaths as $shortPath) {
216 // Generate full path from it
217 //* NOISY-DEBUG: */ printf('[%s:%d]: shortPath=%s' . PHP_EOL, __METHOD__, __LINE__, $shortPath);
218 $realPathName = realpath(sprintf(
220 $configInstance->getConfigEntry('framework_base_path'),
226 // Is it not false and accessible?
227 //* NOISY-DEBUG: */ printf('[%s:%d]: realPathName=%s' . PHP_EOL, __METHOD__, __LINE__, $realPathName);
228 if (is_bool($realPathName)) {
231 } elseif (!is_readable($realPathName)) {
232 // @TODO Throw exception instead of break
236 // Try to load the framework classes
237 $loaderInstance->scanClassPath($realPathName);
241 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
245 * Scans for application's classes, etc.
249 public static function scanApplicationClasses () {
250 // Get loader instance
251 //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
252 $loaderInstance = self::getSelfInstance();
254 // "Cache" configuration instance
255 $configInstance = FrameworkBootstrap::getConfigurationInstance();
257 // Load all classes for the application
258 foreach (self::$frameworkPaths as $shortPath) {
260 //* NOISY-DEBUG: */ printf('[%s:%d]: shortPath=%s' . PHP_EOL, __METHOD__, __LINE__, $shortPath);
261 $pathName = realpath(sprintf(
263 $configInstance->getConfigEntry('application_base_path'),
265 FrameworkBootstrap::getDetectedApplicationName(),
270 // Is the path readable?
271 //* NOISY-DEBUG: */ printf('[%s:%d]: pathName[%s]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype($pathName), $pathName);
272 if (is_dir($pathName)) {
273 // Try to load the application classes
274 $loaderInstance->scanClassPath($pathName);
279 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
283 * Scans for test classes, etc.
287 public static function scanTestsClasses () {
289 //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
291 // "Cache" configuration instance
292 $configInstance = FrameworkBootstrap::getConfigurationInstance();
294 // Load all classes for the application
295 foreach (self::$testPaths as $shortPath) {
297 //* NOISY-DEBUG: */ printf('[%s:%d]: shortPath=%s' . PHP_EOL, __METHOD__, __LINE__, $shortPath);
299 // Construct path name
302 $configInstance->getConfigEntry('root_base_path'),
308 //* NOISY-DEBUG: */ printf('[%s:%d]: pathName[%s]=%s - BEFORE!' . PHP_EOL, __METHOD__, __LINE__, gettype($pathName), $pathName);
309 $realPathName = realpath($pathName);
311 // Is the path readable?
312 //* NOISY-DEBUG: */ printf('[%s:%d]: realPathName[%s]=%s - AFTER!' . PHP_EOL, __METHOD__, __LINE__, gettype($realPathName), $realPathName);
313 if ((is_dir($realPathName)) && (is_readable($realPathName))) {
314 // Try to load the application classes
315 ClassLoader::getSelfInstance()->scanClassPath($realPathName);
320 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
324 * Enables or disables strict naming-convention tests on class loading
326 * @param $strictNamingConvention Whether to strictly check naming-convention
329 public static function enableStrictNamingConventionCheck (bool $strictNamingConvention = true) {
330 self::$strictNamingConvention = $strictNamingConvention;
334 * Registeres given relative path where test classes reside. For regular
335 * framework uses, they should not be loaded (and used).
337 * @param $relativePath Relative path to test classes
340 public static function registerTestsPath (string $relativePath) {
342 //* NOISY-DEBUG: */ printf('[%s:%d]: relativePath=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $relativePath);
343 self::$testPaths[$relativePath] = $relativePath;
346 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
352 * @param $className Name of the class to load
354 * @throws InvalidArgumentException If the class' name does not contain a namespace: Tld\Domain\Project is AT LEAST recommended!
356 public static function autoLoad (string $className) {
357 // The class name should contain at least 2 back-slashes, so split at them
358 //* NOISY-DEBUG: */ printf('[%s:%d] className=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $className);
359 $classNameParts = explode("\\", $className);
361 // At least 3 parts should be there
362 if ((self::$strictNamingConvention === true) && (count($classNameParts) < 5)) {
363 // Namespace scheme is: Project\Package[\SubPackage...]
364 throw new InvalidArgumentException(sprintf('Class name "%s" is not conform to naming-convention: Tld\Domain\Project\Package[\SubPackage...]\SomeFooBar', $className));
367 // Try to include this class
368 self::getSelfInstance()->loadClassFile($className);
371 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
375 * Singleton getter for an instance of this class
377 * @return $selfInstance A singleton instance of this class
379 public static final function getSelfInstance () {
380 // Is the instance there?
381 if (is_null(self::$selfInstance)) {
382 // Get a new one and initialize it
383 self::$selfInstance = new ClassLoader();
384 self::$selfInstance->initClassLoader();
387 // Return the instance
388 return self::$selfInstance;
392 * Getter for total include counter
394 * @return $total Total loaded include files
396 public final function getTotal () {
401 * Getter for a printable list of included main/interfaces/exceptions
403 * @param $includeList A printable include list
405 public function getPrintableIncludeList () {
408 foreach ($this->loadedClasses as $classFile) {
409 $includeList .= basename($classFile) . '<br />' . PHP_EOL;
417 * Scans recursively a local path for class files which must have a prefix and a suffix as given by $this->suffix and $this->prefix
419 * @param $basePath The relative base path to 'framework_base_path' constant for all classes
420 * @param $ignoreList An optional list (array forced) of directory and file names which shall be ignored
423 protected function scanClassPath (string $basePath, array $ignoreList = [] ) {
424 // Is a list has been restored from cache, don't read it again
425 if ($this->listCached === true) {
430 // Keep it in class for later usage
431 $this->ignoreList = $ignoreList;
434 * Ignore .htaccess by default as it is for protection of directories
439 array_push($ignoreList, '.htaccess');
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 if ($basePath2 === false) {
450 /* @TODO: Do not exit here. */
451 exit(__METHOD__ . ': Cannot read ' . $basePath . ' !' . PHP_EOL);
454 $basePath = $basePath2;
457 // Get a new iterator
458 //* NOISY-DEBUG: */ printf('[%s:%d] basePath=%s' . PHP_EOL, __METHOD__, __LINE__, $basePath);
459 $iteratorInstance = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($basePath), RecursiveIteratorIterator::CHILD_FIRST);
462 while ($iteratorInstance->valid()) {
464 $currentEntry = $iteratorInstance->current();
466 // Get filename from iterator which is the class' name (according naming-convention)
467 $fileName = $currentEntry->getFilename();
469 // Current entry must be a file, not smaller than 100 bytes and not on ignore list
470 if ((!$currentEntry->isFile()) || (in_array($fileName, $this->ignoreList)) || ($currentEntry->getSize() < 100)) {
471 // Advance to next entry
472 $iteratorInstance->next();
474 // Skip non-file entries
475 //* NOISY-DEBUG: */ printf('[%s:%d] SKIP: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
479 // Is this file wanted?
480 //* NOISY-DEBUG: */ printf('[%s:%d] FOUND: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
481 if ((substr($fileName, 0, strlen($this->prefix)) == $this->prefix) && (substr($fileName, -strlen($this->suffix), strlen($this->suffix)) == $this->suffix)) {
482 // Add it to the list
483 //* NOISY-DEBUG: */ printf('[%s:%d] ADD: %s,currentEntry=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName, $currentEntry);
484 $this->foundClasses[$fileName] = $currentEntry;
487 //* NOISY-DEBUG: */ printf('[%s:%d] NOT ADDED: %s,currentEntry=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName, $currentEntry);
490 // Advance to next entry
491 //* NOISY-DEBUG: */ printf('[%s:%d] NEXT: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
492 $iteratorInstance->next();
497 * Initializes our loader class
501 private function initClassLoader () {
502 // Construct the FQFN for the cache
503 if (!FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('developer_mode_enabled')) {
504 // Init cache instances
505 $this->listCacheFile = new SplFileInfo(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . 'list-' . FrameworkBootstrap::getDetectedApplicationName() . '.cache');
506 $this->classCacheFile = new SplFileInfo(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . 'class-' . FrameworkBootstrap::getDetectedApplicationName() . '.cache');
509 // Set suffix and prefix from configuration
510 $this->suffix = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('class_suffix');
511 $this->prefix = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('class_prefix');
514 self::$selfInstance = $this;
516 // Skip here if no dev-mode
517 if (FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('developer_mode_enabled')) {
521 // Is the cache there?
522 if (FrameworkBootstrap::isReadableFile($this->listCacheFile)) {
523 // Load and convert it
524 $this->foundClasses = json_decode(file_get_contents($this->listCacheFile->getPathname()));
526 // List has been restored from cache!
527 $this->listCached = true;
530 // Does the class cache exist?
531 if (FrameworkBootstrap::isReadableFile($this->classCacheFile)) {
533 FrameworkBootstrap::loadInclude($this->classCacheFile);
535 // Mark the class cache as loaded
536 $this->classesCached = true;
541 * Tries to find the given class in our list. This method ignores silently
542 * missing classes or interfaces. So if you use class_exists() this method
543 * does not interrupt your program.
545 * @param $className The class that shall be loaded
548 private function loadClassFile (string $className) {
549 // The class name should contain at least 2 back-slashes, so split at them
550 //* NOISY-DEBUG: */ printf('[%s:%d] className=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $className);
551 $classNameParts = explode("\\", $className);
554 $shortClassName = array_pop($classNameParts);
556 // Create a name with prefix and suffix
557 $fileName = sprintf('%s%s%s', $this->prefix, $shortClassName, $this->suffix);
559 // Now look it up in our index
560 //* NOISY-DEBUG: */ printf('[%s:%d] ISSET: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
561 if ((isset($this->foundClasses[$fileName])) && (!isset($this->loadedClasses[$this->foundClasses[$fileName]->getPathname()]))) {
562 // File is found and not loaded so load it only once
563 //* NOISY-DEBUG: */ printf('[%s:%d] LOAD: %s - START' . PHP_EOL, __METHOD__, __LINE__, $fileName);
564 FrameworkBootstrap::loadInclude($this->foundClasses[$fileName]);
565 //* NOISY-DEBUG: */ printf('[%s:%d] LOAD: %s - END' . PHP_EOL, __METHOD__, __LINE__, $fileName);
567 // Count this loaded class/interface/exception
570 // Mark this class as loaded for other purposes than loading it.
571 $this->loadedClasses[$this->foundClasses[$fileName]->getPathname()] = true;
573 // Remove it from classes list so it won't be found twice.
574 //* NOISY-DEBUG: */ printf('[%s:%d] UNSET: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
575 unset($this->foundClasses[$fileName]);
577 // Developer mode excludes caching (better debugging)
578 if (!FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('developer_mode_enabled')) {
580 //* NOISY-DEBUG: */ printf('[%s:%d] classesCached=false' . PHP_EOL, __METHOD__, __LINE__);
581 $this->classesCached = false;
585 //* NOISY-DEBUG: */ printf('[%s:%d] 404: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);