• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

RonasIT / laravel-swagger / 21505246473

30 Jan 2026 05:14AM UTC coverage: 99.669% (+0.01%) from 99.656%
21505246473

Pull #193

github

web-flow
Merge b0b734c52 into 1743f07bc
Pull Request #193: feat: name response object by resource class

16 of 16 new or added lines in 1 file covered. (100.0%)

1 existing line in 1 file now uncovered.

904 of 907 relevant lines covered (99.67%)

22.96 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

99.79
/src/Services/SwaggerService.php
1
<?php
2

3
namespace RonasIT\AutoDoc\Services;
4

5
use Illuminate\Container\Container;
6
use Illuminate\Http\Request;
7
use Illuminate\Http\Testing\File;
8
use Illuminate\Support\Arr;
9
use Illuminate\Support\Facades\ParallelTesting;
10
use Illuminate\Support\Facades\URL;
11
use Illuminate\Support\Str;
12
use ReflectionClass;
13
use RonasIT\AutoDoc\Actions\GetResourceFromResponseAction;
14
use RonasIT\AutoDoc\Contracts\SwaggerDriverContract;
15
use RonasIT\AutoDoc\Exceptions\DocFileNotExistsException;
16
use RonasIT\AutoDoc\Exceptions\EmptyContactEmailException;
17
use RonasIT\AutoDoc\Exceptions\EmptyDocFileException;
18
use RonasIT\AutoDoc\Exceptions\InvalidDriverClassException;
19
use RonasIT\AutoDoc\Exceptions\LegacyConfigException;
20
use RonasIT\AutoDoc\Exceptions\SpecValidation\InvalidSwaggerSpecException;
21
use RonasIT\AutoDoc\Exceptions\SwaggerDriverClassNotFoundException;
22
use RonasIT\AutoDoc\Exceptions\UnsupportedDocumentationViewerException;
23
use RonasIT\AutoDoc\Exceptions\WrongSecurityConfigException;
24
use RonasIT\AutoDoc\Traits\GetDependenciesTrait;
25
use RonasIT\AutoDoc\Validators\SwaggerSpecValidator;
26
use Symfony\Component\HttpFoundation\Response;
27
use Throwable;
28

29
/**
30
 * @property SwaggerDriverContract $driver
31
 */
