ResponseFileStrategy.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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(trim($result[2])), true) : '{}';
  44. $json = ! empty($result[3]) ? str_replace("'", '"', $result[3]) : '{}';
  45. $merged = array_merge(json_decode($content, true), json_decode($json, true));
  46. return new JsonResponse($merged, (int) $status);
  47. }, $responseFileTags);
  48. }
  49. }