3 namespace CoreFramework\Loader;
5 // Import framework stuff
6 use CoreFramework\Configuration\FrameworkConfiguration;
7 use CoreFramework\Object\BaseFrameworkSystem;
10 use \RecursiveDirectoryIterator;
11 use \RecursiveIteratorIterator;
14 * This class loads class include files with a specific prefix and suffix
16 * @author Roland Haeder <webmaster@shipsimu.org>
18 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
19 * @license GNU GPL 3.0 or any newer version
20 * @link http://www.shipsimu.org
22 * This program is free software: you can redistribute it and/or modify
23 * it under the terms of the GNU General Public License as published by
24 * the Free Software Foundation, either version 3 of the License, or
25 * (at your option) any later version.
27 * This program is distributed in the hope that it will be useful,
28 * but WITHOUT ANY WARRANTY; without even the implied warranty of
29 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
30 * GNU General Public License for more details.
32 * You should have received a copy of the GNU General Public License
33 * along with this program. If not, see <http://www.gnu.org/licenses/>.
35 * ----------------------------------
37 * - Namespace scheme Project\Package[\SubPackage...] is fully supported and
38 * throws an E_USER_WARNING if not present. The last part will be always the
41 * - Some comments improved, other minor improvements
43 * - Constructor is now empty and factory method 'createClassLoader' is created
44 * - renamed loadClasses to scanClassPath
45 * - Added initLoader()
47 * - ClassLoader rewritten to PHP SPL's own RecursiveIteratorIterator class
49 * - loadClasses rewritten to fix some notices
52 * ----------------------------------
56 * Instance of this class
58 private static $selfInstance = NULL;
61 * Array with all classes
63 private $classes = array();
66 * List of loaded classes
68 private $loadedClasses = array();
71 * Suffix with extension for all class files
73 private $prefix = 'class_';
76 * Suffix with extension for all class files
78 private $suffix = '.php';
81 * A list for directory names (no leading/trailing slashes!) which not be scanned by the path scanner
84 private $ignoreList = array();
87 * Debug this class loader? (TRUE = yes, FALSE = no)
89 private $debug = FALSE;
92 * Whether the file list is cached
94 private $listCached = FALSE;
97 * Wethe class content has been cached
99 private $classesCached = FALSE;
102 * Filename for the list cache
104 private $listCacheFQFN = '';
107 * Cache for class content
109 private $classCacheFQFN = '';
112 * Counter for loaded include files
117 * Framework/application paths for classes, etc.
119 private static $frameworkPaths = array(
120 'exceptions', // Exceptions
121 'interfaces', // Interfaces
122 'classes', // Classes
123 'middleware' // The middleware
128 * The protected constructor. Please use the factory method below, or use
129 * getSelfInstance() for singleton
133 protected function __construct () {
134 // Is currently empty
138 * The destructor makes it sure all caches got flushed
142 public function __destruct () {
143 // Skip here if dev-mode
144 if (defined('DEVELOPER')) {
148 // Skip here if already cached
149 if ($this->listCached === FALSE) {
150 // Writes the cache file of our list away
151 $cacheContent = json_encode($this->classes);
152 file_put_contents($this->listCacheFQFN, $cacheContent);
155 // Skip here if already cached
156 if ($this->classesCached === FALSE) {
157 // Generate a full-cache of all classes
159 foreach ($this->loadedClasses as $fqfn) {
161 $cacheContent .= file_get_contents($fqfn);
165 file_put_contents($this->classCacheFQFN, $cacheContent);
170 * Creates an instance of this class loader for given configuration instance
172 * @param $configInstance Configuration class instance
175 public static final function createClassLoader (FrameworkConfiguration $configInstance) {
176 // Get a new instance
177 $loaderInstance = new ClassLoader();
180 $loaderInstance->initLoader($configInstance);
182 // Return the prepared instance
183 return $loaderInstance;
187 * Scans for all framework classes, exceptions and interfaces.
191 public static function scanFrameworkClasses () {
192 // Cache loader instance
193 $loaderInstance = self::getSelfInstance();
196 foreach (self::$frameworkPaths as $pathName) {
197 // Try to load the framework classes
198 $loaderInstance->scanClassPath('inc/main/' . $pathName . '/');
203 * Scans for application's classes, etc.
207 public static function scanApplicationClasses () {
208 // Get config instance
209 $cfg = FrameworkConfiguration::getSelfInstance();
211 // Load all classes for the application
212 foreach (self::$frameworkPaths as $class) {
214 $path = sprintf('%s/%s/%s', $cfg->getConfigEntry('application_path'), $cfg->getConfigEntry('app_name'), $class);
216 // Is the path readable?
218 // Try to load the application classes
219 ClassLoader::getSelfInstance()->scanClassPath($path);
225 * Initializes our loader class
227 * @param $configInstance Configuration class instance
230 protected function initLoader (FrameworkConfiguration $configInstance) {
231 // Set configuration instance
232 $this->configInstance = $configInstance;
234 // Construct the FQFN for the cache
235 if (!defined('DEVELOPER')) {
236 $this->listCacheFQFN = $this->configInstance->getConfigEntry('local_db_path') . 'list-' . $this->configInstance->getConfigEntry('app_name') . '.cache';
237 $this->classCacheFQFN = $this->configInstance->getConfigEntry('local_db_path') . 'class-' . $this->configInstance->getConfigEntry('app_name') . '.cache';
240 // Set suffix and prefix from configuration
241 $this->suffix = $configInstance->getConfigEntry('class_suffix');
242 $this->prefix = $configInstance->getConfigEntry('class_prefix');
245 self::$selfInstance = $this;
247 // Skip here if no dev-mode
248 if (defined('DEVELOPER')) {
252 // IS the cache there?
253 if (BaseFrameworkSystem::isReadableFile($this->listCacheFQFN)) {
255 $cacheContent = file_get_contents($this->listCacheFQFN);
258 $this->classes = json_decode($cacheContent);
260 // List has been restored from cache!
261 $this->listCached = TRUE;
264 // Does the class cache exist?
265 if (BaseFrameworkSystem::isReadableFile($this->listCacheFQFN)) {
267 require($this->classCacheFQFN);
269 // Mark the class cache as loaded
270 $this->classesCached = TRUE;
277 * @param $className Name of the class to load
280 public static function autoLoad ($className) {
281 // Try to include this class
282 self::getSelfInstance()->includeClass($className);
286 * Singleton getter for an instance of this class
288 * @return $selfInstance A singleton instance of this class
290 public static final function getSelfInstance () {
291 // Is the instance there?
292 if (is_null(self::$selfInstance)) {
294 self::$selfInstance = ClassLoader::createClassLoader(FrameworkConfiguration::getSelfInstance());
297 // Return the instance
298 return self::$selfInstance;
302 * Scans recursively a local path for class files which must have a prefix and a suffix as given by $this->suffix and $this->prefix
304 * @param $basePath The relative base path to 'base_path' constant for all classes
305 * @param $ignoreList An optional list (array forced) of directory and file names which shall be ignored
308 public function scanClassPath ($basePath, array $ignoreList = array() ) {
309 // Is a list has been restored from cache, don't read it again
310 if ($this->listCached === TRUE) {
315 // Keep it in class for later usage
316 $this->ignoreList = $ignoreList;
319 * Ignore .htaccess by default as it is for protection of directories
322 array_push($ignoreList, '.htaccess');
325 * Set base directory which holds all our classes, an absolute path
326 * should be used here so is_dir(), is_file() and so on will always
327 * find the correct files and dirs.
329 $basePath2 = realpath($basePath);
331 // If the basePath is FALSE it is invalid
332 if ($basePath2 === FALSE) {
333 /* @TODO: Do not exit here. */
334 exit(__METHOD__ . ': Cannot read ' . $basePath . ' !' . PHP_EOL);
337 $basePath = $basePath2;
340 // Get a new iterator
341 /* NOISY-DEBUG: */ printf('[%s:%d] basePath=%s' . PHP_EOL, __METHOD__, __LINE__, $basePath);
342 $iteratorInstance = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($basePath), RecursiveIteratorIterator::CHILD_FIRST);
345 while ($iteratorInstance->valid()) {
347 $currentEntry = $iteratorInstance->current();
349 // Get filename from iterator
350 $fileName = $currentEntry->getFileName();
352 // Get the "FQFN" (path and file name)
353 $fqfn = $currentEntry->getRealPath();
355 // Current entry must be a file, not smaller than 100 bytes and not on ignore list
356 if ((!$currentEntry->isFile()) || (in_array($fileName, $this->ignoreList)) || (filesize($fqfn) < 100)) {
357 // Advance to next entry
358 $iteratorInstance->next();
360 // Skip non-file entries
361 /* NOISY-DEBUG: */ printf('[%s:%d] SKIP: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
365 // Is this file wanted?
366 /* NOISY-DEBUG: */ printf('[%s:%d] FOUND: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
367 if ((substr($fileName, 0, strlen($this->prefix)) == $this->prefix) && (substr($fileName, -strlen($this->suffix), strlen($this->suffix)) == $this->suffix)) {
368 // Add it to the list
369 /* NOISY-DEBUG: */ printf('[%s:%d] ADD: %s,fqfn=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName, $fqfn);
370 $this->classes[$fileName] = $fqfn;
373 /* NOISY-DEBUG: */ printf('[%s:%d] NOT ADDED: %s,fqfn=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName, $fqfn);
376 // Advance to next entry
377 /* NOISY-DEBUG: */ printf('[%s:%d] NEXT: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
378 $iteratorInstance->next();
383 * Load extra config files
387 public function loadExtraConfigs () {
389 $oldPrefix = $this->prefix;
391 // Set new prefix (temporary!)
392 $this->prefix = 'config-';
394 // Set base directory
395 $basePath = $this->configInstance->getConfigEntry('base_path') . 'inc/config/';
397 // Load all classes from the config directory
398 $this->scanClassPath($basePath);
400 // Include these extra configs now
401 $this->includeExtraConfigs();
403 // Set back the old prefix
404 $this->prefix = $oldPrefix;
408 * Tries to find the given class in our list. This method ignores silently
409 * missing classes or interfaces. So if you use class_exists() this method
410 * does not interrupt your program.
412 * @param $className The class that shall be loaded
415 public function includeClass ($className) {
416 // The class name should contain at least 2 back-slashes, so split at them
417 $classNameParts = explode("\\", $className);
419 // At least 3 parts should be there
420 if (count($classNameParts) < 3) {
421 // Namespace scheme is: Project\Package[\SubPackage...]
422 trigger_error(sprintf('Class name "%s" is not after naming-convention: Project\Package[\SubPackage...]', $className), E_USER_WARNING);
426 $shortClassName = array_pop($classNameParts);
428 // Create a name with prefix and suffix
429 $fileName = $this->prefix . $shortClassName . $this->suffix;
431 // Now look it up in our index
432 /* NOISY-DEBUG: */ printf('[%s:%d] ISSET: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
433 if ((isset($this->classes[$fileName])) && (!in_array($this->classes[$fileName], $this->loadedClasses))) {
434 // File is found and not loaded so load it only once
435 /* NOISY-DEBUG: */ printf('[%s:%d] LOAD: %s - START' . PHP_EOL, __METHOD__, __LINE__, $fileName);
436 require($this->classes[$fileName]);
437 /* NOISY-DEBUG: */ printf('[%s:%d] LOAD: %s - END' . PHP_EOL, __METHOD__, __LINE__, $fileName);
439 // Count this loaded class/interface/exception
442 // Mark this class as loaded for other purposes than loading it.
443 array_push($this->loadedClasses, $this->classes[$fileName]);
445 // Remove it from classes list so it won't be found twice.
446 /* NOISY-DEBUG: */ printf('[%s:%d] UNSET: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
447 unset($this->classes[$fileName]);
449 // Developer mode excludes caching (better debugging)
450 if (!defined('DEVELOPER')) {
452 /* NOISY-DEBUG: */ printf('[%s:%d] classesCached=FALSE' . PHP_EOL, __METHOD__, __LINE__);
453 $this->classesCached = FALSE;
457 /* NOISY-DEBUG: */ printf('[%s:%d] 404: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
462 * Includes all extra config files
466 private function includeExtraConfigs () {
467 // Run through all class names (should not be much)
468 foreach ($this->classes as $fileName => $fqfn) {
470 if (substr($fileName, 0, strlen($this->prefix)) == $this->prefix) {
474 // Remove it from the list
475 /* NOISY-DEBUG: */ printf('[%s:%d] UNSET: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
476 unset($this->classes[$fileName]);
482 * Getter for total include counter
484 * @return $total Total loaded include files
486 public final function getTotal () {
491 * Getter for a printable list of included main/interfaces/exceptions
493 * @param $includeList A printable include list
495 public function getPrintableIncludeList () {
498 foreach ($this->loadedClasses as $classFile) {
499 $includeList .= basename($classFile) . '<br />' . PHP_EOL;