32
class SwaggerService
33
{
34
    use GetDependenciesTrait;
35

36
    public const string OPEN_API_VERSION = '3.1.0';
37

38
    protected $driver;
39
    protected $openAPIValidator;
40

41
    protected $data;
42
    protected $config;
43
    protected $container;
44
    private $uri;
45
    private $method;
46
    /**
47
     * @var Request
48
     */
49
    private $request;
50
    private $item;
51
    private $security;
52

53
    protected array $ruleToTypeMap = [
54
        'array' => 'object',
55
        'boolean' => 'boolean',
56
        'date' => 'date',
57
        'digits' => 'integer',
58
        'integer' => 'integer',
59
        'numeric' => 'double',
60
        'string' => 'string',
61
        'int' => 'integer',
62
    ];
63

64
    protected $booleanAnnotations = [
65
        'deprecated',
66
    ];
67

68
    public function __construct(Container $container)
69
    {
70
        $this->openAPIValidator = app(SwaggerSpecValidator::class);
106✔
71

72
        $this->initConfig();
106✔
73

74
        $this->setDriver();
101✔
75

76
        if (config('app.env') === 'testing') {
99✔
77
            // client must enter at least `contact.email` to generate a default `info` block
78
            // otherwise an exception will be called
79
            $this->checkEmail();
99✔
80

81
            $this->container = $container;
98✔
82

83
            $this->security = $this->config['security'];
98✔
84

85
            $this->data = $this->driver->getProcessTmpData();
98✔
86

87
            if (empty($this->data)) {
98✔
88
                $this->data = $this->generateEmptyData();
62✔
89

90
                $this->driver->saveProcessTmpData($this->data);
62✔
91
            }
92
        }
93
    }
94

95
    protected function initConfig()
96
    {
97
        $this->config = config('auto-doc');
106✔
98

99
        $version = Arr::get($this->config, 'config_version');
106✔
100

101
        if (empty($version)) {
106✔
102
            throw new LegacyConfigException();
1✔
103
        }
104

105
        $packageConfigs = require __DIR__ . '/../../config/auto-doc.php';
105✔
106

107
        if (version_compare($packageConfigs['config_version'], $version, '>')) {
105✔
108
            throw new LegacyConfigException();
1✔
109
        }
110

111
        $documentationViewer = (string) Arr::get($this->config, 'documentation_viewer');
104✔
112

113
        if (!view()->exists("auto-doc::documentation-{$documentationViewer}")) {
104✔
114
            throw new UnsupportedDocumentationViewerException($documentationViewer);
2✔
115
        }
116

117
        $securityDriver = Arr::get($this->config, 'security');
102✔
118

119
        if ($securityDriver && !array_key_exists($securityDriver, Arr::get($this->config, 'security_drivers'))) {
102✔
120
            throw new WrongSecurityConfigException();
1✔
121
        }
122
    }
123

124
    protected function setDriver()
125
    {
126
        $driver = $this->config['driver'];
101✔
127
        $className = Arr::get($this->config, "drivers.{$driver}.class");
101✔
128

129
        if (!class_exists($className)) {
101✔
130
            throw new SwaggerDriverClassNotFoundException($className);
1✔
131
        } else {
132
            $this->driver = app($className);
100✔
133
        }
134

135
        if (!$this->driver instanceof SwaggerDriverContract) {
100✔
136
            throw new InvalidDriverClassException($driver);
1✔
137
        }
138
    }
139

140
    protected function generateEmptyData(?string $view = null, array $viewData = [], array $license = []): array
141
    {
142
        if (empty($view) && !empty($this->config['info'])) {
63✔
143
            $view = $this->config['info']['description'];
61✔
144
        }
145

146
        $data = [
63✔
147
            'openapi' => self::OPEN_API_VERSION,
63✔
148
            'servers' => [
63✔
149
                ['url' => URL::query($this->config['basePath'])],
63✔
150
            ],
63✔
151
            'paths' => [],
63✔
152
            'components' => [
63✔
153
                'schemas' => $this->config['definitions'],
63✔
154
            ],
63✔
155
            'info' => $this->prepareInfo($view, $viewData, $license),
63✔
156
        ];
63✔
157

158
        $securityDefinitions = $this->generateSecurityDefinition();
63✔
159

160
        if (!empty($securityDefinitions)) {
63✔
161
            $data['securityDefinitions'] = $securityDefinitions;
3✔
162
        }
163

164
        return $data;
63✔
165
    }
166

167
    protected function checkEmail(): void
168
    {
169
        if (!empty($this->config['info']) && !Arr::get($this->config, 'info.contact.email')) {
99✔
170
            throw new EmptyContactEmailException();
1✔
171
        }
172
    }
173

174
    protected function generateSecurityDefinition(): ?array
175
    {
176
        if (empty($this->security)) {
63✔
177
            return null;
60✔
178
        }
179

180
        return [
3✔
181
            $this->security => $this->generateSecurityDefinitionObject($this->security),
3✔
182
        ];
3✔
183
    }
184

185
    protected function generateSecurityDefinitionObject($type): array
186
    {
187
        return [
3✔
188
            'type' => $this->config['security_drivers'][$type]['type'],
3✔
189
            'name' => $this->config['security_drivers'][$type]['name'],
3✔
190
            'in' => $this->config['security_drivers'][$type]['in'],
3✔
191
        ];
3✔
192
    }
193

194
    public function addData(Request $request, $response)
195
    {
196
        $this->request = $request;
32✔
197

198
        $this->prepareItem();
32✔
199

200
        $this->parseRequest();
32✔
201
        $this->parseResponse($response);
32✔
202

203
        $this->driver->saveProcessTmpData($this->data);
32✔
204
    }
205

206
    protected function prepareItem()
207
    {
208
        $this->uri = "/{$this->getUri()}";
32✔
209
        $this->method = strtolower($this->request->getMethod());
32✔
210

211
        if (empty(Arr::get($this->data, "paths.{$this->uri}.{$this->method}"))) {
32✔
212
            $this->data['paths'][$this->uri][$this->method] = [
31✔
213
                'tags' => [],
31✔
214
                'consumes' => [],
31✔
215
                'produces' => [],
31✔
216
                'parameters' => $this->getPathParams(),
31✔
217
                'responses' => [],
31✔
218
                'security' => [],
31✔
219
                'description' => '',
31✔
220
            ];
31✔
221
        }
222

223
        $this->item = &$this->data['paths'][$this->uri][$this->method];
32✔
224
    }
225

226
    protected function getUri()
227
    {
228
        $uri = $this->request->route()->uri();
32✔
229
        $basePath = preg_replace("/^\//", '', $this->config['basePath']);
32✔
230
        $preparedUri = preg_replace("/^{$basePath}/", '', $uri);
32✔
231

232
        return preg_replace("/^\//", '', $preparedUri);
32✔
233
    }
234

235
    protected function getPathParams(): array
236
    {
237
        $params = [];
31✔
238

239
        preg_match_all('/{.*?}/', $this->uri, $params);
31✔
240

241
        $params = Arr::collapse($params);
31✔
242

243
        $result = [];
31✔
244

245
        foreach ($params as $param) {
31✔
246
            $key = preg_replace('/[{}]/', '', $param);
6✔
247

248
            $result[] = [
6✔
249
                'in' => 'path',
6✔
250
                'name' => $key,
6✔
251
                'description' => $this->generatePathDescription($key),
6✔
252
                'required' => true,
6✔
253
                'schema' => [
6✔
254
                    'type' => 'string',
6✔
255
                ],
6✔
256
            ];
6✔
257
        }
258

259
        return $result;
31✔
260
    }
261

262
    protected function generatePathDescription(string $key): string
263
    {
264
        $expression = Arr::get($this->request->route()->wheres, $key);
6✔
265

266
        if (empty($expression)) {
6✔
267
            return '';
6✔
268
        }
269

270
        $exploded = explode('|', $expression);
1✔
271

272
        foreach ($exploded as $value) {
1✔
273
            if (!preg_match('/^[a-zA-Z0-9\.]+$/', $value)) {
1✔
274
                return "regexp: {$expression}";
1✔
275
            }
276
        }
277

278
        return 'in: ' . implode(',', $exploded);
1✔
279
    }
280

281
    protected function parseRequest()
282
    {
283
        $this->saveConsume();
32✔
284
        $this->saveTags();
32✔
285
        $this->saveSecurity();
32✔
286

287
        $concreteRequest = $this->getConcreteRequest();
32✔
288

289
        if (empty($concreteRequest)) {
32✔
290
            $this->item['description'] = '';
4✔
291

292
            return;
4✔
293
        }
294

295
        $annotations = $this->getClassAnnotations($concreteRequest);
28✔
296

297
        $this->markAsDeprecated($annotations);
28✔
298
        $this->saveParameters($concreteRequest, $annotations);
28✔
299
        $this->saveDescription($concreteRequest, $annotations);
28✔
300
    }
301

302
    protected function markAsDeprecated(array $annotations)
303
    {
304
        $this->item['deprecated'] = Arr::get($annotations, 'deprecated', false);
28✔
305
    }
306

307
    protected function saveResponseSchema(?array $content, string $definition): void
308
    {
309
        $schemaProperties = [];
32✔
310
        $schemaType = 'object';
32✔
311

312
        if (!empty($content) && array_is_list($content)) {
32✔
313
            $this->saveListResponseDefinitions($content, $schemaProperties);
16✔
314

315
            $schemaType = 'array';
16✔
316
        } else {
317
            $this->saveObjectResponseDefinitions($content, $schemaProperties, $definition);
16✔
318
        }
319

320
        $this->data['components']['schemas'][$definition] = [
32✔
321
            'type' => $schemaType,
32✔
322
            'properties' => $schemaProperties,
32✔
323
        ];
32✔
324
    }
325

326
    protected function saveListResponseDefinitions(array $content, array &$schemaProperties): void
327
    {
328
        $types = [];
16✔
329

330
        foreach ($content as $value) {
16✔
331
            $type = gettype($value);
16✔
332

333
            if (!in_array($type, $types)) {
16✔
334
                $types[] = $type;
16✔
335
                $schemaProperties['items']['allOf'][]['type'] = $type;
16✔
336
            }
337
        }
338
    }
339

340
    protected function saveObjectResponseDefinitions(array $content, array &$schemaProperties, string $definition): void
341
    {
342
        $properties = Arr::get($this->data, "components.schemas.{$definition}", []);
16✔
343

344
        foreach ($content as $name => $value) {
16✔
345
            $property = Arr::get($properties, "properties.{$name}", []);
14✔
346

347
            if (is_null($value)) {
14✔
348
                $property['nullable'] = true;
2✔
349
            } else {
350
                $property['type'] = gettype($value);
14✔
351
            }
352

353
            $schemaProperties[$name] = $property;
14✔
354
        }
355
    }
356

357
    protected function parseResponse($response)
358
    {
359
        $produceList = $this->data['paths'][$this->uri][$this->method]['produces'];
32✔
360

361
        $produce = $response->headers->get('Content-type');
32✔
362

363
        if (is_null($produce)) {
32✔
364
            $produce = 'text/plain';
2✔
365
        }
366

367
        if (!in_array($produce, $produceList)) {
32✔
368
            $this->item['produces'][] = $produce;
31✔
369
        }
370

371
        $responses = $this->item['responses'];
32✔
372

373
        $responseExampleLimitCount = config('auto-doc.response_example_limit_count');
32✔
374

375
        $content = json_decode($response->getContent(), true) ?? [];
32✔
376

377
        if (!empty($responseExampleLimitCount)) {
32✔
378
            if (!empty($content['data'])) {
32✔
379
                $limitedResponseData = array_slice($content['data'], 0, $responseExampleLimitCount, true);
3✔
380
                $content['data'] = $limitedResponseData;
3✔
381
                $content['to'] = count($limitedResponseData);
3✔
382
                $content['total'] = count($limitedResponseData);
3✔
383
            }
384
        }
385

386
        if (!empty($content['exception'])) {
32✔
387
            $uselessKeys = array_keys(Arr::except($content, ['message']));
1✔
388

389
            $content = Arr::except($content, $uselessKeys);
1✔
390
        }
391

392
        $code = $response->getStatusCode();
32✔
393

394
        if (!in_array($code, $responses)) {
32✔
395
            $this->saveExample(
32✔
396
                $code,
32✔
397
                json_encode($content, JSON_PRETTY_PRINT),
32✔
398
                $produce,
32✔
399
            );
32✔
400
        }
401

402
        $action = Str::ucfirst($this->getActionName($this->uri));
32✔
403

404
        $resourceName = app(GetResourceFromResponseAction::class)->execute($this->request->route());
32✔
405

406
        $definition = (!empty($resourceName))
32✔
407
            ? Str::replace('Resource', '', $resourceName)
4✔
408
            : "{$this->method}{$action}{$code}ResponseObject";
28✔
409

410
        $this->saveResponseSchema($content, $definition);
32✔
411

412
        if (is_array($this->item['responses'][$code])) {
32✔
413
            $this->item['responses'][$code]['content'][$produce]['schema']['$ref'] = "#/components/schemas/{$definition}";
31✔
414
        }
415
    }
416

417
    protected function saveExample($code, $content, $produce)
418
    {
419
        $description = $this->getResponseDescription($code);
32✔
420
        $availableContentTypes = [
32✔
421
            'application',
32✔
422
            'text',
32✔
423
            'image',
32✔
424
        ];
32✔
425
        $explodedContentType = explode('/', $produce);
32✔
426

427
        if (in_array($explodedContentType[0], $availableContentTypes)) {
32✔
428
            $this->item['responses'][$code] = $this->makeResponseExample($content, $produce, $description);
31✔
429
        } else {
430
            $this->item['responses'][$code] = '*Unavailable for preview*';
1✔
431
        }
432
    }
433

434
    protected function makeResponseExample($content, $mimeType, $description = ''): array
435
    {
436
        $example = match ($mimeType) {
31✔
437
            'application/json' => json_decode($content, true),
27✔
438
            'application/pdf' => base64_encode($content),
1✔
439
            default => $content,
3✔
440
        };
31✔
441

442
        return [
31✔
443
            'description' => $description,
31✔
444
            'content' => [
31✔
445
                $mimeType => [
31✔
446
                    'schema' => [
31✔
447
                        'type' => 'object',
31✔
448
                    ],
31✔
449
                    'example' => $example,
31✔
450
                ],
31✔
451
            ],
31✔
452
        ];
31✔
453
    }
454

455
    protected function saveParameters($request, array $annotations)
456
    {
457
        $formRequest = new $request();
28✔
458
        $formRequest->setUserResolver($this->request->getUserResolver());
28✔
459
        $formRequest->setRouteResolver($this->request->getRouteResolver());
28✔
460
        $rules = method_exists($formRequest, 'rules') ? $this->prepareRules($formRequest->rules()) : [];
28✔
461
        $attributes = method_exists($formRequest, 'attributes') ? $formRequest->attributes() : [];
28✔
462

463
        $actionName = $this->getActionName($this->uri);
28✔
464

465
        if (in_array($this->method, ['get', 'delete'])) {
28✔
466
            $this->saveGetRequestParameters($rules, $attributes, $annotations);
22✔
467
        } else {
468
            $this->savePostRequestParameters($actionName, $rules, $attributes, $annotations);
6✔
469
        }
470
    }
471

472
    protected function prepareRules(array $rules): array
473
    {
474
        $preparedRules = [];
27✔
475

476
        foreach ($rules as $field => $rulesField) {
27✔
477
            if (is_array($rulesField)) {
27✔
478
                $rulesField = array_map(function ($rule) {
25✔
479
                    return $this->getRuleAsString($rule);
25✔
480
                }, $rulesField);
25✔
481

482
                $preparedRules[$field] = implode('|', $rulesField);
25✔
483
            } else {
484
                $preparedRules[$field] = $this->getRuleAsString($rulesField);
27✔
485
            }
486
        }
487

488
        return $preparedRules;
27✔
489
    }
490

491
    protected function getRuleAsString($rule): string
492
    {
493
        if (is_object($rule)) {
27✔
494
            if (method_exists($rule, '__toString')) {
25✔
495
                return $rule->__toString();
25✔
496
            }
497

498
            $shortName = Str::afterLast(get_class($rule), '\\');
25✔
499

500
            $ruleName = preg_replace('/Rule$/', '', $shortName);
25✔
501

502
            return Str::snake($ruleName);
25✔
503
        }
504

505
        return $rule;
27✔
506
    }
507

508
    protected function saveGetRequestParameters($rules, array $attributes, array $annotations)
509
    {
510
        foreach ($rules as $parameter => $rule) {
22✔
511
            $validation = explode('|', $rule);
21✔
512

513
            $description = Arr::get($annotations, $parameter);
21✔
514

515
            if (empty($description)) {
21✔
516
                $description = Arr::get($attributes, $parameter, implode(', ', $validation));
21✔
517
            }
518

519
            $existedParameter = Arr::first($this->item['parameters'], function ($existedParameter) use ($parameter) {
21✔
520
                return $existedParameter['name'] === $parameter;
19✔
521
            });
21✔
522

523
            if (empty($existedParameter)) {
21✔
524
                $parameterDefinition = [
20✔
525
                    'in' => 'query',
20✔
526
                    'name' => $parameter,
20✔
527
                    'description' => $description,
20✔
528
                    'schema' => [
20✔
529
                        'type' => $this->getParameterType($validation),
20✔
530
                    ],
20✔
531
                ];
20✔
532
                if (in_array('required', $validation)) {
20✔
533
                    $parameterDefinition['required'] = true;
20✔
534
                }
535

536
                $this->item['parameters'][] = $parameterDefinition;
20✔
537
            }
538
        }
539
    }
540

541
    protected function savePostRequestParameters($actionName, $rules, array $attributes, array $annotations)
542
    {
543
        if ($this->requestHasMoreProperties($actionName)) {
6✔
544
            if ($this->requestHasBody()) {
6✔
545
                $type = $this->request->header('Content-Type', 'application/json');
6✔
546

547
                $this->item['requestBody'] = [
6✔
548
                    'content' => [
6✔
549
                        $type => [
6✔
550
                            'schema' => [
6✔
551
                                '$ref' => "#/components/schemas/{$actionName}Object",
6✔
552
                            ],
6✔
553
                        ],
6✔
554
                    ],
6✔
555
                    'description' => '',
6✔
556
                    'required' => true,
6✔
557
                ];
6✔
558
            }
559

560
            $this->saveDefinitions($actionName, $rules, $attributes, $annotations);
6✔
561
        }
562
    }
563

564
    protected function saveDefinitions($objectName, $rules, $attributes, array $annotations)
565
    {
566
        $data = [
6✔
567
            'type' => 'object',
6✔
568
            'properties' => [],
6✔
569
        ];
6✔
570

571
        foreach ($rules as $parameter => $rule) {
6✔
572
            $rulesArray = (is_array($rule)) ? $rule : explode('|', $rule);
6✔
573
            $parameterType = $this->getParameterType($rulesArray);
6✔
574
            $this->saveParameterType($data, $parameter, $parameterType);
6✔
575

576
            $uselessRules = $this->ruleToTypeMap;
6✔
577
            $uselessRules['required'] = 'required';
6✔
578

579
            if (in_array('required', $rulesArray)) {
6✔
580
                $data['required'][] = $parameter;
6✔
581
            }
582

583
            $rulesArray = array_flip(array_diff_key(array_flip($rulesArray), $uselessRules));
6✔
584

585
            $this->saveParameterDescription($data, $parameter, $rulesArray, $attributes, $annotations);
6✔
586
        }
587

588
        $data['example'] = $this->generateExample($data['properties']);
6✔
589
        $this->data['components']['schemas']["{$objectName}Object"] = $data;
6✔
590
    }
591

592
    protected function getParameterType(array $validation): string
593
    {
594
        $validationRules = $this->ruleToTypeMap;
26✔
595
        $validationRules['email'] = 'string';
26✔
596

597
        $parameterType = 'string';
26✔
598

599
        foreach ($validation as $item) {
26✔
600
            if (in_array($item, array_keys($validationRules))) {
26✔
601
                return $validationRules[$item];
25✔
602
            }
603
        }
604

605
        return $parameterType;
25✔
606
    }
607

608
    protected function saveParameterType(&$data, $parameter, $parameterType)
609
    {
610
        $data['properties'][$parameter] = [
6✔
611
            'type' => $parameterType,
6✔
612
        ];
6✔
613
    }
614

615
    protected function saveParameterDescription(
616
        array &$data,
617
        string $parameter,
618
        array $rulesArray,
619
        array $attributes,
620
        array $annotations,
621
    ) {
622
        $description = Arr::get($annotations, $parameter);
6✔
623

624
        if (empty($description)) {
6✔
625
            $description = Arr::get($attributes, $parameter, implode(', ', $rulesArray));
6✔
626
        }
627

628
        $data['properties'][$parameter]['description'] = $description;
6✔
629
    }
630

631
    protected function requestHasMoreProperties($actionName): bool
632
    {
633
        $requestParametersCount = count($this->request->all());
6✔
634

635
        $properties = Arr::get($this->data, "components.schemas.{$actionName}Object.properties", []);
6✔
636
        $objectParametersCount = count($properties);
6✔
637

638
        return $requestParametersCount > $objectParametersCount;
6✔
639
    }
640

641
    protected function requestHasBody(): bool
642
    {
643
        $parameters = $this->data['paths'][$this->uri][$this->method]['parameters'];
6✔
644

645
        $bodyParamExisted = Arr::where($parameters, function ($value) {
6✔
646
            return $value['name'] === 'body';
1✔
647
        });
6✔
648

649
        return empty($bodyParamExisted);
6✔
650
    }
651

652
    public function getConcreteRequest()
653
    {
654
        $controller = $this->request->route()->getActionName();
32✔
655

656
        if ($controller === 'Closure') {
32✔
657
            return null;
2✔
658
        }
659

660
        $explodedController = explode('@', $controller);
30✔
661

662
        $class = $explodedController[0];
30✔
663
        $method = Arr::get($explodedController, 1, '__invoke');
30✔
664

665
        if (!method_exists($class, $method)) {
30✔
666
            return null;
1✔
667
        }
668

669
        $parameters = $this->resolveClassMethodDependencies(
29✔
670
            app($class),
29✔
671
            $method,
29✔
672
        );
29✔
673

674
        return Arr::first($parameters, function ($key) {
29✔
675
            return preg_match('/Request/', $key);
29✔
676
        });
29✔
677
    }
678

679
    public function saveConsume()
680
    {
681
        $consumeList = $this->data['paths'][$this->uri][$this->method]['consumes'];
32✔
682
        $consume = $this->request->header('Content-Type');
32✔
683

684
        if (!empty($consume) && !in_array($consume, $consumeList)) {
32✔
685
            $this->item['consumes'][] = $consume;
17✔
686
        }
687
    }
688

689
    public function saveTags()
690
    {
691
        $globalPrefix = config('auto-doc.global_prefix');
32✔
692
        $globalPrefix = Str::after($globalPrefix, '/');
32✔
693

694
        $explodedUri = explode('/', $this->uri);
32✔
695
        $explodedUri = array_filter($explodedUri);
32✔
696

697
        $tag = array_shift($explodedUri);
32✔
698

699
        if ($globalPrefix === $tag) {
32✔
700
            $tag = array_shift($explodedUri);
2✔
701
        }
702

703
        $this->item['tags'] = [$tag];
32✔
704
    }
705

706
    public function saveDescription($request, array $annotations)
707
    {
708
        $this->item['summary'] = $this->getSummary($request, $annotations);
28✔
709

710
        $description = Arr::get($annotations, 'description');
28✔
711

712
        if (!empty($description)) {
28✔
713
            $this->item['description'] = $description;
1✔
714
        }
715
    }
716

717
    protected function saveSecurity()
718
    {
719
        if ($this->requestSupportAuth()) {
32✔
720
            $this->addSecurityToOperation();
5✔
721
        }
722
    }
723

724
    protected function addSecurityToOperation()
725
    {
726
        $security = &$this->data['paths'][$this->uri][$this->method]['security'];
5✔
727

728
        if (empty($security)) {
5✔
729
            $security[] = [
5✔
730
                "{$this->security}" => [],
5✔
731
            ];
5✔
732
        }
733
    }
734

735
    protected function getSummary($request, array $annotations)
736
    {
737
        $summary = Arr::get($annotations, 'summary');
28✔
738

739
        if (empty($summary)) {
28✔
740
            $summary = $this->parseRequestName($request);
27✔
741
        }
742

743
        return $summary;
28✔
744
    }
745

746
    protected function requestSupportAuth(): bool
747
    {
748
        $security = Arr::get($this->config, 'security');
32✔
749
        $securityDriver = Arr::get($this->config, "security_drivers.{$security}");
32✔
750

751
        switch (Arr::get($securityDriver, 'in')) {
32✔
752
            case 'header':
32✔
753
                // TODO Change this logic after migration on Swagger 3.0
754
                // Swagger 2.0 does not support cookie authorization.
755
                $securityToken = $this->request->hasHeader($securityDriver['name'])
8✔
756
                    ? $this->request->header($securityDriver['name'])
5✔
757
                    : $this->request->cookie($securityDriver['name']);
3✔
758

759
                break;
8✔
760
            case 'query':
24✔
761
                $securityToken = $this->request->query($securityDriver['name']);
1✔
762

763
                break;
1✔
764
            default:
765
                $securityToken = null;
23✔
766
        }
767

768
        return !empty($securityToken);
32✔
769
    }
770

771
    protected function parseRequestName($request)
772
    {
773
        $explodedRequest = explode('\\', $request);
27✔
774
        $requestName = array_pop($explodedRequest);
27✔
775
        $summaryName = str_replace('Request', '', $requestName);
27✔
776

777
        $underscoreRequestName = $this->camelCaseToUnderScore($summaryName);
27✔
778

779
        return preg_replace('/[_]/', ' ', $underscoreRequestName);
27✔
780
    }
781

782
    protected function getResponseDescription($code)
783
    {
784
        $defaultDescription = Response::$statusTexts[$code];
32✔
785

786
        $request = $this->getConcreteRequest();
32✔
787

788
        if (empty($request)) {
32✔
789
            return $defaultDescription;
4✔
790
        }
791

792
        $annotations = $this->getClassAnnotations($request);
28✔
793

794
        $localDescription = Arr::get($annotations, "_{$code}");
28✔
795

796
        if (!empty($localDescription)) {
28✔
797
            return $localDescription;
1✔
798
        }
799

800
        return Arr::get($this->config, "defaults.code-descriptions.{$code}", $defaultDescription);
27✔
801
    }
802

803
    protected function getActionName($uri): string
804
    {
805
        $action = preg_replace('[\/]', '', $uri);
32✔
806

807
        return Str::camel($action);
32✔
808
    }
809

810
    public function saveProductionData()
811
    {
812
        if (ParallelTesting::token()) {
4✔
813
            $this->driver->appendProcessDataToTmpFile(function (?array $sharedTmpData) {
2✔
814
                $resultDocContent = (empty($sharedTmpData))
2✔
815
                    ? $this->generateEmptyData($this->config['info']['description'])
1✔
816
                    : $sharedTmpData;
1✔
817

818
                $this->mergeOpenAPIDocs($resultDocContent, $this->data);
2✔
819

820
                return $resultDocContent;
2✔
821
            });
2✔
822
        }
823

824
        $this->driver->saveData();
4✔
825
    }
826

827
    public function getDocFileContent()
828
    {
829
        try {
830
            $documentation = $this->driver->getDocumentation();
46✔
831

832
            $this->openAPIValidator->validate($documentation);
44✔
833
        } catch (Throwable $exception) {
40✔
834
            return $this->generateEmptyData($this->config['defaults']['error'], [
40✔
835
                'message' => $exception->getMessage(),
40✔
836
                'type' => $exception::class,
40✔
837
                'error_place' => $this->getErrorPlace($exception),
40✔
838
            ]);
40✔
839
        }
840

841
        $additionalDocs = config('auto-doc.additional_paths', []);
6✔
842

843
        foreach ($additionalDocs as $filePath) {
6✔
844
            try {
845
                $additionalDocContent = $this->getOpenAPIFileContent(base_path($filePath));
4✔
846
            } catch (DocFileNotExistsException|EmptyDocFileException|InvalidSwaggerSpecException $exception) {
3✔
847
                report($exception);
3✔
848

849
                continue;
3✔
850
            }
851

852
            $this->mergeOpenAPIDocs($documentation, $additionalDocContent);
1✔
853
        }
854

855
        return $documentation;
6✔
856
    }
857

858
    protected function getErrorPlace(Throwable $exception): string
859
    {
860
        $firstTraceEntry = Arr::first($exception->getTrace());
40✔
861

862
        Arr::forget($firstTraceEntry, 'type');
40✔
863

864
        $formattedTraceEntry = Arr::map(
40✔
865
            array: $firstTraceEntry,
40✔
866
            callback: fn ($value, $key) => $key . '=' . (is_array($value) ? json_encode($value) : $value),
40✔
867
        );
40✔
868

869
        return implode(PHP_EOL, $formattedTraceEntry);
40✔
870
    }
871

872
    protected function camelCaseToUnderScore($input): string
873
    {
874
        preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $input, $matches);
27✔
875
        $ret = $matches[0];
27✔
876

877
        foreach ($ret as &$match) {
27✔
878
            $match = ($match === strtoupper($match)) ? strtolower($match) : lcfirst($match);
27✔
879
        }
880

881
        return implode('_', $ret);
27✔
882
    }
