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

RonasIT / laravel-swagger / 25806213366

13 May 2026 02:39PM UTC coverage: 99.669% (+0.01%) from 99.656%
25806213366

Pull #198

github

web-flow
Merge c9149bcaa into a9abd440c
Pull Request #198: feat: expand with[] and with_count[] into separate query params per relation

63 of 63 new or added lines in 4 files covered. (100.0%)

1 existing line in 1 file now uncovered.

903 of 906 relevant lines covered (99.67%)

22.1 hits per line

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

99.8
/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\Contracts\SwaggerDriverContract;
14
use RonasIT\AutoDoc\Exceptions\DocFileNotExistsException;
15
use RonasIT\AutoDoc\Exceptions\EmptyContactEmailException;
16
use RonasIT\AutoDoc\Exceptions\EmptyDocFileException;
17
use RonasIT\AutoDoc\Exceptions\InvalidDriverClassException;
18
use RonasIT\AutoDoc\Exceptions\LegacyConfigException;
19
use RonasIT\AutoDoc\Exceptions\SpecValidation\InvalidSwaggerSpecException;
20
use RonasIT\AutoDoc\Exceptions\SwaggerDriverClassNotFoundException;
21
use RonasIT\AutoDoc\Exceptions\UnsupportedDocumentationViewerException;
22
use RonasIT\AutoDoc\Exceptions\WrongSecurityConfigException;
23
use RonasIT\AutoDoc\Traits\GetDependenciesTrait;
24
use RonasIT\AutoDoc\Validators\SwaggerSpecValidator;
25
use Symfony\Component\HttpFoundation\Response;
26
use Throwable;
27

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

35
    public const string OPEN_API_VERSION = '3.1.0';
36

37
    protected $driver;
38
    protected $openAPIValidator;
39

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

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

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

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

71
        $this->initConfig();
104✔
72

73
        $this->setDriver();
99✔
74

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

80
            $this->container = $container;
96✔
81

82
            $this->security = $this->config['security'];
96✔
83

84
            $this->data = $this->driver->getProcessTmpData();
96✔
85

86
            if (empty($this->data)) {
96✔
87
                $this->data = $this->generateEmptyData();
64✔
88

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

157
        $securityDefinitions = $this->generateSecurityDefinition();
65✔
158

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

163
        return $data;
65✔
164
    }
165

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

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

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

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

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

197
        $this->prepareItem();
28✔
198

199
        $this->parseRequest();
28✔
200
        $this->parseResponse($response);
28✔
201

202
        $this->driver->saveProcessTmpData($this->data);
28✔
203
    }
204

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

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

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

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

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

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

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

240
        $params = Arr::collapse($params);
27✔
241

242
        $result = [];
27✔
243

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

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

258
        return $result;
27✔
259
    }
260

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

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

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

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

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

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

286
        $concreteRequest = $this->getConcreteRequest();
28✔
287

288
        if (empty($concreteRequest)) {
28✔
289
            $this->item['description'] = '';
3✔
290

291
            return;
3✔
292
        }
293

294
        $annotations = $this->getClassAnnotations($concreteRequest);
25✔
295

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

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

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

311
        if (!empty($content) && array_is_list($content)) {
28✔
312
            $this->saveListResponseDefinitions($content, $schemaProperties);
17✔
313

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

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

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

329
        foreach ($content as $value) {
17✔
330
            $type = gettype($value);
17✔
331

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

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

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

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

352
            $schemaProperties[$name] = $property;
10✔
353
        }
354
    }
355

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

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

362
        if (is_null($produce)) {
28✔
363
            $produce = 'text/plain';
1✔
364
        }
365

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

370
        $responses = $this->item['responses'];
28✔
371

372
        $responseExampleLimitCount = config('auto-doc.response_example_limit_count');
28✔
373

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

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

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

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

391
        $code = $response->getStatusCode();
28✔
392

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

401
        $action = Str::ucfirst($this->getActionName($this->uri));
28✔
402
        $definition = "{$this->method}{$action}{$code}ResponseObject";
28✔
403

404
        $this->saveResponseSchema($content, $definition);
28✔
405

406
        if (is_array($this->item['responses'][$code])) {
28✔
407
            $this->item['responses'][$code]['content'][$produce]['schema']['$ref'] = "#/components/schemas/{$definition}";
27✔
408
        }
