Completed
Pull Request — master (#416)
by
unknown
01:51
created

ResponseFileStrategy::__invoke()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 3
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
        $responseFileTags = array_filter($tags, function ($tag) {
36
            return $tag instanceof Tag && strtolower($tag->getName()) === 'responsefile';
37
        });
38
39
        if (empty($responseFileTags)) {
40
            return;
41
        }
42
43
        return array_map(function (Tag $responseFileTag) {
44
            preg_match('/^(\d{3})?\s?([\s\S]*)$/', $responseFileTag->getContent(), $result);
45
46
            $status = $result[1] ?: 200;
47
            $content = $result[2] ? file_get_contents(storage_path($result[2]), true) : '{}';
48
49
            return new JsonResponse(json_decode($content, true), (int) $status);
50
        }, $responseFileTags);
51
    }
52
}
53