4
0

StaticAnalyserTest.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php declare(strict_types=1);
  2. /**
  3. * @license Apache 2.0
  4. */
  5. namespace OpenApiTests;
  6. use OpenApi\Analyser;
  7. use OpenApi\Annotations\Property;
  8. use OpenApi\Context;
  9. use OpenApi\StaticAnalyser;
  10. class StaticAnalyserTest extends OpenApiTestCase
  11. {
  12. public function testWrongCommentType()
  13. {
  14. $analyser = new StaticAnalyser();
  15. $this->assertOpenApiLogEntryStartsWith('Annotations are only parsed inside `/**` DocBlocks');
  16. $analyser->fromCode("<?php\n/*\n * @OA\Parameter() */", new Context([]));
  17. }
  18. public function testIndentationCorrection()
  19. {
  20. $analyser = new StaticAnalyser();
  21. $analysis = $analyser->fromFile(__DIR__.'/Fixtures/routes.php');
  22. $this->assertCount(20, $analysis->annotations);
  23. }
  24. public function testTrait()
  25. {
  26. $analyser = new StaticAnalyser();
  27. $analysis = $analyser->fromFile(__DIR__.'/Fixtures/HelloTrait.php');
  28. $this->assertCount(2, $analysis->annotations);
  29. $property = $analysis->getAnnotationsOfType(Property::class);
  30. $this->assertSame('Hello', $property[0]->_context->trait);
  31. }
  32. public function testThirdPartyAnnotations()
  33. {
  34. $backup = Analyser::$whitelist;
  35. Analyser::$whitelist = ['OpenApi\Annotations\\'];
  36. $analyser = new StaticAnalyser();
  37. $defaultAnalysis = $analyser->fromFile(__DIR__.'/Fixtures/ThirdPartyAnnotations.php');
  38. $this->assertCount(3, $defaultAnalysis->annotations, 'Only read the @OA annotations, skip the others.');
  39. // Allow the analyser to parse 3rd party annotations, which might
  40. // contain useful info that could be extracted with a custom processor
  41. Analyser::$whitelist[] = 'Zend\Form\Annotation';
  42. $openapi = \OpenApi\scan(__DIR__.'/Fixtures/ThirdPartyAnnotations.php');
  43. $this->assertSame('api/3rd-party', $openapi->paths[0]->path);
  44. $this->assertCount(10, $openapi->_unmerged);
  45. Analyser::$whitelist = $backup;
  46. $analysis = $openapi->_analysis;
  47. $annotations = $analysis->getAnnotationsOfType('Zend\Form\Annotation\Name');
  48. $this->assertCount(1, $annotations);
  49. $context = $analysis->getContext($annotations[0]);
  50. $this->assertInstanceOf('OpenApi\Context', $context);
  51. $this->assertSame('ThirdPartyAnnotations', $context->class);
  52. $this->assertSame('\OpenApiFixtures\ThirdPartyAnnotations', $context->fullyQualifiedName($context->class));
  53. $this->assertCount(2, $context->annotations);
  54. }
  55. public function testAnonymousClassProducesNoError()
  56. {
  57. try {
  58. $analyser = new StaticAnalyser(__DIR__.'/Fixtures/php7.php');
  59. $this->assertTrue(true);
  60. } catch (\Exception $e) {
  61. $this->fail("Analyser produced an error: {$e->getMessage()}");
  62. }
  63. }
  64. }