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

RonasIT / laravel-swagger / 25799657184

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

Pull #198

github

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

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

1 existing line in 1 file now uncovered.

904 of 907 relevant lines covered (99.67%)

21.86 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($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 = Arr::get($annotations, $parameter)
17✔
555
            ?: Arr::get($attributes, $parameter, implode(', ', $validation));
17✔
556

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

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

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

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

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

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

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

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

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

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

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

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

621
            $this->saveParameterDescription($data, $parameter, $rulesArray, $attributes, $annotations);
6✔
622
        }
623

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

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

633
        $parameterType = 'string';
23✔
634

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

641
        return $parameterType;
21✔
642
    }
643

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

651
    protected function saveParameterDescription(
652
        array &$data,
653
        string $parameter,
654
        array $rulesArray,
655
        array $attributes,
656
        array $annotations,
657
    ) {
658
        $description = Arr::get($annotations, $parameter);
6✔
659

660
        if (empty($description)) {
6✔
661
            $description = Arr::get($attributes, $parameter, implode(', ', $rulesArray));
6✔
662
        }
663

664
        $data['properties'][$parameter]['description'] = $description;
6✔
665
    }
666

667
    protected function requestHasMoreProperties($actionName): bool
668
    {
669
        $requestParametersCount = count($this->request->all());
6✔
670

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

674
        return $requestParametersCount > $objectParametersCount;
6✔
675
    }
676

677
    protected function requestHasBody(): bool
678
    {
679
        $parameters = $this->data['paths'][$this->uri][$this->method]['parameters'];
6✔
680

681
        $bodyParamExisted = Arr::where($parameters, function ($value) {
6✔
682
            return $value['name'] === 'body';
1✔
683
        });
6✔
684

685
        return empty($bodyParamExisted);
6✔
686
    }
687

688
    public function getConcreteRequest()
689
    {
690
        $controller = $this->request->route()->getActionName();
28✔
691

692
        if ($controller === 'Closure') {
28✔
693
            return null;
1✔
694
        }
695

696
        $explodedController = explode('@', $controller);
27✔
697

698
        $class = $explodedController[0];
27✔
699
        $method = Arr::get($explodedController, 1, '__invoke');
27✔
700

701
        if (!method_exists($class, $method)) {
27✔
702
            return null;
1✔
703
        }
704

705
        $parameters = $this->resolveClassMethodDependencies(
26✔
706
            app($class),
26✔
707
            $method,
26✔
708
        );
26✔
709

710
        return Arr::first($parameters, function ($key) {
26✔
711
            return preg_match('/Request/', $key);
26✔
712
        });
26✔
713
    }
714

715
    public function saveConsume()
716
    {
717
        $consumeList = $this->data['paths'][$this->uri][$this->method]['consumes'];
28✔
718
        $consume = $this->request->header('Content-Type');
28✔
719

720
        if (!empty($consume) && !in_array($consume, $consumeList)) {
28✔
721
            $this->item['consumes'][] = $consume;
17✔
722
        }
723
    }
724

725
    public function saveTags()
726
    {
727
        $globalPrefix = config('auto-doc.global_prefix');
28✔
728
        $globalPrefix = Str::after($globalPrefix, '/');
28✔
729

730
        $explodedUri = explode('/', $this->uri);
28✔
731
        $explodedUri = array_filter($explodedUri);
28✔
732

733
        $tag = array_shift($explodedUri);
28✔
734

735
        if ($globalPrefix === $tag) {
28✔
736
            $tag = array_shift($explodedUri);
2✔
737
        }
738

739
        $this->item['tags'] = [$tag];
28✔
740
    }
741

742
    public function saveDescription($request, array $annotations)
743
    {
744
        $this->item['summary'] = $this->getSummary($request, $annotations);
25✔
745

746
        $description = Arr::get($annotations, 'description');
25✔
747

748
        if (!empty($description)) {
25✔
749
            $this->item['description'] = $description;
1✔
750
        }
751
    }
752

753
    protected function saveSecurity()
754
    {
755
        if ($this->requestSupportAuth()) {
28✔
756
            $this->addSecurityToOperation();
5✔
757
        }
758
    }
759

760
    protected function addSecurityToOperation()
761
    {
762
        $security = &$this->data['paths'][$this->uri][$this->method]['security'];
5✔
763

764
        if (empty($security)) {
5✔
765
            $security[] = [
5✔
766
                "{$this->security}" => [],
5✔
767
            ];
5✔
768
        }
769
    }
770

771
    protected function getSummary($request, array $annotations)
772
    {
773
        $summary = Arr::get($annotations, 'summary');
25✔
774

775
        if (empty($summary)) {
25✔
776
            $summary = $this->parseRequestName($request);
24✔
777
        }
778

779
        return $summary;
25✔
780
    }
781

782
    protected function requestSupportAuth(): bool
783
    {
784
        $security = Arr::get($this->config, 'security');
28✔
785
        $securityDriver = Arr::get($this->config, "security_drivers.{$security}");
28✔
786

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

795
                break;
7✔
796
            case 'query':
21✔
797
                $securityToken = $this->request->query($securityDriver['name']);
1✔
798

799
                break;
1✔
800
            default:
801
                $securityToken = null;
20✔
802
        }
