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