ResponseFileStrategy.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. namespace Mpociot\ApiDoc\Tools\ResponseStrategies;
  3. use Illuminate\Routing\Route;
  4. use Illuminate\Http\JsonResponse;
  5. use Mpociot\Reflection\DocBlock\Tag;
  6. /**
  7. * Get a response from from a file in the docblock ( @responseFile ).
  8. */
  9. class ResponseFileStrategy
  10. {
  11. /**
  12. * @param Route $route
  13. * @param array $tags
  14. * @param array $routeProps
  15. *
  16. * @return array|null
  17. */
  18. public function __invoke(Route $route, array $tags, array $routeProps)
  19. {
  20. return $this->getFileResponses($tags);
  21. }
  22. /**
  23. * Get the response from the file if available.
  24. *
  25. * @param array $tags
  26. *
  27. * @return array|null
  28. */
  29. protected function getFileResponses(array $tags)
  30. {
  31. // avoid "holes" in the keys of the filtered array, by using array_values on the filtered array
  32. $responseFileTags = array_values(
  33. array_filter($tags, function ($tag) {
  34. return $tag instanceof Tag && strtolower($tag->getName()) === 'responsefile';
  35. })
  36. );
  37. if (empty($responseFileTags)) {
  38. return;
  39. }
  40. return array_map(function (Tag $responseFileTag) {
  41. preg_match('/^(\d{3})?\s?([\s\S]*)$/', $responseFileTag->getContent(), $result);
  42. $status = $result[1] ?: 200;
  43. $content = $result[2] ? file_get_contents(storage_path($result[2]), true) : '{}';
  44. return new JsonResponse(json_decode($content, true), (int) $status);
  45. }, $responseFileTags);
  46. }
  47. }