803

804
        return !empty($securityToken);
28✔
805
    }
806

807
    protected function parseRequestName($request)
808
    {
809
        $explodedRequest = explode('\\', $request);
24✔
810
        $requestName = array_pop($explodedRequest);
24✔
811
        $summaryName = str_replace('Request', '', $requestName);
24✔
812

813
        $underscoreRequestName = $this->camelCaseToUnderScore($summaryName);
24✔
814

815
        return preg_replace('/[_]/', ' ', $underscoreRequestName);
24✔
816
    }
817

818
    protected function getResponseDescription($code)
819
    {
820
        $defaultDescription = Response::$statusTexts[$code];
28✔
821

822
        $request = $this->getConcreteRequest();
28✔
823

824
        if (empty($request)) {
28✔
825
            return $defaultDescription;
3✔
826
        }
827

828
        $annotations = $this->getClassAnnotations($request);
25✔
829

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

832
        if (!empty($localDescription)) {
25✔
833
            return $localDescription;
1✔
834
        }
835

836
        return Arr::get($this->config, "defaults.code-descriptions.{$code}", $defaultDescription);
24✔
837
    }
838

839
    protected function getActionName($uri): string
840
    {
841
        $action = preg_replace('[\/]', '', $uri);
28✔
842

843
        return Str::camel($action);
28✔
844
    }
845

846
    public function saveProductionData()
847
    {
848
        if (ParallelTesting::token()) {
4✔
849
            $this->driver->appendProcessDataToTmpFile(function (?array $sharedTmpData) {
2✔
850
                $resultDocContent = (empty($sharedTmpData))
2✔
851
                    ? $this->generateEmptyData($this->config['info']['description'])
1✔
852
                    : $sharedTmpData;
1✔
853

854
                $this->mergeOpenAPIDocs($resultDocContent, $this->data);
2✔
855

856
                return $resultDocContent;
2✔
857
            });
2✔
858
        }
859

860
        $this->driver->saveData();
4✔
861
    }
862

863
    public function getDocFileContent()
864
    {
865
        try {
866
            $documentation = $this->driver->getDocumentation();
48✔
867

868
            $this->openAPIValidator->validate($documentation);
46✔
869
        } catch (Throwable $exception) {
40✔
870
            return $this->generateEmptyData($this->config['defaults']['error'], [
40✔
871
                'message' => $exception->getMessage(),
40✔
872
                'type' => $exception::class,
40✔
873
                'error_place' => $this->getErrorPlace($exception),
40✔
874
            ]);
40✔
875
        }
876

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

879
        foreach ($additionalDocs as $filePath) {
8✔
880
            try {
881
                $additionalDocContent = $this->getOpenAPIFileContent(base_path($filePath));
4✔
882
            } catch (DocFileNotExistsException|EmptyDocFileException|InvalidSwaggerSpecException $exception) {
3✔
883
                report($exception);
3✔
884

885
                continue;
3✔
886
            }
887

888
            $this->mergeOpenAPIDocs($documentation, $additionalDocContent);
1✔
889
        }
890

891
        return $documentation;
8✔
892
    }
893

894
    public function getPrettyDocFileContent(): array
895
    {
896
        $documentation = $this->getDocFileContent();
7✔
897

898
        foreach ($documentation['paths'] as $path => $pathItem) {
7✔
899
            foreach ($pathItem as $method => $operation) {
7✔
900
                if (Arr::has($operation, 'parameters')) {
7✔
901
                    $documentation['paths'][$path][$method]['parameters'] = collect($operation['parameters'])
7✔
902
                        ->groupBy('name')
7✔
903
                        ->map(function ($params, $name) {
7✔
904
                            if ($params->count() === 1 || !Str::endsWith($name, '[]')) {
1✔
905
                                return $params->first();
1✔
906
                            }
907

908
                            $base = $params->first();
1✔
909
                            $base['schema']['enum'] = $params->pluck('example')->filter()->values()->all();
1✔
910

911
                            return $base;
1✔
912
                        })
7✔
913
                        ->values()
7✔
914
                        ->all();
7✔
915
                }
916
            }
917
        }
918

919
        return $documentation;
7✔
920
    }
921

922
    protected function getErrorPlace(Throwable $exception): string
923
    {
924
        $firstTraceEntry = Arr::first($exception->getTrace());
40✔
925

926
        Arr::forget($firstTraceEntry, 'type');
40✔
927

928
        $formattedTraceEntry = Arr::map(
40✔
929
            array: $firstTraceEntry,
40✔
930
            callback: fn ($value, $key) => $key . '=' . (is_array($value) ? json_encode($value) : $value),
40✔
931
        );
40✔
932

933
        return implode(PHP_EOL, $formattedTraceEntry);
40✔
934
    }
935

936
    protected function camelCaseToUnderScore($input): string
937
    {
938
        preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $input, $matches);
24✔
939
        $ret = $matches[0];
24✔
940

941
        foreach ($ret as &$match) {
24✔
942
            $match = ($match === strtoupper($match)) ? strtolower($match) : lcfirst($match);
24✔
943
        }
