ClassMapGenerator.php 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. <?php
  2. /*
  3. * This file is part of Composer.
  4. *
  5. * (c) Nils Adermann <naderman@naderman.de>
  6. * Jordi Boggiano <j.boggiano@seld.be>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. /*
  12. * This file is copied from the Symfony package.
  13. *
  14. * (c) Fabien Potencier <fabien@symfony.com>
  15. */
  16. namespace Composer\Autoload;
  17. use Composer\Util\Silencer;
  18. use Symfony\Component\Finder\Finder;
  19. use Composer\IO\IOInterface;
  20. /**
  21. * ClassMapGenerator
  22. *
  23. * @author Gyula Sallai <salla016@gmail.com>
  24. * @author Jordi Boggiano <j.boggiano@seld.be>
  25. */
  26. class ClassMapGenerator
  27. {
  28. /**
  29. * Generate a class map file
  30. *
  31. * @param \Traversable $dirs Directories or a single path to search in
  32. * @param string $file The name of the class map file
  33. */
  34. public static function dump($dirs, $file)
  35. {
  36. $maps = array();
  37. foreach ($dirs as $dir) {
  38. $maps = array_merge($maps, static::createMap($dir));
  39. }
  40. file_put_contents($file, sprintf('<?php return %s;', var_export($maps, true)));
  41. }
  42. /**
  43. * Iterate over all files in the given directory searching for classes
  44. *
  45. * @param \Iterator|string $path The path to search in or an iterator
  46. * @param string $blacklist Regex that matches against the file path that exclude from the classmap.
  47. * @param IOInterface $io IO object
  48. * @param string $namespace Optional namespace prefix to filter by
  49. *
  50. * @throws \RuntimeException When the path is neither an existing file nor directory
  51. * @return array A class map array
  52. */
  53. public static function createMap($path, $blacklist = null, IOInterface $io = null, $namespace = null)
  54. {
  55. if (is_string($path)) {
  56. if (is_file($path)) {
  57. $path = array(new \SplFileInfo($path));
  58. } elseif (is_dir($path)) {
  59. $path = Finder::create()->files()->followLinks()->name('/\.(php|inc|hh)$/')->in($path);
  60. } else {
  61. throw new \RuntimeException(
  62. 'Could not scan for classes inside "'.$path.
  63. '" which does not appear to be a file nor a folder'
  64. );
  65. }
  66. }
  67. $map = array();
  68. foreach ($path as $file) {
  69. $filePath = $file->getRealPath();
  70. if (!in_array(pathinfo($filePath, PATHINFO_EXTENSION), array('php', 'inc', 'hh'))) {
  71. continue;
  72. }
  73. if ($blacklist && preg_match($blacklist, strtr($filePath, '\\', '/'))) {
  74. continue;
  75. }
  76. $classes = self::findClasses($filePath);
  77. foreach ($classes as $class) {
  78. // skip classes not within the given namespace prefix
  79. if (null !== $namespace && 0 !== strpos($class, $namespace)) {
  80. continue;
  81. }
  82. if (!isset($map[$class])) {
  83. $map[$class] = $filePath;
  84. } elseif ($io && $map[$class] !== $filePath && !preg_match('{/(test|fixture|example|stub)s?/}i', strtr($map[$class].' '.$filePath, '\\', '/'))) {
  85. $io->writeError(
  86. '<warning>Warning: Ambiguous class resolution, "'.$class.'"'.
  87. ' was found in both "'.$map[$class].'" and "'.$filePath.'", the first will be used.</warning>'
  88. );
  89. }
  90. }
  91. }
  92. return $map;
  93. }
  94. /**
  95. * Extract the classes in the given file
  96. *
  97. * @param string $path The file to check
  98. * @throws \RuntimeException
  99. * @return array The found classes
  100. */
  101. private static function findClasses($path)
  102. {
  103. $extraTypes = PHP_VERSION_ID < 50400 ? '' : '|trait';
  104. if (defined('HHVM_VERSION') && version_compare(HHVM_VERSION, '3.3', '>=')) {
  105. $extraTypes .= '|enum';
  106. }
  107. try {
  108. $contents = Silencer::call('php_strip_whitespace', $path);
  109. if (!$contents) {
  110. if (!file_exists($path)) {
  111. throw new \Exception('File does not exist');
  112. }
  113. if (!is_readable($path)) {
  114. throw new \Exception('File is not readable');
  115. }
  116. }
  117. } catch (\Exception $e) {
  118. throw new \RuntimeException('Could not scan for classes inside '.$path.": \n".$e->getMessage(), 0, $e);
  119. }
  120. // return early if there is no chance of matching anything in this file
  121. if (!preg_match('{\b(?:class|interface'.$extraTypes.')\s}i', $contents)) {
  122. return array();
  123. }
  124. // strip heredocs/nowdocs
  125. $contents = preg_replace('{<<<\s*(\'?)(\w+)\\1(?:\r\n|\n|\r)(?:.*?)(?:\r\n|\n|\r)\\2(?=\r\n|\n|\r|;)}s', 'null', $contents);
  126. // strip strings
  127. $contents = preg_replace('{"[^"\\\\]*+(\\\\.[^"\\\\]*+)*+"|\'[^\'\\\\]*+(\\\\.[^\'\\\\]*+)*+\'}s', 'null', $contents);
  128. // strip leading non-php code if needed
  129. if (substr($contents, 0, 2) !== '<?') {
  130. $contents = preg_replace('{^.+?<\?}s', '<?', $contents, 1, $replacements);
  131. if ($replacements === 0) {
  132. return array();
  133. }
  134. }
  135. // strip non-php blocks in the file
  136. $contents = preg_replace('{\?>.+<\?}s', '?><?', $contents);
  137. // strip trailing non-php code if needed
  138. $pos = strrpos($contents, '?>');
  139. if (false !== $pos && false === strpos(substr($contents, $pos), '<?')) {
  140. $contents = substr($contents, 0, $pos);
  141. }
  142. preg_match_all('{
  143. (?:
  144. \b(?<![\$:>])(?P<type>class|interface'.$extraTypes.') \s++ (?P<name>[a-zA-Z_\x7f-\xff:][a-zA-Z0-9_\x7f-\xff:\-]*+)
  145. | \b(?<![\$:>])(?P<ns>namespace) (?P<nsname>\s++[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+(?:\s*+\\\\\s*+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+)*+)? \s*+ [\{;]
  146. )
  147. }ix', $contents, $matches);
  148. $classes = array();
  149. $namespace = '';
  150. for ($i = 0, $len = count($matches['type']); $i < $len; $i++) {
  151. if (!empty($matches['ns'][$i])) {
  152. $namespace = str_replace(array(' ', "\t", "\r", "\n"), '', $matches['nsname'][$i]) . '\\';
  153. } else {
  154. $name = $matches['name'][$i];
  155. if ($name[0] === ':') {
  156. // This is an XHP class, https://github.com/facebook/xhp
  157. $name = 'xhp'.substr(str_replace(array('-', ':'), array('_', '__'), $name), 1);
  158. } elseif ($matches['type'][$i] === 'enum') {
  159. // In Hack, something like:
  160. // enum Foo: int { HERP = '123'; }
  161. // The regex above captures the colon, which isn't part of
  162. // the class name.
  163. $name = rtrim($name, ':');
  164. }
  165. $classes[] = ltrim($namespace . $name, '\\');
  166. }
  167. }
  168. return $classes;
  169. }
  170. }