3 namespace Org\Mxchange\CoreFramework\Loader;
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
7 use Org\Mxchange\CoreFramework\Configuration\FrameworkConfiguration;
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 - 2021 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 * - Namespace scheme Project\Package[\SubPackage...] is fully supported and
40 * throws an InvalidArgumentException if not present. The last part will be
41 * always the class' name.
43 * - Some comments improved, other minor improvements
45 * - Constructor is now empty and factory method 'createClassLoader' is created
46 * - renamed loadClasses to scanClassPath
47 * - Added initLoader()
49 * - ClassLoader rewritten to PHP SPL's own RecursiveIteratorIterator class
51 * - loadClasses rewritten to fix some notices
54 * ----------------------------------
58 * Instance of this class
60 private static $selfInstance = NULL;
63 * Array with all found classes
65 private $foundClasses = [];
68 * List of loaded classes
70 private $loadedClasses = [];
73 * Suffix with extension for all class files
75 private $prefix = 'class_';
78 * Suffix with extension for all class files
80 private $suffix = '.php';
83 * A list for directory names (no leading/trailing slashes!) which not be scanned by the path scanner
86 private $ignoreList = [];
89 * Debug this class loader? (true = yes, false = no)
91 private $debug = false;
94 * Whether the file list is cached
96 private $listCached = false;
99 * Wethe class content has been cached
101 private $classesCached = false;
104 * SplFileInfo for the list cache
106 private $listCacheFile = NULL;
109 * SplFileInfo for class content
111 private $classCacheFile = NULL;
114 * Counter for loaded include files
119 * By default the class loader is strict with naming-convention check
121 private static $strictNamingConvention = true;
124 * Framework/application paths for classes, etc.
126 private static $frameworkPaths = [
127 'classes', // Classes
128 'exceptions', // Exceptions
129 'interfaces', // Interfaces
130 'middleware', // The middleware
135 * Registered paths where test classes can be found. These are all relative
138 private static $testPaths = [];
141 * The protected constructor. Please use the factory method below, or use
142 * getSelfInstance() for singleton
146 private function __construct () {
147 // This is empty for now
151 * The destructor makes it sure all caches got flushed
155 public function __destruct () {
156 // Skip here if dev-mode
157 if (FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('developer_mode_enabled')) {
161 // Skip here if already cached
162 if ($this->listCached === false) {
163 // Writes the cache file of our list away
164 $cacheContent = json_encode($this->foundClasses);
166 // Open cache instance
167 $fileObject = $this->listCacheFile->openFile('w');
169 // And write whole list
170 $fileObject->fwrite($cacheContent);
173 // Skip here if already cached
174 if ($this->classesCached === false) {
175 // Generate a full-cache of all classes
177 foreach (array_keys($this->loadedClasses) as $fileInstance) {
179 $fileObject = $fileInstance->openFile('r');
182 // @TODO Add some uglifying code (compress) here
183 $cacheContent .= $fileObject->fread($fileInstance->getSize());
187 $fileObject = $this->classCacheFile->openFile('w');
190 $fileObject->fwrite($cacheContent);
195 * Creates an instance of this class loader for given configuration instance
197 * @param $configInstance Configuration class instance
200 public static final function createClassLoader (FrameworkConfiguration $configInstance) {
201 // Get a new instance
202 $loaderInstance = new ClassLoader();
205 $loaderInstance->initLoader($configInstance);
207 // Return the prepared instance
208 return $loaderInstance;
212 * Scans for all framework classes, exceptions and interfaces.
216 public static function scanFrameworkClasses () {
217 // Get loader instance
218 //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
219 $loaderInstance = self::getSelfInstance();
221 // Get config instance
222 $configInstance = FrameworkBootstrap::getConfigurationInstance();
225 foreach (self::$frameworkPaths as $shortPath) {
226 // Generate full path from it
227 //* NOISY-DEBUG: */ printf('[%s:%d]: shortPath=%s' . PHP_EOL, __METHOD__, __LINE__, $shortPath);
228 $realPathName = realpath(sprintf(
230 $configInstance->getConfigEntry('framework_base_path'),
236 // Is it not false and accessible?
237 //* NOISY-DEBUG: */ printf('[%s:%d]: realPathName=%s' . PHP_EOL, __METHOD__, __LINE__, $realPathName);
238 if (is_bool($realPathName)) {
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 // Get config 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 () {
299 //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
301 // Get config instance
302 $configInstance = FrameworkBootstrap::getConfigurationInstance();
304 // Load all classes for the application
305 foreach (self::$testPaths as $shortPath) {
307 //* NOISY-DEBUG: */ printf('[%s:%d]: shortPath=%s' . PHP_EOL, __METHOD__, __LINE__, $shortPath);
309 // Construct path name
312 $configInstance->getConfigEntry('root_base_path'),
318 //* NOISY-DEBUG: */ printf('[%s:%d]: pathName[%s]=%s - BEFORE!' . PHP_EOL, __METHOD__, __LINE__, gettype($pathName), $pathName);
319 $realPathName = realpath($pathName);
321 // Is the path readable?
322 //* NOISY-DEBUG: */ printf('[%s:%d]: realPathName[%s]=%s - AFTER!' . PHP_EOL, __METHOD__, __LINE__, gettype($realPathName), $realPathName);
323 if ((is_dir($realPathName)) && (is_readable($realPathName))) {
324 // Try to load the application classes
325 ClassLoader::getSelfInstance()->scanClassPath($realPathName);
330 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
334 * Enables or disables strict naming-convention tests on class loading
336 * @param $strictNamingConvention Whether to strictly check naming-convention
339 public static function enableStrictNamingConventionCheck (bool $strictNamingConvention = true) {
340 self::$strictNamingConvention = $strictNamingConvention;
344 * Registeres given relative path where test classes reside. For regular
345 * framework uses, they should not be loaded (and used).
347 * @param $relativePath Relative path to test classes
350 public static function registerTestsPath (string $relativePath) {
352 //* NOISY-DEBUG: */ printf('[%s:%d]: relativePath=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $relativePath);
353 self::$testPaths[$relativePath] = $relativePath;
356 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
362 * @param $className Name of the class to load
365 public static function autoLoad (string $className) {
367 //* NOISY-DEBUG: */ printf('[%s:%d]: className=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $className);
369 // Try to include this class
370 self::getSelfInstance()->loadClassFile($className);
373 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
377 * Singleton getter for an instance of this class
379 * @return $selfInstance A singleton instance of this class
381 public static final function getSelfInstance () {
382 // Is the instance there?
383 if (is_null(self::$selfInstance)) {
385 self::$selfInstance = ClassLoader::createClassLoader(FrameworkBootstrap::getConfigurationInstance());
388 // Return the instance
389 return self::$selfInstance;
393 * Scans recursively a local path for class files which must have a prefix and a suffix as given by $this->suffix and $this->prefix
395 * @param $basePath The relative base path to 'framework_base_path' constant for all classes
396 * @param $ignoreList An optional list (array forced) of directory and file names which shall be ignored
399 public function scanClassPath (string $basePath, array $ignoreList = [] ) {
400 // Is a list has been restored from cache, don't read it again
401 if ($this->listCached === true) {
406 // Keep it in class for later usage
407 $this->ignoreList = $ignoreList;
410 * Ignore .htaccess by default as it is for protection of directories
413 array_push($ignoreList, '.htaccess');
416 * Set base directory which holds all our classes, an absolute path
417 * should be used here so is_dir(), is_file() and so on will always
418 * find the correct files and dirs.
420 $basePath2 = realpath($basePath);
422 // If the basePath is false it is invalid
423 if ($basePath2 === false) {
424 /* @TODO: Do not exit here. */
425 exit(__METHOD__ . ': Cannot read ' . $basePath . ' !' . PHP_EOL);
428 $basePath = $basePath2;
431 // Get a new iterator
432 //* NOISY-DEBUG: */ printf('[%s:%d] basePath=%s' . PHP_EOL, __METHOD__, __LINE__, $basePath);
433 $iteratorInstance = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($basePath), RecursiveIteratorIterator::CHILD_FIRST);
436 while ($iteratorInstance->valid()) {
438 $currentEntry = $iteratorInstance->current();
440 // Get filename from iterator which is the class' name (according naming-convention)
441 $fileName = $currentEntry->getFilename();
443 // Current entry must be a file, not smaller than 100 bytes and not on ignore list
444 if ((!$currentEntry->isFile()) || (in_array($fileName, $this->ignoreList)) || ($currentEntry->getSize() < 100)) {
445 // Advance to next entry
446 $iteratorInstance->next();
448 // Skip non-file entries
449 //* NOISY-DEBUG: */ printf('[%s:%d] SKIP: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
453 // Is this file wanted?
454 //* NOISY-DEBUG: */ printf('[%s:%d] FOUND: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
455 if ((substr($fileName, 0, strlen($this->prefix)) == $this->prefix) && (substr($fileName, -strlen($this->suffix), strlen($this->suffix)) == $this->suffix)) {
456 // Add it to the list
457 //* NOISY-DEBUG: */ printf('[%s:%d] ADD: %s,currentEntry=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName, $currentEntry);
458 $this->foundClasses[$fileName] = $currentEntry;
461 //* NOISY-DEBUG: */ printf('[%s:%d] NOT ADDED: %s,currentEntry=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName, $currentEntry);
464 // Advance to next entry
465 //* NOISY-DEBUG: */ printf('[%s:%d] NEXT: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
466 $iteratorInstance->next();
471 * Getter for total include counter
473 * @return $total Total loaded include files
475 public final function getTotal () {
480 * Getter for a printable list of included main/interfaces/exceptions
482 * @param $includeList A printable include list
484 public function getPrintableIncludeList () {
487 foreach ($this->loadedClasses as $classFile) {
488 $includeList .= basename($classFile) . '<br />' . PHP_EOL;
496 * Initializes our loader class
498 * @param $configInstance Configuration class instance
501 private function initLoader (FrameworkConfiguration $configInstance) {
502 // Set configuration instance
503 $this->configInstance = $configInstance;
505 // Construct the FQFN for the cache
506 if (!FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('developer_mode_enabled')) {
507 // Init cache instances
508 $this->listCacheFile = new SplFileInfo($this->configInstance->getConfigEntry('local_database_path') . 'list-' . FrameworkBootstrap::getDetectedApplicationName() . '.cache');
509 $this->classCacheFile = new SplFileInfo($this->configInstance->getConfigEntry('local_database_path') . 'class-' . FrameworkBootstrap::getDetectedApplicationName() . '.cache');
512 // Set suffix and prefix from configuration
513 $this->suffix = $configInstance->getConfigEntry('class_suffix');
514 $this->prefix = $configInstance->getConfigEntry('class_prefix');
517 self::$selfInstance = $this;
519 // Skip here if no dev-mode
520 if (FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('developer_mode_enabled')) {
524 // Is the cache there?
525 if (FrameworkBootstrap::isReadableFile($this->listCacheFile)) {
526 // Load and convert it
527 $this->foundClasses = json_decode(file_get_contents($this->listCacheFile->getPathname()));
529 // List has been restored from cache!
530 $this->listCached = true;
533 // Does the class cache exist?
534 if (FrameworkBootstrap::isReadableFile($this->classCacheFile)) {
536 FrameworkBootstrap::loadInclude($this->classCacheFile);
538 // Mark the class cache as loaded
539 $this->classesCached = true;
544 * Tries to find the given class in our list. This method ignores silently
545 * missing classes or interfaces. So if you use class_exists() this method
546 * does not interrupt your program.
548 * @param $className The class that shall be loaded
550 * @throws InvalidArgumentException If strict-checking is enabled and class name is not following naming-convention
552 private function loadClassFile (string $className) {
553 // The class name should contain at least 2 back-slashes, so split at them
554 //* NOISY-DEBUG: */ printf('[%s:%d] className=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $className);
555 $classNameParts = explode("\\", $className);
557 // At least 3 parts should be there
558 if ((self::$strictNamingConvention === true) && (count($classNameParts) < 5)) {
559 // Namespace scheme is: Project\Package[\SubPackage...]
560 throw new InvalidArgumentException(sprintf('Class name "%s" is not conform to naming-convention: Tld\Domain\Project\Package[\SubPackage...]\SomeFooBar', $className));
564 $shortClassName = array_pop($classNameParts);
566 // Create a name with prefix and suffix
567 $fileName = sprintf('%s%s%s', $this->prefix, $shortClassName, $this->suffix);
569 // Now look it up in our index
570 //* NOISY-DEBUG: */ printf('[%s:%d] ISSET: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
571 if ((isset($this->foundClasses[$fileName])) && (!isset($this->loadedClasses[$this->foundClasses[$fileName]->getPathname()]))) {
572 // File is found and not loaded so load it only once
573 //* NOISY-DEBUG: */ printf('[%s:%d] LOAD: %s - START' . PHP_EOL, __METHOD__, __LINE__, $fileName);
574 FrameworkBootstrap::loadInclude($this->foundClasses[$fileName]);
575 //* NOISY-DEBUG: */ printf('[%s:%d] LOAD: %s - END' . PHP_EOL, __METHOD__, __LINE__, $fileName);
577 // Count this loaded class/interface/exception
580 // Mark this class as loaded for other purposes than loading it.
581 $this->loadedClasses[$this->foundClasses[$fileName]->getPathname()] = true;
583 // Remove it from classes list so it won't be found twice.
584 //* NOISY-DEBUG: */ printf('[%s:%d] UNSET: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
585 unset($this->foundClasses[$fileName]);
587 // Developer mode excludes caching (better debugging)
588 if (!FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('developer_mode_enabled')) {
590 //* NOISY-DEBUG: */ printf('[%s:%d] classesCached=false' . PHP_EOL, __METHOD__, __LINE__);
591 $this->classesCached = false;
595 //* NOISY-DEBUG: */ printf('[%s:%d] 404: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);