883

884
    protected function generateExample($properties): array
885
    {
886
        $parameters = $this->replaceObjectValues($this->request->all());
6✔
887
        $example = [];
6✔
888

889
        $this->replaceNullValues($parameters, $properties, $example);
6✔
890

891
        return $example;
6✔
892
    }
893

894
    protected function replaceObjectValues($parameters): array
895
    {
896
        $classNamesValues = [
6✔
897
            File::class => '[uploaded_file]',
6✔
898
        ];
6✔
899

900
        $parameters = Arr::dot($parameters);
6✔
901
        $returnParameters = [];
6✔
902

903
        foreach ($parameters as $parameter => $value) {
6✔
904
            if (is_object($value)) {
6✔
905
                $class = get_class($value);
1✔
906

907
                $value = Arr::get($classNamesValues, $class, $class);
1✔
908
            }
909

910
            Arr::set($returnParameters, $parameter, $value);
6✔
911
        }
912

913
        return $returnParameters;
6✔
914
    }
915

916
    protected function getClassAnnotations($class): array
917
    {
918
        $reflection = new ReflectionClass($class);
28✔
919

920
        $annotations = $reflection->getDocComment();
28✔
921

922
        $annotations = Str::of($annotations)->remove("\r");
28✔
923

924
        $blocks = explode("\n", $annotations);
28✔
925

926
        $result = [];
28✔
927

928
        foreach ($blocks as $block) {
28✔
929
            if (Str::contains($block, '@')) {
28✔
930
                $index = strpos($block, '@');
1✔
931
                $block = substr($block, $index);
1✔
932
                $exploded = explode(' ', $block);
1✔
933

934
                $paramName = str_replace('@', '', array_shift($exploded));
1✔
935
                $paramValue = implode(' ', $exploded);
1✔
936

937
                if (in_array($paramName, $this->booleanAnnotations)) {
1✔
938
                    $paramValue = true;
1✔
939
                }
940

941
                $result[$paramName] = $paramValue;
1✔
942
            }
943
        }
944

945
        return $result;
28✔
946
    }
