ClassMapGenerator.php 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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. // Use @ here instead of Silencer to actively suppress 'unhelpful' output
  109. // @link https://github.com/composer/composer/pull/4886
  110. $contents = @php_strip_whitespace($path);
  111. if (!$contents) {
  112. if (!file_exists($path)) {
  113. throw new \RuntimeException(sprintf('File at "%s" does not exist, check your classmap definitions', $path));
  114. } elseif (!is_readable($path)) {
  115. throw new \RuntimeException(sprintf('File at "%s" is not readable, check its permissions', $path));
  116. }
  117. throw new \RuntimeException(sprintf('File at "%s" could not be parsed as PHP - it may be binary or corrupted', $path));
  118. }
  119. } catch (\Exception $e) {
  120. throw new \RuntimeException('Could not scan for classes inside '.$path.": \n".$e->getMessage(), 0, $e);
  121. }
  122. // return early if there is no chance of matching anything in this file
  123. if (!preg_match('{\b(?:class|interface'.$extraTypes.')\s}i', $contents)) {
  124. return array();
  125. }
  126. // strip heredocs/nowdocs
  127. $contents = preg_replace('{<<<\s*(\'?)(\w+)\\1(?:\r\n|\n|\r)(?:.*?)(?:\r\n|\n|\r)\\2(?=\r\n|\n|\r|;)}s', 'null', $contents);
  128. // strip strings
  129. $contents = preg_replace('{"[^"\\\\]*+(\\\\.[^"\\\\]*+)*+"|\'[^\'\\\\]*+(\\\\.[^\'\\\\]*+)*+\'}s', 'null', $contents);
  130. // strip leading non-php code if needed
  131. if (substr($contents, 0, 2) !== '<?') {
  132. $contents = preg_replace('{^.+?<\?}s', '<?', $contents, 1, $replacements);
  133. if ($replacements === 0) {
  134. return array();
  135. }
  136. }
  137. // strip non-php blocks in the file
  138. $contents = preg_replace('{\?>.+<\?}s', '?><?', $contents);
  139. // strip trailing non-php code if needed
  140. $pos = strrpos($contents, '?>');
  141. if (false !== $pos && false === strpos(substr($contents, $pos), '<?')) {
  142. $contents = substr($contents, 0, $pos);
  143. }
  144. preg_match_all('{
  145. (?:
  146. \b(?<![\$:>])(?P<type>class|interface'.$extraTypes.') \s++ (?P<name>[a-zA-Z_\x7f-\xff:][a-zA-Z0-9_\x7f-\xff:\-]*+)
  147. | \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*+ [\{;]
  148. )
  149. }ix', $contents, $matches);
  150. $classes = array();
  151. $namespace = '';
  152. for ($i = 0, $len = count($matches['type']); $i < $len; $i++) {
  153. if (!empty($matches['ns'][$i])) {
  154. $namespace = str_replace(array(' ', "\t", "\r", "\n"), '', $matches['nsname'][$i]) . '\\';
  155. } else {
  156. $name = $matches['name'][$i];
  157. if ($name[0] === ':') {
  158. // This is an XHP class, https://github.com/facebook/xhp
  159. $name = 'xhp'.substr(str_replace(array('-', ':'), array('_', '__'), $name), 1);
  160. } elseif ($matches['type'][$i] === 'enum') {
  161. // In Hack, something like:
  162. // enum Foo: int { HERP = '123'; }
  163. // The regex above captures the colon, which isn't part of
  164. // the class name.
  165. $name = rtrim($name, ':');
  166. }
  167. $classes[] = ltrim($namespace . $name, '\\');
  168. }
  169. }
  170. return $classes;
  171. }
  172. }