409
    }
410

411
    protected function saveExample($code, $content, $produce)
412
    {
413
        $description = $this->getResponseDescription($code);
28✔
414
        $availableContentTypes = [
28✔
415
            'application',
28✔
416
            'text',
28✔
417
            'image',
28✔
418
        ];
28✔
419
        $explodedContentType = explode('/', $produce);
28✔
420

421
        if (in_array($explodedContentType[0], $availableContentTypes)) {
28✔
422
            $this->item['responses'][$code] = $this->makeResponseExample($content, $produce, $description);
27✔
423
        } else {
424
            $this->item['responses'][$code] = '*Unavailable for preview*';
1✔
425
        }
426
    }
427

428
    protected function makeResponseExample($content, $mimeType, $description = ''): array
429
    {
430
        $example = match ($mimeType) {
27✔
431
            'application/json' => json_decode($content, true),
24✔
432
            'application/pdf' => base64_encode($content),
1✔
433
            default => $content,
2✔
434
        };
435

436
        return [
27✔
437
            'description' => $description,
27✔
438
            'content' => [
27✔
439
                $mimeType => [
27✔
440
                    'schema' => [
27✔
441
                        'type' => 'object',
27✔
442
                    ],
27✔
443
                    'example' => $example,
27✔
444
                ],
27✔
445
            ],
27✔
446
        ];
27✔
447
    }
448

449
    protected function saveParameters($request, array $annotations)
450
    {
451
        $formRequest = new $request();
25✔
452
        $formRequest->setUserResolver($this->request->getUserResolver());
25✔
453
        $formRequest->setRouteResolver($this->request->getRouteResolver());
25✔
454
        $rules = method_exists($formRequest, 'rules') ? $this->prepareRules($formRequest->rules()) : [];
25✔
455
        $attributes = method_exists($formRequest, 'attributes') ? $formRequest->attributes() : [];
25✔
456

457
        $actionName = $this->getActionName($this->uri);
25✔
458

459
        if (in_array($this->method, ['get', 'delete'])) {
25✔
460
            $this->saveGetRequestParameters($rules, $attributes, $annotations);
19✔
461
        } else {
462
            $this->savePostRequestParameters($actionName, $rules, $attributes, $annotations);
6✔
463
        }
464
    }
465

466
    protected function prepareRules(array $rules): array
467
    {
468
        $preparedRules = [];
24✔
469

470
        foreach ($rules as $field => $rulesField) {
24✔
471
            if (is_array($rulesField)) {
24✔
472
                $rulesField = array_map(function ($rule) {
21✔
473
                    return $this->getRuleAsString($rule);
21✔
474
                }, $rulesField);
21✔
475

476
                $preparedRules[$field] = implode('|', $rulesField);
21✔
477
            } else {
478
                $preparedRules[$field] = $this->getRuleAsString($rulesField);
24✔
479
            }
480
        }
481

482
        return $preparedRules;
24✔
483
    }
484

485
    protected function getRuleAsString($rule): string
486
    {
487
        if (is_object($rule)) {
24✔
488
            if (method_exists($rule, '__toString')) {
21✔
489
                return $rule->__toString();
21✔
490
            }
491

492
            $shortName = Str::afterLast(get_class($rule), '\\');
21✔
493

494
            $ruleName = preg_replace('/Rule$/', '', $shortName);
21✔
495

496
            return Str::snake($ruleName);
21✔
497
        }
498

499
        return $rule;
24✔
500
    }
501

502
    protected function saveGetRequestParameters($rules, array $attributes, array $annotations)
503
    {
504
        foreach ($rules as $parameter => $rule) {
19✔
505
            if (Arr::exists($rules, "{$parameter}.*")) {
18✔
506
                continue;
1✔
507
            }
508

509
            $validation = explode('|', $rule);
18✔
510

511
            if ($this->isArrayItemParameter($parameter, $validation)) {
18✔
512
                $this->saveRelationParameters(Str::remove('.*', $parameter), $validation, $attributes, $annotations);
1✔
513

514
                continue;
1✔
515
            }
516

517
            $this->saveQueryParameter($parameter, $validation, $attributes, $annotations);
18✔
518
        }
519
    }
520

