StandardAutoloader.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Loader
  17. * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @license http://framework.zend.com/license/new-bsd New BSD License
  19. */
  20. // Grab SplAutoloader interface
  21. #require_once dirname(__FILE__) . '/SplAutoloader.php';
  22. /**
  23. * PSR-0 compliant autoloader
  24. *
  25. * Allows autoloading both namespaced and vendor-prefixed classes. Class
  26. * lookups are performed on the filesystem. If a class file for the referenced
  27. * class is not found, a PHP warning will be raised by include().
  28. *
  29. * @package Zend_Loader
  30. * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
  31. * @license New BSD {@link http://framework.zend.com/license/new-bsd}
  32. */
  33. class Zend_Loader_StandardAutoloader implements Zend_Loader_SplAutoloader
  34. {
  35. const NS_SEPARATOR = '\\';
  36. const PREFIX_SEPARATOR = '_';
  37. const LOAD_NS = 'namespaces';
  38. const LOAD_PREFIX = 'prefixes';
  39. const ACT_AS_FALLBACK = 'fallback_autoloader';
  40. const AUTOREGISTER_ZF = 'autoregister_zf';
  41. /**
  42. * @var array Namespace/directory pairs to search; ZF library added by default
  43. */
  44. protected $namespaces = array();
  45. /**
  46. * @var array Prefix/directory pairs to search
  47. */
  48. protected $prefixes = array();
  49. /**
  50. * @var bool Whether or not the autoloader should also act as a fallback autoloader
  51. */
  52. protected $fallbackAutoloaderFlag = false;
  53. /**
  54. * @var bool
  55. */
  56. protected $error;
  57. /**
  58. * Constructor
  59. *
  60. * @param null|array|Traversable $options
  61. * @return void
  62. */
  63. public function __construct($options = null)
  64. {
  65. if (null !== $options) {
  66. $this->setOptions($options);
  67. }
  68. }
  69. /**
  70. * Configure autoloader
  71. *
  72. * Allows specifying both "namespace" and "prefix" pairs, using the
  73. * following structure:
  74. * <code>
  75. * array(
  76. * 'namespaces' => array(
  77. * 'Zend' => '/path/to/Zend/library',
  78. * 'Doctrine' => '/path/to/Doctrine/library',
  79. * ),
  80. * 'prefixes' => array(
  81. * 'Phly_' => '/path/to/Phly/library',
  82. * ),
  83. * 'fallback_autoloader' => true,
  84. * )
  85. * </code>
  86. *
  87. * @param array|Traversable $options
  88. * @return Zend_Loader_StandardAutoloader
  89. */
  90. public function setOptions($options)
  91. {
  92. if (!is_array($options) && !($options instanceof Traversable)) {
  93. #require_once dirname(__FILE__) . '/Exception/InvalidArgumentException.php';
  94. throw new Zend_Loader_Exception_InvalidArgumentException('Options must be either an array or Traversable');
  95. }
  96. foreach ($options as $type => $pairs) {
  97. switch ($type) {
  98. case self::AUTOREGISTER_ZF:
  99. if ($pairs) {
  100. $this->registerPrefix('Zend', dirname(dirname(__FILE__)));
  101. }
  102. break;
  103. case self::LOAD_NS:
  104. if (is_array($pairs) || $pairs instanceof Traversable) {
  105. $this->registerNamespaces($pairs);
  106. }
  107. break;
  108. case self::LOAD_PREFIX:
  109. if (is_array($pairs) || $pairs instanceof Traversable) {
  110. $this->registerPrefixes($pairs);
  111. }
  112. break;
  113. case self::ACT_AS_FALLBACK:
  114. $this->setFallbackAutoloader($pairs);
  115. break;
  116. default:
  117. // ignore
  118. }
  119. }
  120. return $this;
  121. }
  122. /**
  123. * Set flag indicating fallback autoloader status
  124. *
  125. * @param bool $flag
  126. * @return Zend_Loader_StandardAutoloader
  127. */
  128. public function setFallbackAutoloader($flag)
  129. {
  130. $this->fallbackAutoloaderFlag = (bool) $flag;
  131. return $this;
  132. }
  133. /**
  134. * Is this autoloader acting as a fallback autoloader?
  135. *
  136. * @return bool
  137. */
  138. public function isFallbackAutoloader()
  139. {
  140. return $this->fallbackAutoloaderFlag;
  141. }
  142. /**
  143. * Register a namespace/directory pair
  144. *
  145. * @param string $namespace
  146. * @param string $directory
  147. * @return Zend_Loader_StandardAutoloader
  148. */
  149. public function registerNamespace($namespace, $directory)
  150. {
  151. $namespace = rtrim($namespace, self::NS_SEPARATOR). self::NS_SEPARATOR;
  152. $this->namespaces[$namespace] = $this->normalizeDirectory($directory);
  153. return $this;
  154. }
  155. /**
  156. * Register many namespace/directory pairs at once
  157. *
  158. * @param array $namespaces
  159. * @return Zend_Loader_StandardAutoloader
  160. */
  161. public function registerNamespaces($namespaces)
  162. {
  163. if (!is_array($namespaces) && !$namespaces instanceof Traversable) {
  164. #require_once dirname(__FILE__) . '/Exception/InvalidArgumentException.php';
  165. throw new Zend_Loader_Exception_InvalidArgumentException('Namespace pairs must be either an array or Traversable');
  166. }
  167. foreach ($namespaces as $namespace => $directory) {
  168. $this->registerNamespace($namespace, $directory);
  169. }
  170. return $this;
  171. }
  172. /**
  173. * Register a prefix/directory pair
  174. *
  175. * @param string $prefix
  176. * @param string $directory
  177. * @return Zend_Loader_StandardAutoloader
  178. */
  179. public function registerPrefix($prefix, $directory)
  180. {
  181. $prefix = rtrim($prefix, self::PREFIX_SEPARATOR). self::PREFIX_SEPARATOR;
  182. $this->prefixes[$prefix] = $this->normalizeDirectory($directory);
  183. return $this;
  184. }
  185. /**
  186. * Register many namespace/directory pairs at once
  187. *
  188. * @param array $prefixes
  189. * @return Zend_Loader_StandardAutoloader
  190. */
  191. public function registerPrefixes($prefixes)
  192. {
  193. if (!is_array($prefixes) && !$prefixes instanceof Traversable) {
  194. #require_once dirname(__FILE__) . '/Exception/InvalidArgumentException.php';
  195. throw new Zend_Loader_Exception_InvalidArgumentException('Prefix pairs must be either an array or Traversable');
  196. }
  197. foreach ($prefixes as $prefix => $directory) {
  198. $this->registerPrefix($prefix, $directory);
  199. }
  200. return $this;
  201. }
  202. /**
  203. * Defined by Autoloadable; autoload a class
  204. *
  205. * @param string $class
  206. * @return false|string
  207. */
  208. public function autoload($class)
  209. {
  210. $isFallback = $this->isFallbackAutoloader();
  211. if (false !== strpos($class, self::NS_SEPARATOR)) {
  212. if ($this->loadClass($class, self::LOAD_NS)) {
  213. return $class;
  214. } elseif ($isFallback) {
  215. return $this->loadClass($class, self::ACT_AS_FALLBACK);
  216. }
  217. return false;
  218. }
  219. if (false !== strpos($class, self::PREFIX_SEPARATOR)) {
  220. if ($this->loadClass($class, self::LOAD_PREFIX)) {
  221. return $class;
  222. } elseif ($isFallback) {
  223. return $this->loadClass($class, self::ACT_AS_FALLBACK);
  224. }
  225. return false;
  226. }
  227. if ($isFallback) {
  228. return $this->loadClass($class, self::ACT_AS_FALLBACK);
  229. }
  230. return false;
  231. }
  232. /**
  233. * Register the autoloader with spl_autoload
  234. *
  235. * @return void
  236. */
  237. public function register()
  238. {
  239. spl_autoload_register(array($this, 'autoload'));
  240. }
  241. /**
  242. * Error handler
  243. *
  244. * Used by {@link loadClass} during fallback autoloading in PHP versions
  245. * prior to 5.3.0.
  246. *
  247. * @param mixed $errno
  248. * @param mixed $errstr
  249. * @return void
  250. */
  251. public function handleError($errno, $errstr)
  252. {
  253. $this->error = true;
  254. }
  255. /**
  256. * Transform the class name to a filename
  257. *
  258. * @param string $class
  259. * @param string $directory
  260. * @return string
  261. */
  262. protected function transformClassNameToFilename($class, $directory)
  263. {
  264. // $class may contain a namespace portion, in which case we need
  265. // to preserve any underscores in that portion.
  266. $matches = array();
  267. preg_match('/(?P<namespace>.+\\\)?(?P<class>[^\\\]+$)/', $class, $matches);
  268. $class = (isset($matches['class'])) ? $matches['class'] : '';
  269. $namespace = (isset($matches['namespace'])) ? $matches['namespace'] : '';
  270. return $directory
  271. . str_replace(self::NS_SEPARATOR, '/', $namespace)
  272. . str_replace(self::PREFIX_SEPARATOR, '/', $class)
  273. . '.php';
  274. }
  275. /**
  276. * Load a class, based on its type (namespaced or prefixed)
  277. *
  278. * @param string $class
  279. * @param string $type
  280. * @return void
  281. */
  282. protected function loadClass($class, $type)
  283. {
  284. if (!in_array($type, array(self::LOAD_NS, self::LOAD_PREFIX, self::ACT_AS_FALLBACK))) {
  285. #require_once dirname(__FILE__) . '/Exception/InvalidArgumentException.php';
  286. throw new Zend_Loader_Exception_InvalidArgumentException();
  287. }
  288. // Fallback autoloading
  289. if ($type === self::ACT_AS_FALLBACK) {
  290. // create filename
  291. $filename = $this->transformClassNameToFilename($class, '');
  292. if (version_compare(PHP_VERSION, '5.3.2', '>=')) {
  293. $resolvedName = stream_resolve_include_path($filename);
  294. if ($resolvedName !== false) {
  295. return include $resolvedName;
  296. }
  297. return false;
  298. }
  299. $this->error = false;
  300. set_error_handler(array($this, 'handleError'), E_WARNING);
  301. include $filename;
  302. restore_error_handler();
  303. if ($this->error) {
  304. return false;
  305. }
  306. return class_exists($class, false);
  307. }
  308. // Namespace and/or prefix autoloading
  309. foreach ($this->$type as $leader => $path) {
  310. if (0 === strpos($class, $leader)) {
  311. // Trim off leader (namespace or prefix)
  312. $trimmedClass = substr($class, strlen($leader));
  313. // create filename
  314. $filename = $this->transformClassNameToFilename($trimmedClass, $path);
  315. if (file_exists($filename)) {
  316. return include $filename;
  317. }
  318. return false;
  319. }
  320. }
  321. return false;
  322. }
  323. /**
  324. * Normalize the directory to include a trailing directory separator
  325. *
  326. * @param string $directory
  327. * @return string
  328. */
  329. protected function normalizeDirectory($directory)
  330. {
  331. $last = $directory[strlen($directory) - 1];
  332. if (in_array($last, array('/', '\\'))) {
  333. $directory[strlen($directory) - 1] = DIRECTORY_SEPARATOR;
  334. return $directory;
  335. }
  336. $directory .= DIRECTORY_SEPARATOR;
  337. return $directory;
  338. }
  339. }