944

945
        return implode('_', $ret);
24✔
946
    }
947

948
    protected function generateExample($properties): array
949
    {
950
        $parameters = $this->replaceObjectValues($this->request->all());
6✔
951
        $example = [];
6✔
952

953
        $this->replaceNullValues($parameters, $properties, $example);
6✔
954

955
        return $example;
6✔
956
    }
957

958
    protected function replaceObjectValues($parameters): array
959
    {
960
        $classNamesValues = [
6✔
961
            File::class => '[uploaded_file]',
6✔
962
        ];
6✔
963

964
        $parameters = Arr::dot($parameters);
6✔
965
        $returnParameters = [];
6✔
966

967
        foreach ($parameters as $parameter => $value) {
6✔
968
            if (is_object($value)) {
6✔
969
                $class = get_class($value);
1✔
970

971
                $value = Arr::get($classNamesValues, $class, $class);
1✔
972
            }
973

974
            Arr::set($returnParameters, $parameter, $value);
6✔
975
        }
976

977
        return $returnParameters;
6✔
978
    }
979

980
    protected function getClassAnnotations($class): array
981
    {
982
        $reflection = new ReflectionClass($class);
25✔
983

984
        $annotations = $reflection->getDocComment();
25✔
985

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

988
        $blocks = explode("\n", $annotations);
25✔
989

990
        $result = [];
25✔
991

992
        foreach ($blocks as $block) {
25✔
993
            if (Str::contains($block, '@')) {
25✔
994
                $index = strpos($block, '@');
1✔
995
                $block = substr($block, $index);
1✔
996
                $exploded = explode(' ', $block);
1✔
997

998
                $paramName = str_replace('@', '', array_shift($exploded));
1✔
999
                $paramValue = implode(' ', $exploded);
1✔
1000

1001
                if (in_array($paramName, $this->booleanAnnotations)) {
1✔
1002
                    $paramValue = true;
1✔
1003
                }
1004

1005
                $result[$paramName] = $paramValue;
1✔
1006
            }
1007
        }
1008

1009
        return $result;
25✔
1010
    }
1011

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

1030
    protected function getDefaultValueByType($type)
1031
    {
1032
        $values = [
5✔
1033
            'object' => 'null',
5✔
1034
            'boolean' => false,
5✔
1035
            'date' => '0000-00-00',
5✔
1036
            'integer' => 0,
5✔
1037
            'string' => '',
5✔
1038
            'double' => 0,
5✔
1039
        ];
5✔
1040

1041
        return $values[$type];
5✔
1042
    }
1043

1044
    protected function prepareInfo(?string $view = null, array $viewData = [], array $license = []): array
1045
    {
1046
        $info = [];
65✔
1047

1048
        $license = array_filter($license);
65✔
1049

1050
        if (!empty($license)) {
65✔
UNCOV
1051
            $info['license'] = $license;
×
1052
        }
1053

1054
        if (!empty($view)) {
65✔
1055
            $info['description'] = view($view, $viewData)->render();
64✔
1056
        }
1057

1058
        return array_merge($this->config['info'], $info);
65✔
1059
    }
1060

1061
    protected function getOpenAPIFileContent(string $filePath): array
1062
    {
1063
        if (!file_exists($filePath)) {
4✔
1064
            throw new DocFileNotExistsException($filePath);
1✔
1065
        }
1066

1067
        $fileContent = json_decode(file_get_contents($filePath), true);
3✔
1068

1069
        if (empty($fileContent)) {
3✔
1070
            throw new EmptyDocFileException($filePath);
1✔
1071
        }
1072

1073
        $this->openAPIValidator->validate($fileContent);
2✔
1074

1075
        return $fileContent;
1✔
1076
    }
1077

1078
    protected function mergeOpenAPIDocs(array &$documentation, array $additionalDocumentation): void
1079
    {
1080
        $paths = array_keys($additionalDocumentation['paths']);
3✔
1081

1082
        foreach ($paths as $path) {
3✔
1083
            $additionalDocPath = $additionalDocumentation['paths'][$path];
3✔
1084

1085
            if (empty($documentation['paths'][$path])) {
3✔
1086
                $documentation['paths'][$path] = $additionalDocPath;
3✔
1087
            } else {
1088
                $methods = array_keys($documentation['paths'][$path]);
1✔
1089
                $additionalDocMethods = array_keys($additionalDocPath);
1✔
1090

1091
                foreach ($additionalDocMethods as $method) {
1✔
1092
                    if (!in_array($method, $methods)) {
1✔
1093
                        $documentation['paths'][$path][$method] = $additionalDocPath[$method];
1✔
1094
                    }
1095
                }
1096
            }
1097
        }
1098

1099
        foreach (Arr::get($additionalDocumentation, 'components.schemas', []) as $definitionName => $definitionData) {
3✔
1100
            if (empty($documentation['components']['schemas'][$definitionName])) {
3✔
1101
                $documentation['components']['schemas'][$definitionName] = $definitionData;
3✔
1102
            }
1103
        }
1104
    }
1105
}
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