521
    protected function isArrayItemParameter(string $parameter, array $validation): bool
522
    {
523
        if (!Str::endsWith($parameter, '.*')) {
18✔
524
            return false;
18✔
525
        }
526

527
        return collect($validation)->contains(fn ($rule) => Str::startsWith($rule, 'in:'));
1✔
528
    }
529

530
    protected function saveRelationParameters(string $parameter, array $validation, array $attributes, array $annotations): void
531
    {
532
        $inRule = collect($validation)->first(fn ($rule) => Str::startsWith($rule, 'in:'));
1✔
533

534
        $availableValues = $inRule ? array_filter(explode(',', Str::after($inRule, 'in:'))) : [];
1✔
535

536
        $validationWithoutRequired = array_values(array_filter($validation, fn ($rule) => $rule !== 'required'));
1✔
537

538
        foreach ($availableValues as $value) {
1✔
539
            $this->saveQueryParameter("{$parameter}[]", $validationWithoutRequired, $attributes, $annotations, $value);
1✔
540
        }
541
    }
542

543
    protected function saveQueryParameter(string $parameter, array $validation, array $attributes, array $annotations, ?string $example = null): void
544
    {
545
        $existedParameter = Arr::first(
18✔
546
            $this->item['parameters'],
18✔
547
            fn ($existedParameter) => $existedParameter['name'] === $parameter && Arr::get($existedParameter, 'example') === $example,
18✔
548
        );
18✔
549

550
        if (!empty($existedParameter)) {
18✔
551
            return;
1✔
552
        }
553

554
        $description = $this->generateDescription($parameter, $validation, $attributes, $annotations);
17✔
555

556
        $parameterDefinition = [
17✔
557
            'in' => 'query',
17✔
558
            'name' => $parameter,
17✔
559
            'description' => $description,
17✔
560
            'schema' => [
17✔
561
                'type' => $this->getParameterType($validation),
17✔
562
            ],
17✔
563
        ];
17✔
564

565
        if (in_array('required', $validation)) {
17✔
566
            $parameterDefinition['required'] = true;
17✔
567
        }
568

569
        if ($example !== null) {
17✔
570
            $parameterDefinition['example'] = $example;
1✔
571
        }
572

573
        $this->item['parameters'][] = $parameterDefinition;
17✔
574
    }
575

576
    protected function savePostRequestParameters($actionName, $rules, array $attributes, array $annotations)
577
    {
578
        if ($this->requestHasMoreProperties($actionName)) {
6✔
579
            if ($this->requestHasBody()) {
6✔
580
                $type = $this->request->header('Content-Type', 'application/json');
6✔
581

582
                $this->item['requestBody'] = [
6✔
583
                    'content' => [
6✔
584
                        $type => [
6✔
585
                            'schema' => [
6✔
586
                                '$ref' => "#/components/schemas/{$actionName}Object",
6✔
587
                            ],
6✔
588
                        ],
6✔
589
                    ],
6✔
590
                    'description' => '',
6✔
591
                    'required' => true,
6✔
592
                ];
6✔
593
            }
594

595
            $this->saveDefinitions($actionName, $rules, $attributes, $annotations);
6✔
596
        }
597
    }
598

599
    protected function saveDefinitions($objectName, $rules, $attributes, array $annotations)
600
    {
601
        $data = [
6✔
602
            'type' => 'object',
6✔
603
            'properties' => [],
6✔
604
        ];
6✔
605

606
        foreach ($rules as $parameter => $rule) {
6✔
607
            $rulesArray = (is_array($rule)) ? $rule : explode('|', $rule);
6✔
608
            $parameterType = $this->getParameterType($rulesArray);
6✔
609
            $this->saveParameterType($data, $parameter, $parameterType);
6✔
610

611
            $uselessRules = $this->ruleToTypeMap;
6✔
612
            $uselessRules['required'] = 'required';
6✔
613

614
            if (in_array('required', $rulesArray)) {
6✔
615
                $data['required'][] = $parameter;
6✔
616
            }
617

618
            $rulesArray = array_flip(array_diff_key(array_flip($rulesArray), $uselessRules));
6✔
619

620
            $data['properties'][$parameter]['description'] = $this->generateDescription($parameter, $rulesArray, $attributes, $annotations);
6✔
621
        }
622

623
        $data['example'] = $this->generateExample($data['properties']);
6✔
624
        $this->data['components']['schemas']["{$objectName}Object"] = $data;
6✔
625
    }
