Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * @Author neun
- * @since 20.04.2015 23:55
- */
- Autoload::load();
- class Autoload
- {
- /**
- * The class map.
- *
- * @var array
- */
- private static $aClasses = array();
- /**
- * Root directory of the application.
- *
- * @var string
- */
- private static $sRootDir;
- /**
- * Load class map and register.
- */
- public static function load()
- {
- self::$sRootDir = str_replace(
- array('libs\mine', 'libs/mine', '\\'),
- array('', '', '/'),
- __DIR__
- );
- self::loadClassMap();
- self::register();
- }
- /**
- * Register mapped classes.
- */
- private static function register()
- {
- spl_autoload_register(
- /**
- * @param $sClass
- */
- function($sClass)
- {
- $sClassFile = self::preRegister($sClass);
- if (is_readable($sClassFile))
- {
- require_once($sClassFile);
- }
- if (!class_exists($sClass))
- {
- die("Class {$sClass} not found!");
- }
- });
- }
- /**
- * Check whether the requested class exists, re-generate map if neccessary.
- *
- * @param string $sClass
- * @param bool $isRetry
- * @return string
- * @throws Exception
- */
- private static function preRegister($sClass, $isRetry = false)
- {
- if (!array_key_exists($sClass, self::$aClasses))
- {
- if (false === $isRetry)
- {
- // Try to regenerate once.
- self::generateClassMap();
- }
- elseif(!array_key_exists($sClass, self::$aClasses))
- {
- // Die if the class is still not there
- die("Class {$sClass} appears to be invalid - dying!");
- }
- self::preRegister($sClass, true);
- }
- else
- {
- return rtrim(self::$sRootDir) .'/'. self::$aClasses[$sClass];
- }
- return rtrim(self::$sRootDir) .'/'. self::$aClasses[$sClass];
- }
- /**
- * Try loading the classmap from an existing file else regenerate.
- */
- private static function loadClassMap()
- {
- if (is_readable('classmap.json'))
- {
- // Load from existing file.
- self::$aClasses = (array) json_decode(file_get_contents(__DIR__ .'/classmap.json'));
- }
- else
- {
- // Regenerate and write file.
- self::generateClassMap();
- }
- }
- /**
- * Generate Classmap and dump to json file.
- */
- private static function generateClassMap()
- {
- // Generate class map.
- self::readFolders(self::$sRootDir);
- // Dump class map to json file.
- file_put_contents(__DIR__ .'/classmap.json', json_encode(self::$aClasses, JSON_UNESCAPED_SLASHES));
- }
- /**
- * Add classes and paths recursive.
- *
- * @param $sDir
- */
- private static function readFolders($sDir)
- {
- foreach (glob($sDir . '/*') as $sPath)
- {
- // If its a directory, scan again else add class to map.
- if (is_dir($sPath))
- {
- self::readFolders($sPath);
- }
- else
- {
- if (preg_match('#.*\/([A-Z][A-Za-z\d]+)\.php$#', $sPath, $m) && $m[1] != 'Autoload')
- {
- self::$aClasses[$m[1]] = str_replace(self::$sRootDir . '/', '', $m[0]);
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement