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 - 2020 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 = array();
68 * List of loaded classes
70 private $loadedClasses = array();
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 = array();
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 = array(
127 'exceptions', // Exceptions
128 'interfaces', // Interfaces
129 'classes', // Classes
130 'middleware' // The middleware
134 * Registered paths where test classes can be found. These are all relative
137 private static $testPaths = array();
140 * The protected constructor. Please use the factory method below, or use
141 * getSelfInstance() for singleton
145 protected function __construct () {
146 // This is empty for now
150 * The destructor makes it sure all caches got flushed
154 public function __destruct () {
155 // Skip here if dev-mode
156 if (defined('DEVELOPER')) {
160 // Skip here if already cached
161 if ($this->listCached === false) {
162 // Writes the cache file of our list away
163 $cacheContent = json_encode($this->foundClasses);
165 // Open cache instance
166 $fileObject = $this->listCacheFile->openFile('w');
168 // And write whole list
169 $fileObject->fwrite($cacheContent);
172 // Skip here if already cached
173 if ($this->classesCached === false) {
174 // Generate a full-cache of all classes
176 foreach (array_keys($this->loadedClasses) as $fileInstance) {
178 $fileObject = $fileInstance->openFile('r');
181 // @TODO Add some uglifying code (compress) here
182 $cacheContent .= $fileObject->fread($fileInstance->getSize());
186 $fileObject = $this->classCacheFile->openFile('w');
189 $fileObject->fwrite($cacheContent);
194 * Creates an instance of this class loader for given configuration instance
196 * @param $configInstance Configuration class instance
199 public static final function createClassLoader (FrameworkConfiguration $configInstance) {
200 // Get a new instance
201 $loaderInstance = new ClassLoader();
204 $loaderInstance->initLoader($configInstance);
206 // Return the prepared instance
207 return $loaderInstance;
211 * Scans for all framework classes, exceptions and interfaces.
215 public static function scanFrameworkClasses () {
217 //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
219 // Get loader instance
220 $loaderInstance = self::getSelfInstance();
222 // Get config instance
223 $configInstance = FrameworkBootstrap::getConfigurationInstance();
226 foreach (self::$frameworkPaths as $shortPath) {
228 //* NOISY-DEBUG: */ printf('[%s:%d]: shortPath=%s' . PHP_EOL, __METHOD__, __LINE__, $shortPath);
230 // Generate full path from it
231 $realPathName = realpath(sprintf(
233 $configInstance->getConfigEntry('framework_base_path'),
240 //* NOISY-DEBUG: */ printf('[%s:%d]: realPathName=%s' . PHP_EOL, __METHOD__, __LINE__, $realPathName);
242 // Is it not false and accessible?
243 if (is_bool($realPathName)) {
246 } elseif (!is_readable($realPathName)) {
247 // @TODO Throw exception instead of break
251 // Try to load the framework classes
252 $loaderInstance->scanClassPath($realPathName);
256 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
260 * Scans for application's classes, etc.
264 public static function scanApplicationClasses () {
266 //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
268 // Get loader instance
269 $loaderInstance = self::getSelfInstance();
271 // Get config instance
272 $configInstance = FrameworkBootstrap::getConfigurationInstance();
274 // Load all classes for the application
275 foreach (self::$frameworkPaths as $shortPath) {
277 //* NOISY-DEBUG: */ printf('[%s:%d]: shortPath=%s' . PHP_EOL, __METHOD__, __LINE__, $shortPath);
280 $pathName = realpath(sprintf(
282 $configInstance->getConfigEntry('application_base_path'),
284 $configInstance->getConfigEntry('detected_app_name'),
290 //* NOISY-DEBUG: */ printf('[%s:%d]: pathName[%s]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype($pathName), $pathName);
292 // Is the path readable?
293 if (is_dir($pathName)) {
294 // Try to load the application classes
295 $loaderInstance->scanClassPath($pathName);
300 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
304 * Scans for test classes, etc.
308 public static function scanTestsClasses () {
310 //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
312 // Get config instance
313 $configInstance = FrameworkBootstrap::getConfigurationInstance();
315 // Load all classes for the application
316 foreach (self::$testPaths as $shortPath) {
318 //* NOISY-DEBUG: */ printf('[%s:%d]: shortPath=%s' . PHP_EOL, __METHOD__, __LINE__, $shortPath);
320 // Construct path name
323 $configInstance->getConfigEntry('root_base_path'),
329 //* NOISY-DEBUG: */ printf('[%s:%d]: pathName[%s]=%s - BEFORE!' . PHP_EOL, __METHOD__, __LINE__, gettype($pathName), $pathName);
332 $realPathName = realpath($pathName);
335 //* NOISY-DEBUG: */ printf('[%s:%d]: realPathName[%s]=%s - AFTER!' . PHP_EOL, __METHOD__, __LINE__, gettype($realPathName), $realPathName);
337 // Is the path readable?
338 if ((is_dir($realPathName)) && (is_readable($realPathName))) {
339 // Try to load the application classes
340 ClassLoader::getSelfInstance()->scanClassPath($realPathName);
345 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
349 * Enables or disables strict naming-convention tests on class loading
351 * @param $strictNamingConvention Whether to strictly check naming-convention
354 public static function enableStrictNamingConventionCheck ($strictNamingConvention = true) {
355 self::$strictNamingConvention = $strictNamingConvention;
359 * Registeres given relative path where test classes reside. For regular
360 * framework uses, they should not be loaded (and used).
362 * @param $relativePath Relative path to test classes
365 public static function registerTestsPath ($relativePath) {
367 //* NOISY-DEBUG: */ printf('[%s:%d]: relativePath=%s - CALLED!' . 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
382 public static function autoLoad ($className) {
384 //* NOISY-DEBUG: */ printf('[%s:%d]: className=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $className);
386 // Try to include this class
387 self::getSelfInstance()->loadClassFile($className);
390 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
394 * Singleton getter for an instance of this class
396 * @return $selfInstance A singleton instance of this class
398 public static final function getSelfInstance () {
399 // Is the instance there?
400 if (is_null(self::$selfInstance)) {
402 self::$selfInstance = ClassLoader::createClassLoader(FrameworkBootstrap::getConfigurationInstance());
405 // Return the instance
406 return self::$selfInstance;
410 * Scans recursively a local path for class files which must have a prefix and a suffix as given by $this->suffix and $this->prefix
412 * @param $basePath The relative base path to 'framework_base_path' constant for all classes
413 * @param $ignoreList An optional list (array forced) of directory and file names which shall be ignored
416 public function scanClassPath ($basePath, array $ignoreList = array() ) {
417 // Is a list has been restored from cache, don't read it again
418 if ($this->listCached === true) {
423 // Keep it in class for later usage
424 $this->ignoreList = $ignoreList;
427 * Ignore .htaccess by default as it is for protection of directories
430 array_push($ignoreList, '.htaccess');
433 * Set base directory which holds all our classes, an absolute path
434 * should be used here so is_dir(), is_file() and so on will always
435 * find the correct files and dirs.
437 $basePath2 = realpath($basePath);
439 // If the basePath is false it is invalid
440 if ($basePath2 === false) {
441 /* @TODO: Do not exit here. */
442 exit(__METHOD__ . ': Cannot read ' . $basePath . ' !' . PHP_EOL);
445 $basePath = $basePath2;
448 // Get a new iterator
449 //* NOISY-DEBUG: */ printf('[%s:%d] basePath=%s' . PHP_EOL, __METHOD__, __LINE__, $basePath);
450 $iteratorInstance = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($basePath), RecursiveIteratorIterator::CHILD_FIRST);
453 while ($iteratorInstance->valid()) {
455 $currentEntry = $iteratorInstance->current();
457 // Get filename from iterator which is the class' name (according naming-convention)
458 $fileName = $currentEntry->getFilename();
460 // Current entry must be a file, not smaller than 100 bytes and not on ignore list
461 if ((!$currentEntry->isFile()) || (in_array($fileName, $this->ignoreList)) || ($currentEntry->getSize() < 100)) {
462 // Advance to next entry
463 $iteratorInstance->next();
465 // Skip non-file entries
466 //* NOISY-DEBUG: */ printf('[%s:%d] SKIP: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
470 // Is this file wanted?
471 //* NOISY-DEBUG: */ printf('[%s:%d] FOUND: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
472 if ((substr($fileName, 0, strlen($this->prefix)) == $this->prefix) && (substr($fileName, -strlen($this->suffix), strlen($this->suffix)) == $this->suffix)) {
473 // Add it to the list
474 //* NOISY-DEBUG: */ printf('[%s:%d] ADD: %s,currentEntry=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName, $currentEntry);
475 $this->foundClasses[$fileName] = $currentEntry;
478 //* NOISY-DEBUG: */ printf('[%s:%d] NOT ADDED: %s,currentEntry=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName, $currentEntry);
481 // Advance to next entry
482 //* NOISY-DEBUG: */ printf('[%s:%d] NEXT: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
483 $iteratorInstance->next();
488 * Getter for total include counter
490 * @return $total Total loaded include files
492 public final function getTotal () {
497 * Getter for a printable list of included main/interfaces/exceptions
499 * @param $includeList A printable include list
501 public function getPrintableIncludeList () {
504 foreach ($this->loadedClasses as $classFile) {
505 $includeList .= basename($classFile) . '<br />' . PHP_EOL;
513 * Initializes our loader class
515 * @param $configInstance Configuration class instance
518 private function initLoader (FrameworkConfiguration $configInstance) {
519 // Set configuration instance
520 $this->configInstance = $configInstance;
522 // Construct the FQFN for the cache
523 if (!defined('DEVELOPER')) {
524 $this->listCacheFile = new SplFileInfo($this->configInstance->getConfigEntry('local_database_path') . 'list-' . $this->configInstance->getConfigEntry('detected_app_name') . '.cache');
525 $this->classCacheFile = new SplFileInfo($this->configInstance->getConfigEntry('local_database_path') . 'class-' . $this->configInstance->getConfigEntry('detected_app_name') . '.cache');
528 // Set suffix and prefix from configuration
529 $this->suffix = $configInstance->getConfigEntry('class_suffix');
530 $this->prefix = $configInstance->getConfigEntry('class_prefix');
533 self::$selfInstance = $this;
535 // Skip here if no dev-mode
536 if (defined('DEVELOPER')) {
540 // Is the cache there?
541 if (FrameworkBootstrap::isReadableFile($this->listCacheFile)) {
542 // Load and convert it
543 $this->foundClasses = json_decode(file_get_contents($this->listCacheFile->getPathname()));
545 // List has been restored from cache!
546 $this->listCached = true;
549 // Does the class cache exist?
550 if (FrameworkBootstrap::isReadableFile($this->classCacheFile)) {
552 FrameworkBootstrap::loadInclude($this->classCacheFile);
554 // Mark the class cache as loaded
555 $this->classesCached = true;
560 * Tries to find the given class in our list. This method ignores silently
561 * missing classes or interfaces. So if you use class_exists() this method
562 * does not interrupt your program.
564 * @param $className The class that shall be loaded
566 * @throws InvalidArgumentException If strict-checking is enabled and class name is not following naming-convention
568 private function loadClassFile ($className) {
570 //* NOISY-DEBUG: */ printf('[%s:%d] className=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $className);
572 // The class name should contain at least 2 back-slashes, so split at them
573 $classNameParts = explode("\\", $className);
575 // At least 3 parts should be there
576 if ((self::$strictNamingConvention === true) && (count($classNameParts) < 5)) {
577 // Namespace scheme is: Project\Package[\SubPackage...]
578 throw new InvalidArgumentException(sprintf('Class name "%s" is not conform to naming-convention: Tld\Domain\Project\Package[\SubPackage...]\SomeFooBar', $className));
582 $shortClassName = array_pop($classNameParts);
584 // Create a name with prefix and suffix
585 $fileName = sprintf('%s%s%s', $this->prefix, $shortClassName, $this->suffix);
587 // Now look it up in our index
588 //* NOISY-DEBUG: */ printf('[%s:%d] ISSET: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
589 if ((isset($this->foundClasses[$fileName])) && (!isset($this->loadedClasses[$this->foundClasses[$fileName]->getPathname()]))) {
590 // File is found and not loaded so load it only once
591 //* NOISY-DEBUG: */ printf('[%s:%d] LOAD: %s - START' . PHP_EOL, __METHOD__, __LINE__, $fileName);
592 FrameworkBootstrap::loadInclude($this->foundClasses[$fileName]);
593 //* NOISY-DEBUG: */ printf('[%s:%d] LOAD: %s - END' . PHP_EOL, __METHOD__, __LINE__, $fileName);
595 // Count this loaded class/interface/exception
598 // Mark this class as loaded for other purposes than loading it.
599 $this->loadedClasses[$this->foundClasses[$fileName]->getPathname()] = true;
601 // Remove it from classes list so it won't be found twice.
602 //* NOISY-DEBUG: */ printf('[%s:%d] UNSET: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
603 unset($this->foundClasses[$fileName]);
605 // Developer mode excludes caching (better debugging)
606 if (!defined('DEVELOPER')) {
608 //* NOISY-DEBUG: */ printf('[%s:%d] classesCached=false' . PHP_EOL, __METHOD__, __LINE__);
609 $this->classesCached = false;
613 //* NOISY-DEBUG: */ printf('[%s:%d] 404: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);