626

627
    protected function getParameterType(array $validation): string
628
    {
629
        $validationRules = $this->ruleToTypeMap;
23✔
630
        $validationRules['email'] = 'string';
23✔
631

632
        $parameterType = 'string';
23✔
633

634
        foreach ($validation as $item) {
23✔
635
            if (in_array($item, array_keys($validationRules))) {
23✔
636
                return $validationRules[$item];
22✔
637
            }
638
        }
639

640
        return $parameterType;
21✔
641
    }
642

643
    protected function saveParameterType(&$data, $parameter, $parameterType)
644
    {
645
        $data['properties'][$parameter] = [
6✔
646
            'type' => $parameterType,
6✔
647
        ];
6✔
648
    }
649

650
    protected function generateDescription(string $parameter, array $validation, array $attributes, array $annotations): string
651
    {
652
        $description = Arr::get($annotations, $parameter);
23✔
653

654
        if (empty($description)) {
23✔
655
            $description = Arr::get($attributes, $parameter, implode(', ', $validation));
23✔
656
        }
657

658
        return $description;
23✔
659
    }
660

661
    protected function requestHasMoreProperties($actionName): bool
662
    {
663
        $requestParametersCount = count($this->request->all());
6✔
664

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

668
        return $requestParametersCount > $objectParametersCount;
6✔
669
    }
670

671
    protected function requestHasBody(): bool
672
    {
673
        $parameters = $this->data['paths'][$this->uri][$this->method]['parameters'];
6✔
674

675
        $bodyParamExisted = Arr::where($parameters, function ($value) {
6✔
676
            return $value['name'] === 'body';
1✔
677
        });
6✔
678

679
        return empty($bodyParamExisted);
6✔
680
    }
681

682
    public function getConcreteRequest()
683
    {
684
        $controller = $this->request->route()->getActionName();
28✔
685

686
        if ($controller === 'Closure') {
28✔
687
            return null;
1✔
688
        }
689

690
        $explodedController = explode('@', $controller);
27✔
691

692
        $class = $explodedController[0];
27✔
693
        $method = Arr::get($explodedController, 1, '__invoke');
27✔
694

695
        if (!method_exists($class, $method)) {
27✔
696
            return null;
1✔
697
        }
698

699
        $parameters = $this->resolveClassMethodDependencies(
26✔
700
            app($class),
26✔
701
            $method,
26✔
702
        );
26✔
703

704
        return Arr::first($parameters, function ($key) {
26✔
705
            return preg_match('/Request/', $key);
26✔
706
        });
26✔
707
    }
708

709
    public function saveConsume()
710
    {
711
        $consumeList = $this->data['paths'][$this->uri][$this->method]['consumes'];
28✔
712
        $consume = $this->request->header('Content-Type');
28✔
713

714
        if (!empty($consume) && !in_array($consume, $consumeList)) {
28✔
715
            $this->item['consumes'][] = $consume;
17✔
716
        }
717
    }
718

719
    public function saveTags()
720
    {
721
        $globalPrefix = config('auto-doc.global_prefix');
28✔
722
        $globalPrefix = Str::after($globalPrefix, '/');
28✔
723

724
        $explodedUri = explode('/', $this->uri);
28✔
725
        $explodedUri = array_filter($explodedUri);
28✔
726

727
        $tag = array_shift($explodedUri);
28✔
728

729
        if ($globalPrefix === $tag) {
28✔
730
            $tag = array_shift($explodedUri);
2✔
731
        }
732

733
        $this->item['tags'] = [$tag];
28✔
734
    }
735

736
    public function saveDescription($request, array $annotations)
737
    {
738
        $this->item['summary'] = $this->getSummary($request, $annotations);
25✔
739

740
        $description = Arr::get($annotations, 'description');
25✔
741

742
        if (!empty($description)) {
25✔
743
            $this->item['description'] = $description;
1✔
744
        }
745
    }
746

747
    protected function saveSecurity()
748
    {
749
        if ($this->requestSupportAuth()) {
28✔
750
            $this->addSecurityToOperation();
5✔
751
        }
752
    }
753

