<?php

/**
 * Description of Autoloader
 *
 * @author Arkadiusz Rychlik <a.rychlik at eppe.com.pl>
 */
class Rtn_Autoloader extends Rtn_Autoloader_Core {

	static $scan_dirs = array('APP_CLASSES_PATH' => APP_CLASSES_PATH, 'CLASSES_PATH' => CLASSES_PATH, 'LIBRARY_PATH' => LIBRARY_PATH, 'MODULES_PATH' => MODULES_PATH, 'VENDORS_PATH' => VENDORS_PATH);
	static $found_dirs = array();

	public static function auto_load($class) {
		// Transform the class name according to PSR-0
		$class = ltrim($class, '\\');
		$file = '';
		$namespace = '';
		$dir = '';

		if ($last_namespace_position = strripos($class, '\\')) {
			$namespace = substr($class, 0, $last_namespace_position);
			$class = substr($class, $last_namespace_position + 1);
			$file = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
		}

		$file .= str_replace('_', DIRECTORY_SEPARATOR, $class);

		if ($path = static::find_file($file, $dir)) {
			// Load the class file
			if (file_exists($path)) {
				require $path;
				// Class has been found
				return TRUE;
			} else {
				// File does not exists
				return FALSE;
			}
		}
		// Class is not in the filesystem
		return FALSE;
	}

	/**
	 *
	 * @param string $dir
	 * @param plik $file
	 * @param rozszerzenie $ext
	 */
	final static function find_file($file, $dir = NULL, $ext = 'php', $must_exist=true) {
		if (empty(static::$found_dirs)) {
			foreach (static::$scan_dirs as $scan_dir_key => $scan_dir) {
				foreach (new DirectoryIterator($scan_dir) as $element) {
					if ($element->isDir() && !$element->isDot()) {
						static::$found_dirs[$scan_dir][$element->getFilename()] = $scan_dir_key;
					}
				}
			}
		}

		foreach (array_keys(static::$found_dirs) as $scan_dir) {
			foreach (static::$found_dirs[$scan_dir] as $directory => $scan_dir_key) {
				if (strpos($file, $directory) === 0) {
					if ($scan_dir_key == 'MODULES_PATH') {
						$file_exploded = explode(DIRECTORY_SEPARATOR, $file);
						array_splice($file_exploded, 1, 0, 'classes');
						$file = join(DIRECTORY_SEPARATOR, $file_exploded);
					} elseif ($scan_dir_key == 'LIBRARY_PATH') {
						$file_exploded = explode(DIRECTORY_SEPARATOR, $file);
						array_splice($file_exploded, 2, 0, 'classes');
						$file = join(DIRECTORY_SEPARATOR, $file_exploded);
					}
					$candidate = $scan_dir . $file . '.' . $ext;
					if($must_exist && file_exists($candidate)){
						return $candidate;
					}
					elseif(!$must_exist){
						return $candidate;
					}
				}
			}
		}
	}

}

