3 namespace CoreFramework\Loader;
5 // Import framework stuff
6 use CoreFramework\Configuration\FrameworkConfiguration;
7 use CoreFramework\Object\BaseFrameworkSystem;
10 use \InvalidArgumentException;
11 use \RecursiveDirectoryIterator;
12 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 - 2017 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 * - Namespace scheme Project\Package[\SubPackage...] is fully supported and
39 * throws an InvalidArgumentException if not present. The last part will be
40 * always the class' name.
42 * - Some comments improved, other minor improvements
44 * - Constructor is now empty and factory method 'createClassLoader' is created
45 * - renamed loadClasses to scanClassPath
46 * - Added initLoader()
48 * - ClassLoader rewritten to PHP SPL's own RecursiveIteratorIterator class
50 * - loadClasses rewritten to fix some notices
53 * ----------------------------------
57 * Instance of this class
59 private static $selfInstance = NULL;
62 * Array with all found classes
64 private $foundClasses = array();
67 * List of loaded classes
69 private $loadedClasses = array();
72 * Suffix with extension for all class files
74 private $prefix = 'class_';
77 * Suffix with extension for all class files
79 private $suffix = '.php';
82 * A list for directory names (no leading/trailing slashes!) which not be scanned by the path scanner
85 private $ignoreList = array();
88 * Debug this class loader? (TRUE = yes, FALSE = no)
90 private $debug = FALSE;
93 * Whether the file list is cached
95 private $listCached = FALSE;
98 * Wethe class content has been cached
100 private $classesCached = FALSE;
103 * Filename for the list cache
105 private $listCacheFQFN = '';
108 * Cache for class content
110 private $classCacheFQFN = '';
113 * Counter for loaded include files
118 * Framework/application paths for classes, etc.
120 private static $frameworkPaths = array(
121 'exceptions', // Exceptions
122 'interfaces', // Interfaces
123 'classes', // Classes
124 'middleware' // The middleware
129 * The protected constructor. Please use the factory method below, or use
130 * getSelfInstance() for singleton
134 protected function __construct () {
135 // Is currently empty
139 * The destructor makes it sure all caches got flushed
143 public function __destruct () {
144 // Skip here if dev-mode
145 if (defined('DEVELOPER')) {
149 // Skip here if already cached
150 if ($this->listCached === FALSE) {
151 // Writes the cache file of our list away
152 $cacheContent = json_encode($this->foundClasses);
153 file_put_contents($this->listCacheFQFN, $cacheContent);
156 // Skip here if already cached
157 if ($this->classesCached === FALSE) {
158 // Generate a full-cache of all classes
160 foreach (array_keys($this->loadedClasses) as $fqfn) {
162 $cacheContent .= file_get_contents($fqfn);
166 file_put_contents($this->classCacheFQFN, $cacheContent);
171 * Creates an instance of this class loader for given configuration instance
173 * @param $configInstance Configuration class instance
176 public static final function createClassLoader (FrameworkConfiguration $configInstance) {
177 // Get a new instance
178 $loaderInstance = new ClassLoader();
181 $loaderInstance->initLoader($configInstance);
183 // Return the prepared instance
184 return $loaderInstance;
188 * Scans for all framework classes, exceptions and interfaces.
192 public static function scanFrameworkClasses () {
193 // Cache loader instance
194 $loaderInstance = self::getSelfInstance();
197 foreach (self::$frameworkPaths as $pathName) {
198 // Try to load the framework classes
199 $loaderInstance->scanClassPath('inc/main/' . $pathName . '/');
204 * Scans for application's classes, etc.
208 public static function scanApplicationClasses () {
209 // Get config instance
210 $cfg = FrameworkConfiguration::getSelfInstance();
212 // Load all classes for the application
213 foreach (self::$frameworkPaths as $class) {
215 $path = sprintf('%s/%s/%s', $cfg->getConfigEntry('application_path'), $cfg->getConfigEntry('app_name'), $class);
217 // Is the path readable?
219 // Try to load the application classes
220 ClassLoader::getSelfInstance()->scanClassPath($path);
226 * Initializes our loader class
228 * @param $configInstance Configuration class instance
231 protected function initLoader (FrameworkConfiguration $configInstance) {
232 // Set configuration instance
233 $this->configInstance = $configInstance;
235 // Construct the FQFN for the cache
236 if (!defined('DEVELOPER')) {
237 $this->listCacheFQFN = $this->configInstance->getConfigEntry('local_db_path') . 'list-' . $this->configInstance->getConfigEntry('app_name') . '.cache';
238 $this->classCacheFQFN = $this->configInstance->getConfigEntry('local_db_path') . 'class-' . $this->configInstance->getConfigEntry('app_name') . '.cache';
241 // Set suffix and prefix from configuration
242 $this->suffix = $configInstance->getConfigEntry('class_suffix');
243 $this->prefix = $configInstance->getConfigEntry('class_prefix');
246 self::$selfInstance = $this;
248 // Skip here if no dev-mode
249 if (defined('DEVELOPER')) {
253 // IS the cache there?
254 if (BaseFrameworkSystem::isReadableFile($this->listCacheFQFN)) {
256 $cacheContent = file_get_contents($this->listCacheFQFN);
259 $this->foundClasses = json_decode($cacheContent);
261 // List has been restored from cache!
262 $this->listCached = TRUE;
265 // Does the class cache exist?
266 if (BaseFrameworkSystem::isReadableFile($this->listCacheFQFN)) {
268 require($this->classCacheFQFN);
270 // Mark the class cache as loaded
271 $this->classesCached = TRUE;
278 * @param $className Name of the class to load
281 public static function autoLoad ($className) {
282 // Try to include this class
283 self::getSelfInstance()->loadClassFile($className);
287 * Singleton getter for an instance of this class
289 * @return $selfInstance A singleton instance of this class
291 public static final function getSelfInstance () {
292 // Is the instance there?
293 if (is_null(self::$selfInstance)) {
295 self::$selfInstance = ClassLoader::createClassLoader(FrameworkConfiguration::getSelfInstance());
298 // Return the instance
299 return self::$selfInstance;
303 * Scans recursively a local path for class files which must have a prefix and a suffix as given by $this->suffix and $this->prefix
305 * @param $basePath The relative base path to 'base_path' constant for all classes
306 * @param $ignoreList An optional list (array forced) of directory and file names which shall be ignored
309 public function scanClassPath ($basePath, array $ignoreList = array() ) {
310 // Is a list has been restored from cache, don't read it again
311 if ($this->listCached === TRUE) {
316 // Keep it in class for later usage
317 $this->ignoreList = $ignoreList;
320 * Ignore .htaccess by default as it is for protection of directories
323 array_push($ignoreList, '.htaccess');
326 * Set base directory which holds all our classes, an absolute path
327 * should be used here so is_dir(), is_file() and so on will always
328 * find the correct files and dirs.
330 $basePath2 = realpath($basePath);
332 // If the basePath is FALSE it is invalid
333 if ($basePath2 === FALSE) {
334 /* @TODO: Do not exit here. */
335 exit(__METHOD__ . ': Cannot read ' . $basePath . ' !' . PHP_EOL);
338 $basePath = $basePath2;
341 // Get a new iterator
342 /* NOISY-DEBUG: */ printf('[%s:%d] basePath=%s' . PHP_EOL, __METHOD__, __LINE__, $basePath);
343 $iteratorInstance = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($basePath), RecursiveIteratorIterator::CHILD_FIRST);
346 while ($iteratorInstance->valid()) {
348 $currentEntry = $iteratorInstance->current();
350 // Get filename from iterator
351 $fileName = $currentEntry->getFileName();
353 // Get the "FQFN" (path and file name)
354 $fqfn = $currentEntry->getRealPath();
356 // Current entry must be a file, not smaller than 100 bytes and not on ignore list
357 if ((!$currentEntry->isFile()) || (in_array($fileName, $this->ignoreList)) || (filesize($fqfn) < 100)) {
358 // Advance to next entry
359 $iteratorInstance->next();
361 // Skip non-file entries
362 /* NOISY-DEBUG: */ printf('[%s:%d] SKIP: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
366 // Is this file wanted?
367 /* NOISY-DEBUG: */ printf('[%s:%d] FOUND: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
368 if ((substr($fileName, 0, strlen($this->prefix)) == $this->prefix) && (substr($fileName, -strlen($this->suffix), strlen($this->suffix)) == $this->suffix)) {
369 // Add it to the list
370 /* NOISY-DEBUG: */ printf('[%s:%d] ADD: %s,fqfn=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName, $fqfn);
371 $this->foundClasses[$fileName] = $fqfn;
374 /* NOISY-DEBUG: */ printf('[%s:%d] NOT ADDED: %s,fqfn=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName, $fqfn);
377 // Advance to next entry
378 /* NOISY-DEBUG: */ printf('[%s:%d] NEXT: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
379 $iteratorInstance->next();
384 * Load extra config files
388 public function loadExtraConfigs () {
390 $oldPrefix = $this->prefix;
392 // Set new prefix (temporary!)
393 $this->prefix = 'config-';
395 // Set base directory
396 $basePath = $this->configInstance->getConfigEntry('base_path') . 'inc/config/';
398 // Load all classes from the config directory
399 $this->scanClassPath($basePath);
401 // Include these extra configs now
402 $this->includeExtraConfigs();
404 // Set back the old prefix
405 $this->prefix = $oldPrefix;
409 * Tries to find the given class in our list. This method ignores silently
410 * missing classes or interfaces. So if you use class_exists() this method
411 * does not interrupt your program.
413 * @param $className The class that shall be loaded
416 private function loadClassFile ($className) {
418 /* NOISY-DEBUG: */ printf('[%s:%d] className=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $className);
420 // The class name should contain at least 2 back-slashes, so split at them
421 $classNameParts = explode("\\", $className);
423 // At least 3 parts should be there
424 if (count($classNameParts) < 3) {
425 // Namespace scheme is: Project\Package[\SubPackage...]
426 throw new InvalidArgumentException(sprintf('Class name "%s" is not conform to naming-convention: Project\Package[\SubPackage...]\SomeFooBar', $className));
430 $shortClassName = array_pop($classNameParts);
432 // Create a name with prefix and suffix
433 $fileName = $this->prefix . $shortClassName . $this->suffix;
435 // Now look it up in our index
436 /* NOISY-DEBUG: */ printf('[%s:%d] ISSET: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
437 if ((isset($this->foundClasses[$fileName])) && (!isset($this->loadedClasses[$this->foundClasses[$fileName]]))) {
438 // File is found and not loaded so load it only once
439 /* NOISY-DEBUG: */ printf('[%s:%d] LOAD: %s - START' . PHP_EOL, __METHOD__, __LINE__, $fileName);
440 require($this->foundClasses[$fileName]);
441 /* NOISY-DEBUG: */ printf('[%s:%d] LOAD: %s - END' . PHP_EOL, __METHOD__, __LINE__, $fileName);
443 // Count this loaded class/interface/exception
446 // Mark this class as loaded for other purposes than loading it.
447 $this->loadedClasses[$this->foundClasses[$fileName]] = TRUE;
449 // Remove it from classes list so it won't be found twice.
450 /* NOISY-DEBUG: */ printf('[%s:%d] UNSET: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
451 unset($this->foundClasses[$fileName]);
453 // Developer mode excludes caching (better debugging)
454 if (!defined('DEVELOPER')) {
456 /* NOISY-DEBUG: */ printf('[%s:%d] classesCached=FALSE' . PHP_EOL, __METHOD__, __LINE__);
457 $this->classesCached = FALSE;
461 /* NOISY-DEBUG: */ printf('[%s:%d] 404: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
466 * Includes all extra config files
470 private function includeExtraConfigs () {
471 // Run through all class names (should not be much)
472 foreach ($this->foundClasses as $fileName => $fqfn) {
474 if (substr($fileName, 0, strlen($this->prefix)) == $this->prefix) {
476 /* NOISY-DEBUG: */ printf('[%s:%d] LOAD: %s - START' . PHP_EOL, __METHOD__, __LINE__, $fileName);
478 /* NOISY-DEBUG: */ printf('[%s:%d] LOAD: %s - END' . PHP_EOL, __METHOD__, __LINE__, $fileName);
480 // Remove it from the list
481 /* NOISY-DEBUG: */ printf('[%s:%d] UNSET: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
482 unset($this->foundClasses[$fileName]);
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;