Completed
Pull Request — master (#457)
by
unknown
01:36
created

CollectionWriter::getResponseAccessTokenKey()   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 0
1
<?php
2
3
namespace Mpociot\ApiDoc\Postman;
4
5
use Ramsey\Uuid\Uuid;
6
use Illuminate\Support\Collection;
7
use Illuminate\Support\Facades\URL;
8
9
class CollectionWriter
10
{
11
    /**
12
     * @var Collection
13
     */
14
    private $routeGroups;
15
16
    private $usePostmanEnvironment;
17
18
    private $addResponseExample;
19
20
    /**
21
     * CollectionWriter constructor.
22
     *
23
     * @param Collection $routeGroups
24
     */
25
    public function __construct(Collection $routeGroups)
26
    {
27
        $this->routeGroups = $routeGroups;
28
        $this->usePostmanEnvironment = (bool) $this->getPostmanEnvironment();
29
        $this->addResponseExample = config('apidoc.postman.add_response_example', false);
30
    }
31
32
    protected function getPostmanEnvironment()
33
    {
34
        return config('apidoc.postman.environment');
35
    }
36
37
    /**
38
     * @param $route
39
     *
40
     * @return string
41
     */
42
    function getRouteUri($route): string
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
43
    {
44
        if ($this->usePostmanEnvironment) {
45
            $baseUrl = config('apidoc.postman.environment.variables.baseUrl');
46
            if ($baseUrl) {
47
                return '{{' . $baseUrl . '}}' . '/' . $route['uri'];
48
            } else {
49
                return url($route['uri']);
50
            }
51
        }
52
53
        return url($route['uri']);
54
    }
55
56
    /**
57
     * Returns Auth response object key with access token string.
58
     *
59
     * @return string
60
     */
61
    protected function getResponseAccessTokenKey(): string
62
    {
63
        return config('apidoc.postman.environment.auth_response_access_token_key', 'data');
64
    }
65
66
    /**
67
     * Returns Auth response object key with refresh token string
68
     *
69
     * @return string
70
     */
71
    protected function getResponseRefreshTokenKey(): string
72
    {
73
        return config('apidoc.postman.environment.auth_response_refresh_token_key', 'data');
74
    }
75
76
    protected function getAccessTokenVariable(): string
77
    {
78
        return config('apidoc.postman.environment.variables.accessToken', '');
79
    }
80
81
    protected function getRefreshTokenVariable(): string
82
    {
83
        return config('apidoc.postman.environment.variables.refreshToken', '');
84
    }
85
86
    /**
87
     * @return array
88
     */
89
    protected function getExcludingHeaders()
90
    {
91
        return config('apidoc.postman.excluded_headers', []);
92
    }
93
94
    protected function getRequest($route, $mode)
95
    {
96
        return [
97
            'auth' => $route['authenticated'] ? [
98
                'type' => 'bearer',
99
                'bearer' => [
100
                    'token' => '{{'.$this->getAccessTokenVariable().'}}',
101
                ],
102
            ] : false,
103
            'url' => $this->getRouteUri($route),
104
            'method' => $route['methods'][0],
105
            'header' => collect($route['headers'])->map(function ($header, $key) use ($route) {
106
                if (in_array($key, $this->getExcludingHeaders())) {
107
                    return;
108
                }
109
110
                return [
111
                    'key' => $key,
112
                    'name' => $key,
113
                    'type' => 'text',
114
                    'value' => $header,
115
                ];
116
            })->filter()->values()->toArray(),
117
            'body' => [
118
                'mode' => $mode,
119
                $mode => collect($route['bodyParameters'])->map(function ($parameter, $key) {
120
                    return [
121
                        'key' => $key,
122
                        'value' => isset($parameter['value']) ? ($parameter['type'] === 'boolean' ? (string) $parameter['value'] : $parameter['value']) : '',
123
                        'description' => implode(' | ', [($parameter['required'] ? 'required' : 'optional'), $parameter['type'], $parameter['description']]),
124
                        'type' => 'text',
125
                        'enabled' => true,
126
                    ];
127
                })->values()->toArray(),
128
            ],
129
            'description' => $route['description'],
130
        ];
131
    }
132
133
    public function getCollection()
134
    {
135
        URL::forceRootUrl(config('app.url'));
136
137
        $collection = [
138
            'variables' => [],
139
            'info' => [
140
                'name' => config('apidoc.postman.name') ?: config('app.name').' API',
141
                '_postman_id' => Uuid::uuid4()->toString(),
142
                'description' => config('apidoc.postman.description') ?: '',
143
                'schema' => 'https://schema.getpostman.com/json/collection/v2.0.0/collection.json',
144
            ],
145
            'item' => $this->routeGroups->map(function ($routes, $group) {
146
                list($groupName, $groupDescription) = explode("\n\n", $group);
147
                return [
148
                    'name' => $groupName,
149
                    'description' => $groupDescription,
150
                    'item' => $routes->map(function ($route) {
151
                        $mode = $route['methods'][0] === 'PUT' ? 'urlencoded' : 'formdata';
152
153
                        return [
154
                            'name' => $route['title'] != '' ? $route['title'] : $this->getRouteUri($route),
155
                            'event' => [[
156
                                'listen' => 'test',
157
                                'script' => $this->usePostmanEnvironment ? [
158
                                    'id' => Uuid::uuid4()->toString(),
159
                                    'exec' => [
160
                                        'var response = JSON.parse(responseBody);',
161
                                        'tests["Successful request"] = responseCode.code === 200;',
162
                                        'if (response.'.$this->getResponseAccessTokenKey().') { postman.setEnvironmentVariable("'.$this->getAccessTokenVariable().'", response.'.$this->getResponseAccessTokenKey().'); }',
163
                                        'if (response.'.$this->getResponseRefreshTokenKey().') { postman.setEnvironmentVariable("'.$this->getRefreshTokenVariable().'", response.'.$this->getResponseRefreshTokenKey().'); }',
164
                                    ],
165
                                    'type' => 'text/javascript',
166
                                ] : [],
167
                            ]],
168
                            'request' => $this->getRequest($route, $mode),
169
                            'response' => $this->addResponseExample ? [
170
                                [
171
                                    'name' => $route['title'] != '' ? $route['title'] : $this->getRouteUri($route),
172
                                    'originalRequest' => $this->getRequest($route, $mode),
173
                                    'status' => $route['response'][0]['statusText'],
174
                                    'code' => $route['response'][0]['status'],
175
                                    '_postman_previewlanguage' => 'json',
176
                                    'header' => collect($route['response'][0]['headers'])->map(function ($header, $key) use ($route) {
177
                                        return [
178
                                            'key' => $key,
179
                                            'name' => $key,
180
                                            'type' => 'text',
181
                                            'value' => $header,
182
                                        ];
183
                                    })->values()->toArray(),
184
                                    'body' => json_encode(json_decode($route['response'][0]['content']), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE),
185
                                ],
186
                            ] : [],
187
                        ];
188
                    })->toArray(),
189
                ];
190
            })->values()->toArray(),
191
        ];
192
193
        return json_encode($collection);
194
    }
195
}
196