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