StaticAnalyser.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. <?php
  2. /**
  3. * @license Apache 2.0
  4. */
  5. namespace Swagger;
  6. /**
  7. * Swagger\StaticAnalyser extracts swagger-php annotations from php code using static analysis.
  8. */
  9. class StaticAnalyser
  10. {
  11. /**
  12. * @param string $filename
  13. */
  14. public function __construct($filename = null)
  15. {
  16. if ($filename !== null) {
  17. $this->fromFile($filename);
  18. }
  19. }
  20. /**
  21. * Extract and process all doc-comments from a file.
  22. *
  23. * @param string $filename Path to a php file.
  24. * @return Analysis
  25. */
  26. public function fromFile($filename)
  27. {
  28. if (function_exists('opcache_get_status') && function_exists('opcache_get_configuration')) {
  29. if (empty($GLOBALS['swagger_opcache_warning'])) {
  30. $GLOBALS['swagger_opcache_warning'] = true;
  31. $status = opcache_get_status();
  32. $config = opcache_get_configuration();
  33. if ($status['opcache_enabled'] && $config['directives']['opcache.save_comments'] == false) {
  34. Logger::warning("php.ini \"opcache.save_comments = 0\" interferes with extracting annotations.\n[LINK] http://php.net/manual/en/opcache.configuration.php#ini.opcache.save-comments");
  35. }
  36. }
  37. }
  38. $tokens = token_get_all(file_get_contents($filename));
  39. return $this->fromTokens($tokens, new Context(['filename' => $filename]));
  40. }
  41. /**
  42. * Extract and process all doc-comments from the contents.
  43. *
  44. * @param string $code PHP code. (including <?php tags)
  45. * @param Context $context The original location of the contents.
  46. * @return Analysis
  47. */
  48. public function fromCode($code, $context)
  49. {
  50. $tokens = token_get_all($code);
  51. return $this->fromTokens($tokens, $context);
  52. }
  53. /**
  54. * Shared implementation for parseFile() & parseContents().
  55. *
  56. * @param array $tokens The result of a token_get_all()
  57. * @param Context $parseContext
  58. * @return Analysis
  59. */
  60. protected function fromTokens($tokens, $parseContext)
  61. {
  62. $analyser = new Analyser();
  63. $analysis = new Analysis();
  64. reset($tokens);
  65. $token = '';
  66. $imports = Analyser::$defaultImports; // Use @SWG\* for swagger annotations (unless overwritten by a use statement)
  67. $parseContext->uses = [];
  68. $definitionContext = $parseContext; // Use the parseContext until a definitionContext (class or trait) is created.
  69. $classDefinition = false;
  70. $comment = false;
  71. $line = 0;
  72. $lineOffset = $parseContext->line ? : 0;
  73. while ($token !== false) {
  74. $previousToken = $token;
  75. $token = $this->nextToken($tokens, $parseContext);
  76. if (is_array($token) === false) { // Ignore tokens like "{", "}", etc
  77. continue;
  78. }
  79. if ($token[0] === T_DOC_COMMENT) {
  80. if ($comment) { // 2 Doc-comments in succession?
  81. $this->analyseComment($analysis, $analyser, $comment, new Context(['line' => $line], $definitionContext));
  82. }
  83. $comment = $token[1];
  84. $line = $token[2] + $lineOffset;
  85. continue;
  86. }
  87. if (in_array($token[0], [T_ABSTRACT, T_FINAL])) {
  88. $token = $this->nextToken($tokens, $parseContext); // Skip "abstract" and "final" keywords
  89. }
  90. if ($token[0] === T_CLASS) { // Doc-comment before a class?
  91. if (is_array($previousToken) && $previousToken[0] === T_DOUBLE_COLON) {
  92. //php 5.5 class name resolution (i.e. ClassName::class)
  93. continue;
  94. }
  95. $token = $this->nextToken($tokens, $parseContext);
  96. if (is_string($token) && ($token === '(' || $token === '{')) {
  97. // php7 anonymous classes (i.e. new class() { public function foo() {} };)
  98. continue;
  99. }
  100. $definitionContext = new Context(['class' => $token[1], 'line' => $token[2]], $parseContext);
  101. if ($classDefinition) {
  102. $analysis->addClassDefinition($classDefinition);
  103. }
  104. $classDefinition = [
  105. 'class' => $token[1],
  106. 'extends' => null,
  107. 'properties' => [],
  108. 'methods' => [],
  109. 'context' => $definitionContext
  110. ];
  111. // @todo detect end-of-class and reset $definitionContext
  112. $token = $this->nextToken($tokens, $parseContext);
  113. if ($token[0] === T_EXTENDS) {
  114. $definitionContext->extends = $this->parseNamespace($tokens, $token, $parseContext);
  115. $classDefinition['extends'] = $definitionContext->fullyQualifiedName($definitionContext->extends);
  116. }
  117. if ($comment) {
  118. $definitionContext->line = $line;
  119. $this->analyseComment($analysis, $analyser, $comment, $definitionContext);
  120. $comment = false;
  121. continue;
  122. }
  123. }
  124. if ($token[0] === T_TRAIT) {
  125. $classDefinition = false;
  126. $token = $this->nextToken($tokens, $parseContext);
  127. $definitionContext = new Context(['trait' => $token[1], 'line' => $token[2]], $parseContext);
  128. if ($comment) {
  129. $definitionContext->line = $line;
  130. $this->analyseComment($analysis, $analyser, $comment, $definitionContext);
  131. $comment = false;
  132. continue;
  133. }
  134. }
  135. if ($token[0] === T_STATIC) {
  136. $token = $this->nextToken($tokens, $parseContext);
  137. if ($token[0] === T_VARIABLE) { // static property
  138. $propertyContext = new Context([
  139. 'property' => substr($token[1], 1),
  140. 'static' => true,
  141. 'line' => $line
  142. ], $definitionContext);
  143. if ($classDefinition) {
  144. $classDefinition['properties'][$propertyContext->property] = $propertyContext;
  145. }
  146. if ($comment) {
  147. $this->analyseComment($analysis, $analyser, $comment, $propertyContext);
  148. $comment = false;
  149. }
  150. continue;
  151. }
  152. }
  153. if (in_array($token[0], [T_PRIVATE, T_PROTECTED, T_PUBLIC, T_VAR])) { // Scope
  154. $token = $this->nextToken($tokens, $parseContext);
  155. if ($token[0] == T_STATIC) {
  156. $token = $this->nextToken($tokens, $parseContext);
  157. }
  158. if ($token[0] === T_VARIABLE) { // instance property
  159. $propertyContext = new Context([
  160. 'property' => substr($token[1], 1),
  161. 'line' => $line
  162. ], $definitionContext);
  163. if ($classDefinition) {
  164. $classDefinition['properties'][$propertyContext->property] = $propertyContext;
  165. }
  166. if ($comment) {
  167. $this->analyseComment($analysis, $analyser, $comment, $propertyContext);
  168. $comment = false;
  169. }
  170. } elseif ($token[0] === T_FUNCTION) {
  171. $token = $this->nextToken($tokens, $parseContext);
  172. if ($token[0] === T_STRING) {
  173. $methodContext = new Context([
  174. 'method' => $token[1],
  175. 'line' => $line
  176. ], $definitionContext);
  177. if ($classDefinition) {
  178. $classDefinition['methods'][$token[1]] = $methodContext;
  179. }
  180. if ($comment) {
  181. $this->analyseComment($analysis, $analyser, $comment, $methodContext);
  182. $comment = false;
  183. }
  184. }
  185. }
  186. continue;
  187. } elseif ($token[0] === T_FUNCTION) {
  188. $token = $this->nextToken($tokens, $parseContext);
  189. if ($token[0] === T_STRING) {
  190. $methodContext = new Context([
  191. 'method' => $token[1],
  192. 'line' => $line
  193. ], $definitionContext);
  194. if ($classDefinition) {
  195. $classDefinition['methods'][$token[1]] = $methodContext;
  196. }
  197. if ($comment) {
  198. $this->analyseComment($analysis, $analyser, $comment, $methodContext);
  199. $comment = false;
  200. }
  201. }
  202. }
  203. if (in_array($token[0], [T_NAMESPACE, T_USE]) === false) { // Skip "use" & "namespace" to prevent "never imported" warnings)
  204. // Not a doc-comment for a class, property or method?
  205. if ($comment) {
  206. $this->analyseComment($analysis, $analyser, $comment, new Context(['line' => $line], $definitionContext));
  207. $comment = false;
  208. }
  209. }
  210. if ($token[0] === T_NAMESPACE) {
  211. $parseContext->namespace = $this->parseNamespace($tokens, $token, $parseContext);
  212. continue;
  213. }
  214. if ($token[0] === T_USE) {
  215. $statements = $this->parseUseStatement($tokens, $token, $parseContext);
  216. foreach ($statements as $alias => $target) {
  217. if ($target[0] === '\\') {
  218. $target = substr($target, 1);
  219. }
  220. $parseContext->uses[$alias] = $target;
  221. if (Analyser::$whitelist === false) {
  222. $imports[strtolower($alias)] = $target;
  223. } else {
  224. foreach (Analyser::$whitelist as $namespace) {
  225. if (strcasecmp(substr($target, 0, strlen($namespace)), $namespace) === 0) {
  226. $imports[strtolower($alias)] = $target;
  227. break;
  228. }
  229. }
  230. }
  231. }
  232. $analyser->docParser->setImports($imports);
  233. continue;
  234. }
  235. }
  236. if ($comment) { // File ends with a T_DOC_COMMENT
  237. $this->analyseComment($analysis, $analyser, $comment, new Context(['line' => $line], $definitionContext));
  238. }
  239. if ($classDefinition) {
  240. $analysis->addClassDefinition($classDefinition);
  241. }
  242. return $analysis;
  243. }
  244. /**
  245. *
  246. * @param Analysis $analysis
  247. * @param Analyser $analyser
  248. * @param string $comment
  249. * @param Context $context
  250. */
  251. private function analyseComment($analysis, $analyser, $comment, $context)
  252. {
  253. $analysis->addAnnotations($analyser->fromComment($comment, $context), $context);
  254. }
  255. /**
  256. * The next non-whitespace, non-comment token.
  257. *
  258. * @param array $tokens
  259. * @param Context $context
  260. * @return string|array The next token (or false)
  261. */
  262. private function nextToken(&$tokens, $context)
  263. {
  264. while (true) {
  265. $token = next($tokens);
  266. if ($token[0] === T_WHITESPACE) {
  267. continue;
  268. }
  269. if ($token[0] === T_COMMENT) {
  270. $pos = strpos($token[1], '@SWG\\');
  271. if ($pos) {
  272. $line = $context->line ? $context->line + $token[2] : $token[2];
  273. $commentContext = new Context(['line' => $line], $context);
  274. Logger::notice('Annotations are only parsed inside `/**` DocBlocks, skipping ' . $commentContext);
  275. }
  276. continue;
  277. }
  278. return $token;
  279. }
  280. }
  281. private function parseNamespace(&$tokens, &$token, $parseContext)
  282. {
  283. $namespace = '';
  284. while ($token !== false) {
  285. $token = $this->nextToken($tokens, $parseContext);
  286. if ($token[0] !== T_STRING && $token[0] !== T_NS_SEPARATOR) {
  287. break;
  288. }
  289. $namespace .= $token[1];
  290. }
  291. return $namespace;
  292. }
  293. private function parseUseStatement(&$tokens, &$token, $parseContext)
  294. {
  295. $class = '';
  296. $alias = '';
  297. $statements = [];
  298. $explicitAlias = false;
  299. while ($token !== false) {
  300. $token = $this->nextToken($tokens, $parseContext);
  301. $isNameToken = $token[0] === T_STRING || $token[0] === T_NS_SEPARATOR;
  302. if (!$explicitAlias && $isNameToken) {
  303. $class .= $token[1];
  304. $alias = $token[1];
  305. } elseif ($explicitAlias && $isNameToken) {
  306. $alias .= $token[1];
  307. } elseif ($token[0] === T_AS) {
  308. $explicitAlias = true;
  309. $alias = '';
  310. } elseif ($token === ',') {
  311. $statements[$alias] = $class;
  312. $class = '';
  313. $alias = '';
  314. $explicitAlias = false;
  315. } elseif ($token === ';') {
  316. $statements[$alias] = $class;
  317. break;
  318. } else {
  319. break;
  320. }
  321. }
  322. return $statements;
  323. }
  324. }