3 namespace CoreFramework\Loader;
5 // Import framework stuff
6 use CoreFramework\Configuration\FrameworkConfiguration;
7 use CoreFramework\EntryPoint\ApplicationEntryPoint;
8 use CoreFramework\Object\BaseFrameworkSystem;
11 use \InvalidArgumentException;
12 use \RecursiveDirectoryIterator;
13 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 - 2017 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 * Filename for the list cache
106 private $listCacheFQFN = '';
109 * Cache for class content
111 private $classCacheFQFN = '';
114 * Counter for loaded include files
119 * Framework/application paths for classes, etc.
121 private static $frameworkPaths = array(
122 'exceptions', // Exceptions
123 'interfaces', // Interfaces
124 'classes', // Classes
125 'middleware' // The middleware
129 * Registered paths where test classes can be found. These are all relative
132 private static $testPaths = array();
135 * The protected constructor. Please use the factory method below, or use
136 * getSelfInstance() for singleton
140 protected function __construct () {
141 // This is empty for now
145 * The destructor makes it sure all caches got flushed
149 public function __destruct () {
150 // Skip here if dev-mode
151 if (defined('DEVELOPER')) {
155 // Skip here if already cached
156 if ($this->listCached === FALSE) {
157 // Writes the cache file of our list away
158 $cacheContent = json_encode($this->foundClasses);
159 file_put_contents($this->listCacheFQFN, $cacheContent);
162 // Skip here if already cached
163 if ($this->classesCached === FALSE) {
164 // Generate a full-cache of all classes
166 foreach (array_keys($this->loadedClasses) as $fqfn) {
168 $cacheContent .= file_get_contents($fqfn);
172 file_put_contents($this->classCacheFQFN, $cacheContent);
177 * Creates an instance of this class loader for given configuration instance
179 * @param $configInstance Configuration class instance
182 public static final function createClassLoader (FrameworkConfiguration $configInstance) {
183 // Get a new instance
184 $loaderInstance = new ClassLoader();
187 $loaderInstance->initLoader($configInstance);
189 // Return the prepared instance
190 return $loaderInstance;
194 * Scans for all framework classes, exceptions and interfaces.
198 public static function scanFrameworkClasses () {
200 //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
202 // Cache loader instance
203 $loaderInstance = self::getSelfInstance();
205 // Get config instance
206 $cfg = FrameworkConfiguration::getSelfInstance();
209 foreach (self::$frameworkPaths as $shortPath) {
211 //* NOISY-DEBUG: */ printf('[%s:%d]: shortPath=%s' . PHP_EOL, __METHOD__, __LINE__, $shortPath);
213 // Generate full path from it
214 $pathName = realpath(sprintf(
215 '%s/framework/main/%s/',
216 $cfg->getConfigEntry('base_path'),
221 //* NOISY-DEBUG: */ printf('[%s:%d]: pathName=%s' . PHP_EOL, __METHOD__, __LINE__, $pathName);
223 // Is it not FALSE and accessible?
224 if (is_bool($pathName)) {
227 } elseif (!is_readable($pathName)) {
228 // @TODO Throw exception instead of break
232 // Try to load the framework classes
233 $loaderInstance->scanClassPath($pathName);
237 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
241 * Scans for application's classes, etc.
245 public static function scanApplicationClasses () {
247 //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
249 // Get config instance
250 $cfg = FrameworkConfiguration::getSelfInstance();
252 // Load all classes for the application
253 foreach (self::$frameworkPaths as $shortPath) {
255 //* NOISY-DEBUG: */ printf('[%s:%d]: shortPath=%s' . PHP_EOL, __METHOD__, __LINE__, $shortPath);
258 $pathName = realpath(sprintf(
260 $cfg->getConfigEntry('application_path'),
261 $cfg->getConfigEntry('app_name'),
266 //* NOISY-DEBUG: */ printf('[%s:%d]: pathName[%s]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype($pathName), $pathName);
268 // Is the path readable?
269 if (is_dir($pathName)) {
270 // Try to load the application classes
271 ClassLoader::getSelfInstance()->scanClassPath($pathName);
276 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
280 * Scans for test classes, etc.
284 public static function scanTestsClasses () {
286 //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
288 // Get config instance
289 $cfg = FrameworkConfiguration::getSelfInstance();
291 // Load all classes for the application
292 foreach (self::$testPaths as $shortPath) {
294 //* NOISY-DEBUG: */ printf('[%s:%d]: shortPath=%s' . PHP_EOL, __METHOD__, __LINE__, $shortPath);
297 $pathName = realpath(sprintf(
299 $cfg->getConfigEntry('base_path'),
304 //* NOISY-DEBUG: */ printf('[%s:%d]: pathName[%s]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype($pathName), $pathName);
306 // Is the path readable?
307 if (is_dir($pathName)) {
308 // Try to load the application classes
309 ClassLoader::getSelfInstance()->scanClassPath($pathName);
314 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
318 * Registeres given relative path where test classes reside. For regular
319 * framework uses, they should not be loaded (and used).
321 * @param $relativePath Relative path to test classes
324 public static function registerTestsPath ($relativePath) {
326 self::$testPaths[$relativePath] = $relativePath;
332 * @param $className Name of the class to load
335 public static function autoLoad ($className) {
336 // Try to include this class
337 self::getSelfInstance()->loadClassFile($className);
341 * Singleton getter for an instance of this class
343 * @return $selfInstance A singleton instance of this class
345 public static final function getSelfInstance () {
346 // Is the instance there?
347 if (is_null(self::$selfInstance)) {
349 self::$selfInstance = ClassLoader::createClassLoader(FrameworkConfiguration::getSelfInstance());
352 // Return the instance
353 return self::$selfInstance;
357 * Scans recursively a local path for class files which must have a prefix and a suffix as given by $this->suffix and $this->prefix
359 * @param $basePath The relative base path to 'base_path' constant for all classes
360 * @param $ignoreList An optional list (array forced) of directory and file names which shall be ignored
363 public function scanClassPath ($basePath, array $ignoreList = array() ) {
364 // Is a list has been restored from cache, don't read it again
365 if ($this->listCached === TRUE) {
370 // Keep it in class for later usage
371 $this->ignoreList = $ignoreList;
374 * Ignore .htaccess by default as it is for protection of directories
377 array_push($ignoreList, '.htaccess');
380 * Set base directory which holds all our classes, an absolute path
381 * should be used here so is_dir(), is_file() and so on will always
382 * find the correct files and dirs.
384 $basePath2 = realpath($basePath);
386 // If the basePath is FALSE it is invalid
387 if ($basePath2 === FALSE) {
388 /* @TODO: Do not exit here. */
389 exit(__METHOD__ . ': Cannot read ' . $basePath . ' !' . PHP_EOL);
392 $basePath = $basePath2;
395 // Get a new iterator
396 //* NOISY-DEBUG: */ printf('[%s:%d] basePath=%s' . PHP_EOL, __METHOD__, __LINE__, $basePath);
397 $iteratorInstance = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($basePath), RecursiveIteratorIterator::CHILD_FIRST);
400 while ($iteratorInstance->valid()) {
402 $currentEntry = $iteratorInstance->current();
404 // Get filename from iterator
405 $fileName = $currentEntry->getFileName();
407 // Get the "FQFN" (path and file name)
408 $fqfn = $currentEntry->getRealPath();
410 // Current entry must be a file, not smaller than 100 bytes and not on ignore list
411 if ((!$currentEntry->isFile()) || (in_array($fileName, $this->ignoreList)) || (filesize($fqfn) < 100)) {
412 // Advance to next entry
413 $iteratorInstance->next();
415 // Skip non-file entries
416 //* NOISY-DEBUG: */ printf('[%s:%d] SKIP: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
420 // Is this file wanted?
421 //* NOISY-DEBUG: */ printf('[%s:%d] FOUND: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
422 if ((substr($fileName, 0, strlen($this->prefix)) == $this->prefix) && (substr($fileName, -strlen($this->suffix), strlen($this->suffix)) == $this->suffix)) {
423 // Add it to the list
424 //* NOISY-DEBUG: */ printf('[%s:%d] ADD: %s,fqfn=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName, $fqfn);
425 $this->foundClasses[$fileName] = $fqfn;
428 //* NOISY-DEBUG: */ printf('[%s:%d] NOT ADDED: %s,fqfn=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName, $fqfn);
431 // Advance to next entry
432 //* NOISY-DEBUG: */ printf('[%s:%d] NEXT: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
433 $iteratorInstance->next();
438 * Load extra config files
442 public function loadExtraConfigs () {
444 $oldPrefix = $this->prefix;
446 // Set new prefix (temporary!)
447 $this->prefix = 'config-';
449 // Set base directory
450 $basePath = $this->configInstance->getConfigEntry('base_path') . 'framework/config/';
452 // Load all classes from the config directory
453 $this->scanClassPath($basePath);
455 // Include these extra configs now
456 $this->includeExtraConfigs();
458 // Set back the old prefix
459 $this->prefix = $oldPrefix;
463 * Initializes our loader class
465 * @param $configInstance Configuration class instance
468 private function initLoader (FrameworkConfiguration $configInstance) {
469 // Set configuration instance
470 $this->configInstance = $configInstance;
472 // Construct the FQFN for the cache
473 if (!defined('DEVELOPER')) {
474 $this->listCacheFQFN = $this->configInstance->getConfigEntry('local_db_path') . 'list-' . $this->configInstance->getConfigEntry('app_name') . '.cache';
475 $this->classCacheFQFN = $this->configInstance->getConfigEntry('local_db_path') . 'class-' . $this->configInstance->getConfigEntry('app_name') . '.cache';
478 // Set suffix and prefix from configuration
479 $this->suffix = $configInstance->getConfigEntry('class_suffix');
480 $this->prefix = $configInstance->getConfigEntry('class_prefix');
483 self::$selfInstance = $this;
485 // Skip here if no dev-mode
486 if (defined('DEVELOPER')) {
490 // IS the cache there?
491 if (BaseFrameworkSystem::isReadableFile($this->listCacheFQFN)) {
493 $cacheContent = file_get_contents($this->listCacheFQFN);
496 $this->foundClasses = json_decode($cacheContent);
498 // List has been restored from cache!
499 $this->listCached = TRUE;
502 // Does the class cache exist?
503 if (BaseFrameworkSystem::isReadableFile($this->listCacheFQFN)) {
505 require($this->classCacheFQFN);
507 // Mark the class cache as loaded
508 $this->classesCached = TRUE;
513 * Tries to find the given class in our list. This method ignores silently
514 * missing classes or interfaces. So if you use class_exists() this method
515 * does not interrupt your program.
517 * @param $className The class that shall be loaded
520 private function loadClassFile ($className) {
522 //* NOISY-DEBUG: */ printf('[%s:%d] className=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $className);
524 // The class name should contain at least 2 back-slashes, so split at them
525 $classNameParts = explode("\\", $className);
527 // At least 3 parts should be there
528 if (count($classNameParts) < 3) {
529 // Namespace scheme is: Project\Package[\SubPackage...]
530 throw new InvalidArgumentException(sprintf('Class name "%s" is not conform to naming-convention: Project\Package[\SubPackage...]\SomeFooBar', $className));
534 $shortClassName = array_pop($classNameParts);
536 // Create a name with prefix and suffix
537 $fileName = $this->prefix . $shortClassName . $this->suffix;
539 // Now look it up in our index
540 //* NOISY-DEBUG: */ printf('[%s:%d] ISSET: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
541 if ((isset($this->foundClasses[$fileName])) && (!isset($this->loadedClasses[$this->foundClasses[$fileName]]))) {
542 // File is found and not loaded so load it only once
543 //* NOISY-DEBUG: */ printf('[%s:%d] LOAD: %s - START' . PHP_EOL, __METHOD__, __LINE__, $fileName);
544 require($this->foundClasses[$fileName]);
545 //* NOISY-DEBUG: */ printf('[%s:%d] LOAD: %s - END' . PHP_EOL, __METHOD__, __LINE__, $fileName);
547 // Count this loaded class/interface/exception
550 // Mark this class as loaded for other purposes than loading it.
551 $this->loadedClasses[$this->foundClasses[$fileName]] = TRUE;
553 // Remove it from classes list so it won't be found twice.
554 //* NOISY-DEBUG: */ printf('[%s:%d] UNSET: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
555 unset($this->foundClasses[$fileName]);
557 // Developer mode excludes caching (better debugging)
558 if (!defined('DEVELOPER')) {
560 //* NOISY-DEBUG: */ printf('[%s:%d] classesCached=FALSE' . PHP_EOL, __METHOD__, __LINE__);
561 $this->classesCached = FALSE;
565 //* NOISY-DEBUG: */ printf('[%s:%d] 404: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
570 * Includes all extra config files
574 private function includeExtraConfigs () {
575 // Run through all class names (should not be much)
576 foreach ($this->foundClasses as $fileName => $fqfn) {
578 if (substr($fileName, 0, strlen($this->prefix)) == $this->prefix) {
580 //* NOISY-DEBUG: */ printf('[%s:%d] LOAD: %s - START' . PHP_EOL, __METHOD__, __LINE__, $fileName);
582 //* NOISY-DEBUG: */ printf('[%s:%d] LOAD: %s - END' . PHP_EOL, __METHOD__, __LINE__, $fileName);
584 // Remove it from the list
585 //* NOISY-DEBUG: */ printf('[%s:%d] UNSET: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
586 unset($this->foundClasses[$fileName]);
592 * Getter for total include counter
594 * @return $total Total loaded include files
596 public final function getTotal () {
601 * Getter for a printable list of included main/interfaces/exceptions
603 * @param $includeList A printable include list
605 public function getPrintableIncludeList () {
608 foreach ($this->loadedClasses as $classFile) {
609 $includeList .= basename($classFile) . '<br />' . PHP_EOL;