ClassMap.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. /**
  3. * An autoloader that uses class map
  4. *
  5. * Copyright © Magento, Inc. All rights reserved.
  6. * See COPYING.txt for license details.
  7. */
  8. namespace Magento\Framework\Autoload;
  9. class ClassMap
  10. {
  11. /**
  12. * Absolute path to base directory that will be prepended as prefix to the included files
  13. *
  14. * @var string
  15. */
  16. protected $_baseDir;
  17. /**
  18. * Map of class name to file (relative to the base directory)
  19. *
  20. * array(
  21. * 'Class_Name' => 'relative/path/to/Class/Name.php',
  22. * )
  23. *
  24. * @var array
  25. */
  26. protected $_map = [];
  27. /**
  28. * Set base directory absolute path
  29. *
  30. * @param string $baseDir
  31. * @throws \InvalidArgumentException
  32. */
  33. public function __construct($baseDir)
  34. {
  35. $this->_baseDir = realpath($baseDir);
  36. if (!$this->_baseDir || !is_dir($this->_baseDir)) {
  37. throw new \InvalidArgumentException("Specified path is not a valid directory: '{$baseDir}'");
  38. }
  39. }
  40. /**
  41. * Find an absolute path to a file to be included
  42. *
  43. * @param string $class
  44. * @return string|bool
  45. */
  46. public function getFile($class)
  47. {
  48. if (isset($this->_map[$class])) {
  49. return $this->_baseDir . '/' . $this->_map[$class];
  50. }
  51. return false;
  52. }
  53. /**
  54. * Add classes files declaration to the map. New map will override existing values if such was defined before.
  55. *
  56. * @param array $map
  57. * @return $this
  58. */
  59. public function addMap(array $map)
  60. {
  61. $this->_map = array_merge($this->_map, $map);
  62. return $this;
  63. }
  64. /**
  65. * Resolve a class file and include it
  66. *
  67. * @param string $class
  68. * @return void
  69. */
  70. public function load($class)
  71. {
  72. $file = $this->getFile($class);
  73. if (file_exists($file)) {
  74. include $file;
  75. }
  76. }
  77. }