Autoloader.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace Doctrine\Common\Proxy;
  3. use Doctrine\Common\Proxy\Exception\InvalidArgumentException;
  4. /**
  5. * Special Autoloader for Proxy classes, which are not PSR-0 compliant.
  6. *
  7. * @author Benjamin Eberlei <kontakt@beberlei.de>
  8. *
  9. * @internal
  10. *
  11. * @deprecated The Doctrine\Common\Proxy component is deprecated, please use ocramius/proxy-manager instead.
  12. */
  13. class Autoloader
  14. {
  15. /**
  16. * Resolves proxy class name to a filename based on the following pattern.
  17. *
  18. * 1. Remove Proxy namespace from class name.
  19. * 2. Remove namespace separators from remaining class name.
  20. * 3. Return PHP filename from proxy-dir with the result from 2.
  21. *
  22. * @param string $proxyDir
  23. * @param string $proxyNamespace
  24. * @param string $className
  25. *
  26. * @return string
  27. *
  28. * @throws InvalidArgumentException
  29. */
  30. public static function resolveFile($proxyDir, $proxyNamespace, $className)
  31. {
  32. if (0 !== strpos($className, $proxyNamespace)) {
  33. throw InvalidArgumentException::notProxyClass($className, $proxyNamespace);
  34. }
  35. // remove proxy namespace from class name
  36. $classNameRelativeToProxyNamespace = substr($className, strlen($proxyNamespace));
  37. // remove namespace separators from remaining class name
  38. $fileName = str_replace('\\', '', $classNameRelativeToProxyNamespace);
  39. return $proxyDir . DIRECTORY_SEPARATOR . $fileName . '.php';
  40. }
  41. /**
  42. * Registers and returns autoloader callback for the given proxy dir and namespace.
  43. *
  44. * @param string $proxyDir
  45. * @param string $proxyNamespace
  46. * @param callable|null $notFoundCallback Invoked when the proxy file is not found.
  47. *
  48. * @return \Closure
  49. *
  50. * @throws InvalidArgumentException
  51. */
  52. public static function register($proxyDir, $proxyNamespace, $notFoundCallback = null)
  53. {
  54. $proxyNamespace = ltrim($proxyNamespace, '\\');
  55. if ( ! (null === $notFoundCallback || is_callable($notFoundCallback))) {
  56. throw InvalidArgumentException::invalidClassNotFoundCallback($notFoundCallback);
  57. }
  58. $autoloader = function ($className) use ($proxyDir, $proxyNamespace, $notFoundCallback) {
  59. if (0 === strpos($className, $proxyNamespace)) {
  60. $file = Autoloader::resolveFile($proxyDir, $proxyNamespace, $className);
  61. if ($notFoundCallback && ! file_exists($file)) {
  62. call_user_func($notFoundCallback, $proxyDir, $proxyNamespace, $className);
  63. }
  64. require $file;
  65. }
  66. };
  67. spl_autoload_register($autoloader);
  68. return $autoloader;
  69. }
  70. }