947

948
    /**
949
     * NOTE: All functions below are temporary solution for
950
     * this issue: https://github.com/OAI/OpenAPI-Specification/issues/229
951
     * We hope swagger developers will resolve this problem in next release of Swagger OpenAPI
952
     * */
953
    protected function replaceNullValues($parameters, $types, &$example)
954
    {
955
        foreach ($parameters as $parameter => $value) {
6✔
956
            if (is_null($value) && array_key_exists($parameter, $types)) {
6✔
957
                $example[$parameter] = $this->getDefaultValueByType($types[$parameter]['type']);
5✔
958
            } elseif (is_array($value)) {
6✔
959
                $this->replaceNullValues($value, $types, $example[$parameter]);
3✔
960
            } else {
961
                $example[$parameter] = $value;
6✔
962
            }
963
        }
964
    }
965

966
    protected function getDefaultValueByType($type)
967
    {
968
        $values = [
5✔
969
            'object' => 'null',
5✔
970
            'boolean' => false,
5✔
971
            'date' => '0000-00-00',
5✔
972
            'integer' => 0,
5✔
973
            'string' => '',
5✔
974
            'double' => 0,
5✔
975
        ];
5✔
976

977
        return $values[$type];
5✔
978
    }
979

980
    protected function prepareInfo(?string $view = null, array $viewData = [], array $license = []): array
