<?php
namespace gnomephp;
/**
*
* Lightweight spl autoloader for gnomephp namespace and sub namespace.
* Takes use of GNOME_FW_PATH ( Location is to the root namespace "gnomephp".
* @author peec
*
*/
class AutoLoader {
private $uses = array();
public function __construct() {
spl_autoload_register(array($this, 'loader'));
// Add support for load of new namespaces.
$uses = Configuration::get('application', 'use');
if ($uses && is_array($uses) && count($uses) > 0){
$this->uses = $uses;
}
}
/**
* Tries to load a class.
* @param string $className
* @throws AutoLoaderException
*/
private function loader($className) {
// Strip of \ start of ns if any.
if (substr($className, 0, 1) == '\\')$className = substr($className, 1);
if (substr($className, 0, 8) == 'gnomephp'){
$clsName = $this->dirify(substr($className, 9, strlen($className)));
$f = GNOME_FW_PATH.DIRECTORY_SEPARATOR.$clsName.'.php';
if (file_exists($f))require_once $f;
else throw new AutoLoaderException("Could not include file $f because it did not exist.");
}else if (@defined('GNOME_APP_NS') && @defined('GNOME_APP_PATH') && substr($className, 0, strlen(GNOME_APP_NS)) == GNOME_APP_NS){
$clsName = $this->dirify(substr($className, strlen(GNOME_APP_NS)+1, strlen($className)));
$f = GNOME_APP_PATH . DIRECTORY_SEPARATOR.$clsName.'.php';
if (file_exists($f))require_once $f;
else throw new AutoLoaderException("Could not include file $f because it did not exist.");
}else{
foreach($this->uses as $ns => $basePath){
if (substr($className, 0, strlen($ns)) == $ns){
// Allow variable.
$basePath = str_replace('$gnomeAppDir', GNOME_FW_PATH . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'apps', $basePath);
$clsName = $this->dirify(substr($className, strlen($ns)+1, strlen($className)));
$f = $basePath . DIRECTORY_SEPARATOR . $clsName . '.php';
if (file_exists($f))require_once $f;
else throw new AutoLoaderException("Could not include file $f because it did not exist.");
}
}
}
}
/**
* Converts ns path ( eg. gnomephp\sub\Test )
* to
* gnomephp (DIRECTORY_SEPARATOR) sub (DIRECTORY_SEPARATOR) Test
*
* This must be done since linux systems uses another directory separator then windows systems.
* @param string $ns A namespace with associated class. eg. gnomephp\sub\Test
*/
private function dirify($ns){
return str_replace('\\', DIRECTORY_SEPARATOR, $ns);
}
}