754
    protected function addSecurityToOperation()
755
    {
756
        $security = &$this->data['paths'][$this->uri][$this->method]['security'];
5✔
757

758
        if (empty($security)) {
5✔
759
            $security[] = [
5✔
760
                "{$this->security}" => [],
5✔
761
            ];
5✔
762
        }
763
    }
764

765
    protected function getSummary($request, array $annotations)
766
    {
767
        $summary = Arr::get($annotations, 'summary');
25✔
768

769
        if (empty($summary)) {
25✔
770
            $summary = $this->parseRequestName($request);
24✔
771
        }
772

773
        return $summary;
25✔
774
    }
775

776
    protected function requestSupportAuth(): bool
777
    {
778
        $security = Arr::get($this->config, 'security');
28✔
779
        $securityDriver = Arr::get($this->config, "security_drivers.{$security}");
28✔
780

781
        switch (Arr::get($securityDriver, 'in')) {
28✔
782
            case 'header':
28✔
783
                // TODO Change this logic after migration on Swagger 3.0
784
                // Swagger 2.0 does not support cookie authorization.
785
                $securityToken = $this->request->hasHeader($securityDriver['name'])
7✔
786
                    ? $this->request->header($securityDriver['name'])
5✔
787
                    : $this->request->cookie($securityDriver['name']);
2✔
788

789
                break;
7✔
790
            case 'query':
21✔
791
                $securityToken = $this->request->query($securityDriver['name']);
1✔
792

793
                break;
1✔
794
            default:
795
                $securityToken = null;
20✔
796
        }
797

798
        return !empty($securityToken);
28✔
799
    }
800

801
    protected function parseRequestName($request)
802
    {
803
        $explodedRequest = explode('\\', $request);
24✔
804
        $requestName = array_pop($explodedRequest);
24✔
805
        $summaryName = str_replace('Request', '', $requestName);
24✔
806

807
        $underscoreRequestName = $this->camelCaseToUnderScore($summaryName);
24✔
808

809
        return preg_replace('/[_]/', ' ', $underscoreRequestName);
24✔
810
    }
811

812
    protected function getResponseDescription($code)
813
    {
814
        $defaultDescription = Response::$statusTexts[$code];
28✔
815

816
        $request = $this->getConcreteRequest();
28✔
817

818
        if (empty($request)) {
28✔
819
            return $defaultDescription;
3✔
820
        }
821

822
        $annotations = $this->getClassAnnotations($request);
25✔
823

824
        $localDescription = Arr::get($annotations, "_{$code}");
25✔
825

826
        if (!empty($localDescription)) {
25✔
827
            return $localDescription;
1✔
828
        }
829

830
        return Arr::get($this->config, "defaults.code-descriptions.{$code}", $defaultDescription);
24✔
831
    }
832

833
    protected function getActionName($uri): string
834
    {
835
        $action = preg_replace('[\/]', '', $uri);
28✔
836

837
        return Str::camel($action);
28✔
838
    }
839

840
    public function saveProductionData()
841
    {
842
        if (ParallelTesting::token()) {
4✔
843
            $this->driver->appendProcessDataToTmpFile(function (?array $sharedTmpData) {
2✔
844
                $resultDocContent = (empty($sharedTmpData))
2✔
845
                    ? $this->generateEmptyData($this->config['info']['description'])
1✔
846
                    : $sharedTmpData;
1✔
847

848
                $this->mergeOpenAPIDocs($resultDocContent, $this->data);
2✔
849

850
                return $resultDocContent;
2✔
851
            });
2✔
852
        }
853

854
        $this->driver->saveData();
4✔
855
    }
856

857
    public function getDocFileContent()
858
    {
859
        try {
860
            $documentation = $this->driver->getDocumentation();
48✔
861

862
            $this->openAPIValidator->validate($documentation);
46✔
863
        } catch (Throwable $exception) {
40✔
864
            return $this->generateEmptyData($this->config['defaults']['error'], [
40✔
865
                'message' => $exception->getMessage(),
40✔
866
                'type' => $exception::class,
40✔
867
                'error_place' => $this->getErrorPlace($exception),
40✔
868
            ]);
40✔
869
        }
870

871
        $additionalDocs = config('auto-doc.additional_paths', []);
8✔
872

873
        foreach ($additionalDocs as $filePath) {
8✔
874
            try {
875
                $additionalDocContent = $this->getOpenAPIFileContent(base_path($filePath));
4✔
876
            } catch (DocFileNotExistsException|EmptyDocFileException|InvalidSwaggerSpecException $exception) {
3✔
877
                report($exception);
3✔
878

879
                continue;
3✔
880
            }
881

882
            $this->mergeOpenAPIDocs($documentation, $additionalDocContent);
1✔
883
        }
884

885
        return $documentation;
8✔
886
    }