981
    {
982
        $info = [];
63✔
983

984
        $license = array_filter($license);
63✔
985

986
        if (!empty($license)) {
63✔
UNCOV
987
            $info['license'] = $license;
×
988
        }
989

990
        if (!empty($view)) {
63✔
991
            $info['description'] = view($view, $viewData)->render();
62✔
992
        }
993

994
        return array_merge($this->config['info'], $info);
63✔
995
    }
996

997
    protected function getOpenAPIFileContent(string $filePath): array
998
    {
999
        if (!file_exists($filePath)) {
4✔
1000
            throw new DocFileNotExistsException($filePath);
1✔
1001
        }
1002

1003
        $fileContent = json_decode(file_get_contents($filePath), true);
3✔
1004

1005
        if (empty($fileContent)) {
3✔
1006
            throw new EmptyDocFileException($filePath);
1✔
1007
        }
1008

1009
        $this->openAPIValidator->validate($fileContent);
2✔
1010

1011
        return $fileContent;
1✔
1012
    }
1013

1014
    protected function mergeOpenAPIDocs(array &$documentation, array $additionalDocumentation): void
1015
    {
1016
        $paths = array_keys($additionalDocumentation['paths']);
3✔
1017

1018
        foreach ($paths as $path) {
3✔
1019
            $additionalDocPath = $additionalDocumentation['paths'][$path];
3✔
1020

1021
            if (empty($documentation['paths'][$path])) {
3✔
1022
                $documentation['paths'][$path] = $additionalDocPath;
3✔
1023
            } else {
1024
                $methods = array_keys($documentation['paths'][$path]);
1✔
1025
                $additionalDocMethods = array_keys($additionalDocPath);
1✔
1026

1027
                foreach ($additionalDocMethods as $method) {
1✔
1028
                    if (!in_array($method, $methods)) {
1✔
1029
                        $documentation['paths'][$path][$method] = $additionalDocPath[$method];
1✔
1030
                    }
1031
                }
1032
            }
1033
        }
1034

1035
        foreach (Arr::get($additionalDocumentation, 'components.schemas', []) as $definitionName => $definitionData) {
3✔
1036
            if (empty($documentation['components']['schemas'][$definitionName])) {
3✔
1037
                $documentation['components']['schemas'][$definitionName] = $definitionData;
3✔
1038
            }
1039
        }
1040
    }
1041
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc