Completed
Pull Request — master (#457)
by
unknown
02:29 queued 55s
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
    protected function getRouteUri($route): string
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
148
                return [
149
                    'name' => $groupName,
150
                    'description' => $groupDescription,
151
                    'item' => $routes->map(function ($route) {
152
                        $mode = $route['methods'][0] === 'PUT' ? 'urlencoded' : 'formdata';
153
154
                        return [
155
                            'name' => $route['title'] != '' ? $route['title'] : $this->getRouteUri($route),
156
                            'event' => [[
157
                                'listen' => 'test',
158
                                'script' => $this->usePostmanEnvironment ? [
159
                                    'id' => Uuid::uuid4()->toString(),
160
                                    'exec' => [
161
                                        'var response = JSON.parse(responseBody);',
162
                                        'tests["Successful request"] = responseCode.code === 200;',
163
                                        'if (response.'.$this->getResponseAccessTokenKey().') { postman.setEnvironmentVariable("'.$this->getAccessTokenVariable().'", response.'.$this->getResponseAccessTokenKey().'); }',
164
                                        'if (response.'.$this->getResponseRefreshTokenKey().') { postman.setEnvironmentVariable("'.$this->getRefreshTokenVariable().'", response.'.$this->getResponseRefreshTokenKey().'); }',
165
                                    ],
166
                                    'type' => 'text/javascript',
167
                                ] : [],
168
                            ]],
169
                            'request' => $this->getRequest($route, $mode),
170
                            'response' => $this->addResponseExample ? [
171
                                [
172
                                    'name' => $route['title'] != '' ? $route['title'] : $this->getRouteUri($route),
173
                                    'originalRequest' => $this->getRequest($route, $mode),
174
                                    'status' => $route['response'][0]['statusText'],
175
                                    'code' => $route['response'][0]['status'],
176
                                    '_postman_previewlanguage' => 'json',
177
                                    'header' => collect($route['response'][0]['headers'])->map(function ($header, $key) use ($route) {
178
                                        return [
179
                                            'key' => $key,
180
                                            'name' => $key,
181
                                            'type' => 'text',
182
                                            'value' => $header,
183
                                        ];
184
                                    })->values()->toArray(),
185
                                    'body' => json_encode(json_decode($route['response'][0]['content']), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE),
186
                                ],
187
                            ] : [],
188
                        ];
189
                    })->toArray(),
190
                ];
191
            })->values()->toArray(),
192
        ];
193
194
        return json_encode($collection);
195
    }
196
}
197