887

888
    public function getPrettyDocFileContent(): array
889
    {
890
        $documentation = $this->getDocFileContent();
7✔
891

892
        foreach ($documentation['paths'] as $path => $pathItem) {
7✔
893
            foreach ($pathItem as $method => $operation) {
7✔
894
                if (Arr::has($operation, 'parameters')) {
7✔
895
                    $documentation['paths'][$path][$method]['parameters'] = collect($operation['parameters'])
7✔
896
                        ->groupBy('name')
7✔
897
                        ->map(function ($params, $name) {
7✔
898
                            if ($params->count() === 1 || !Str::endsWith($name, '[]')) {
7✔
899
                                return $params->first();
1✔
900
                            }
901

902
                            $base = $params->first();
7✔
903
                            $base['schema']['enum'] = $params->pluck('example')->filter()->values()->all();
7✔
904

905
                            return $base;
7✔
906
                        })
7✔
907
                        ->values()
7✔
908
                        ->all();
7✔
909
                }
910
            }
911
        }
912

913
        return $documentation;
7✔
914
    }
915

916
    protected function getErrorPlace(Throwable $exception): string
917
    {
918
        $firstTraceEntry = Arr::first($exception->getTrace());
40✔
919

920
        Arr::forget($firstTraceEntry, 'type');
40✔
921

922
        $formattedTraceEntry = Arr::map(
40✔
923
            array: $firstTraceEntry,
40✔
924
            callback: fn ($value, $key) => $key . '=' . (is_array($value) ? json_encode($value) : $value),
40✔
925
        );
40✔
926

927
        return implode(PHP_EOL, $formattedTraceEntry);
40✔
928
    }
929

930
    protected function camelCaseToUnderScore($input): string
931
    {
932
        preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $input, $matches);
24✔
933
        $ret = $matches[0];
24✔
934

935
        foreach ($ret as &$match) {
24✔
936
            $match = ($match === strtoupper($match)) ? strtolower($match) : lcfirst($match);
24✔
937
        }
938

939
        return implode('_', $ret);
24✔
940
    }
941

942
    protected function generateExample($properties): array
943
    {
944
        $parameters = $this->replaceObjectValues($this->request->all());
6✔
945
        $example = [];
6✔
946

947
        $this->replaceNullValues($parameters, $properties, $example);
6✔
948

949
        return $example;
6✔
950
    }
951

952
    protected function replaceObjectValues($parameters): array
953
    {
954
        $classNamesValues = [
6✔
955
            File::class => '[uploaded_file]',
6✔
956
        ];
6✔
957

958
        $parameters = Arr::dot($parameters);
6✔
959
        $returnParameters = [];
6✔
960

961
        foreach ($parameters as $parameter => $value) {
6✔
962
            if (is_object($value)) {
6✔
963
                $class = get_class($value);
1✔
964

965
                $value = Arr::get($classNamesValues, $class, $class);
1✔
966
            }
967

968
            Arr::set($returnParameters, $parameter, $value);
6✔
969
        }
970

971
        return $returnParameters;
6✔
972
    }
973

974
    protected function getClassAnnotations($class): array
975
    {
976
        $reflection = new ReflectionClass($class);
25✔
977

978
        $annotations = $reflection->getDocComment();
25✔
979

980
        $annotations = Str::of($annotations)->remove("\r");
25✔
981

982
        $blocks = explode("\n", $annotations);
25✔
983

984
        $result = [];
25✔
985

986
        foreach ($blocks as $block) {
25✔
987
            if (Str::contains($block, '@')) {
25✔
988
                $index = strpos($block, '@');
1✔
989
                $block = substr($block, $index);
1✔
990
                $exploded = explode(' ', $block);
1✔
991

992
                $paramName = str_replace('@', '', array_shift($exploded));
1✔
993
                $paramValue = implode(' ', $exploded);
1✔
994

995
                if (in_array($paramName, $this->booleanAnnotations)) {
1✔
996
                    $paramValue = true;
1✔
997
                }
998

999
                $result[$paramName] = $paramValue;
1✔
1000
            }
1001
        }
1002

1003
        return $result;
25✔
1004
    }
