Constructs.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * Copyright (c) 2017-2025 Andreas Möller
  5. *
  6. * For the full copyright and license information, please view
  7. * the LICENSE.md file that was distributed with this source code.
  8. *
  9. * @see https://github.com/ergebnis/classy
  10. */
  11. namespace Ergebnis\Classy;
  12. final class Constructs
  13. {
  14. /**
  15. * Returns a list of constructs defined in source code.
  16. *
  17. * @throws Exception\ParseError
  18. *
  19. * @return list<Construct>
  20. */
  21. public static function fromSource(string $source): array
  22. {
  23. $constructs = [];
  24. try {
  25. $sequence = \token_get_all(
  26. $source,
  27. \TOKEN_PARSE,
  28. );
  29. } catch (\ParseError $exception) {
  30. throw Exception\ParseError::fromParseError($exception);
  31. }
  32. $count = \count($sequence);
  33. $namespacePrefix = '';
  34. $namespaceSegmentOrNamespaceTokens = [
  35. \T_STRING,
  36. ];
  37. /**
  38. * @see https://wiki.php.net/rfc/namespaced_names_as_token
  39. */
  40. if (
  41. \PHP_VERSION_ID >= 80000
  42. && \defined('T_NAME_QUALIFIED')
  43. ) {
  44. /** @var list<int> $namespaceSegmentOrNamespaceTokens */
  45. $namespaceSegmentOrNamespaceTokens = [
  46. \T_STRING,
  47. \T_NAME_QUALIFIED,
  48. ];
  49. }
  50. $classyTokens = [
  51. \T_CLASS,
  52. \T_INTERFACE,
  53. \T_TRAIT,
  54. ];
  55. /**
  56. * @see https://wiki.php.net/rfc/enumerations
  57. */
  58. if (
  59. \PHP_VERSION_ID >= 80100
  60. && \defined('T_ENUM')
  61. ) {
  62. $classyTokens = [
  63. \T_CLASS,
  64. \T_ENUM,
  65. \T_INTERFACE,
  66. \T_TRAIT,
  67. ];
  68. }
  69. for ($index = 0; $index < $count; ++$index) {
  70. $token = $sequence[$index];
  71. // collect namespace name
  72. if (\is_array($token) && \T_NAMESPACE === $token[0]) {
  73. $namespaceSegments = [];
  74. // collect namespace segments
  75. for ($index = self::significantAfter($index, $sequence, $count); $index < $count; ++$index) {
  76. $token = $sequence[$index];
  77. if (\is_array($token) && !\in_array($token[0], $namespaceSegmentOrNamespaceTokens, true)) {
  78. continue;
  79. }
  80. $content = self::content($token);
  81. if (\in_array($content, ['{', ';'], true)) {
  82. break;
  83. }
  84. $namespaceSegments[] = $content;
  85. }
  86. $namespace = \implode('\\', $namespaceSegments);
  87. $namespacePrefix = $namespace . '\\';
  88. }
  89. // skip non-classy tokens
  90. if (!\is_array($token) || !\in_array($token[0], $classyTokens, true)) {
  91. continue;
  92. }
  93. // skip anonymous classes
  94. if (\T_CLASS === $token[0]) {
  95. $current = self::significantBefore($index, $sequence);
  96. $token = $sequence[$current];
  97. // if significant token before T_CLASS is T_NEW, it's an instantiation of an anonymous class
  98. if (\is_array($token) && \T_NEW === $token[0]) {
  99. continue;
  100. }
  101. }
  102. $index = self::significantAfter($index, $sequence, $count);
  103. $token = $sequence[$index];
  104. $constructs[] = Construct::fromName($namespacePrefix . self::content($token));
  105. }
  106. \usort($constructs, static function (Construct $a, Construct $b): int {
  107. return \strcmp(
  108. $a->name(),
  109. $b->name(),
  110. );
  111. });
  112. return $constructs;
  113. }
  114. /**
  115. * Returns a list of constructs defined in a directory.
  116. *
  117. * @throws Exception\DirectoryDoesNotExist
  118. * @throws Exception\MultipleDefinitionsFound
  119. *
  120. * @return list<Construct>
  121. */
  122. public static function fromDirectory(string $directory): array
  123. {
  124. if (!\is_dir($directory)) {
  125. throw Exception\DirectoryDoesNotExist::fromDirectory($directory);
  126. }
  127. $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator(
  128. $directory,
  129. \FilesystemIterator::FOLLOW_SYMLINKS,
  130. ));
  131. $constructs = [];
  132. foreach ($iterator as $fileInfo) {
  133. /** @var \SplFileInfo $fileInfo */
  134. if (!$fileInfo->isFile()) {
  135. continue;
  136. }
  137. if ($fileInfo->getBasename('.php') === $fileInfo->getBasename()) {
  138. continue;
  139. }
  140. /** @var string $fileName */
  141. $fileName = $fileInfo->getRealPath();
  142. /** @var string $source */
  143. $source = \file_get_contents($fileName);
  144. try {
  145. $constructsFromFile = self::fromSource($source);
  146. } catch (Exception\ParseError $exception) {
  147. throw Exception\ParseError::fromFileNameAndParseError(
  148. $fileName,
  149. $exception,
  150. );
  151. }
  152. if (0 === \count($constructsFromFile)) {
  153. continue;
  154. }
  155. foreach ($constructsFromFile as $construct) {
  156. $name = $construct->name();
  157. if (\array_key_exists($name, $constructs)) {
  158. $construct = $constructs[$name];
  159. }
  160. $constructs[$name] = $construct->definedIn($fileName);
  161. }
  162. }
  163. \usort($constructs, static function (Construct $a, Construct $b): int {
  164. return \strcmp(
  165. $a->name(),
  166. $b->name(),
  167. );
  168. });
  169. $constructsWithMultipleDefinitions = \array_filter($constructs, static function (Construct $construct): bool {
  170. return 1 < \count($construct->fileNames());
  171. });
  172. if (0 < \count($constructsWithMultipleDefinitions)) {
  173. throw Exception\MultipleDefinitionsFound::fromConstructs($constructsWithMultipleDefinitions);
  174. }
  175. return \array_values($constructs);
  176. }
  177. /**
  178. * Returns the index of the significant token after the index.
  179. *
  180. * @param array<int, array{0: int, 1: string, 2: int}|string> $sequence
  181. */
  182. private static function significantAfter(
  183. int $index,
  184. array $sequence,
  185. int $count
  186. ): int {
  187. for ($current = $index + 1; $current < $count; ++$current) {
  188. $token = $sequence[$current];
  189. if (\is_array($token) && \in_array($token[0], [\T_COMMENT, \T_DOC_COMMENT, \T_WHITESPACE], true)) {
  190. continue;
  191. }
  192. return $current;
  193. }
  194. throw Exception\ShouldNotHappen::create();
  195. }
  196. /**
  197. * Returns the index of the significant token after the index.
  198. *
  199. * @param array<int, array{0: int, 1: string, 2: int}|string> $sequence
  200. */
  201. private static function significantBefore(
  202. int $index,
  203. array $sequence
  204. ): int {
  205. for ($current = $index - 1; -1 < $current; --$current) {
  206. $token = $sequence[$current];
  207. if (\is_array($token) && \in_array($token[0], [\T_COMMENT, \T_DOC_COMMENT, \T_WHITESPACE], true)) {
  208. continue;
  209. }
  210. return $current;
  211. }
  212. throw Exception\ShouldNotHappen::create();
  213. }
  214. /**
  215. * Returns the string content of a token.
  216. *
  217. * @param array{0: int, 1: string, 2: int}|string $token
  218. */
  219. private static function content($token): string
  220. {
  221. if (\is_array($token)) {
  222. return $token[1];
  223. }
  224. return $token;
  225. }
  226. }