1005

1006
    /**
1007
     * NOTE: All functions below are temporary solution for
1008
     * this issue: https://github.com/OAI/OpenAPI-Specification/issues/229
1009
     * We hope swagger developers will resolve this problem in next release of Swagger OpenAPI
1010
     * */
1011
    protected function replaceNullValues($parameters, $types, &$example)
1012
    {
1013
        foreach ($parameters as $parameter => $value) {
6✔
1014
            if (is_null($value) && Arr::exists($types, $parameter)) {
6✔
1015
                $example[$parameter] = $this->getDefaultValueByType($types[$parameter]['type']);
5✔
1016
            } elseif (is_array($value)) {
6✔
1017
                $this->replaceNullValues($value, $types, $example[$parameter]);
3✔
1018
            } else {
1019
                $example[$parameter] = $value;
6✔
1020
            }
1021
        }
1022
    }
1023

1024
    protected function getDefaultValueByType($type)
1025
    {
1026
        $values = [
5✔
1027
            'object' => 'null',
5✔
1028
            'boolean' => false,
5✔
1029
            'date' => '0000-00-00',
5✔
1030
            'integer' => 0,
5✔
1031
            'string' => '',
5✔
1032
            'double' => 0,
5✔
1033
        ];
5✔
1034

1035
        return $values[$type];
5✔
1036
    }
1037

1038
    protected function prepareInfo(?string $view = null, array $viewData = [], array $license = []): array
1039
    {
1040
        $info = [];
65✔
1041

1042
        $license = array_filter($license);
65✔
1043

1044
        if (!empty($license)) {
65✔
UNCOV
1045
            $info['license'] = $license;
×
1046
        }
1047

1048
        if (!empty($view)) {
65✔
1049
            $info['description'] = view($view, $viewData)->render();
64✔
1050
        }
1051

1052
        return array_merge($this->config['info'], $info);
65✔
1053
    }
1054

1055
    protected function getOpenAPIFileContent(string $filePath): array
1056
    {
1057
        if (!file_exists($filePath)) {
4✔
1058
            throw new DocFileNotExistsException($filePath);
1✔
1059
        }
1060

1061
        $fileContent = json_decode(file_get_contents($filePath), true);
3✔
1062

1063
        if (empty($fileContent)) {
3✔
1064
            throw new EmptyDocFileException($filePath);
1✔
1065
        }
1066

1067
        $this->openAPIValidator->validate($fileContent);
2✔
1068

1069
        return $fileContent;
1✔
1070
    }
1071

1072
    protected function mergeOpenAPIDocs(array &$documentation, array $additionalDocumentation): void
1073
    {
1074
        $paths = array_keys($additionalDocumentation['paths']);
3✔
1075

1076
        foreach ($paths as $path) {
3✔
1077
            $additionalDocPath = $additionalDocumentation['paths'][$path];
3✔
1078

1079
            if (empty($documentation['paths'][$path])) {
3✔
1080
                $documentation['paths'][$path] = $additionalDocPath;
3✔
1081
            } else {
1082
                $methods = array_keys($documentation['paths'][$path]);
1✔
1083
                $additionalDocMethods = array_keys($additionalDocPath);
1✔
1084

1085
                foreach ($additionalDocMethods as $method) {
1✔
1086
                    if (!in_array($method, $methods)) {
1✔
1087
                        $documentation['paths'][$path][$method] = $additionalDocPath[$method];
1✔
1088
                    }
1089
                }
1090
            }
1091
        }
1092

1093
        foreach (Arr::get($additionalDocumentation, 'components.schemas', []) as $definitionName => $definitionData) {
3✔
1094
            if (empty($documentation['components']['schemas'][$definitionName])) {
3✔
1095
                $documentation['components']['schemas'][$definitionName] = $definitionData;
3✔
1096
            }
1097
        }
1098
    }
1099
}
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