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

RonasIT / laravel-swagger / 26731510720

01 Jun 2026 02:09AM UTC coverage: 99.672% (+0.02%) from 99.656%
26731510720

Pull #198

github

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

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

1 existing line in 1 file now uncovered.

911 of 914 relevant lines covered (99.67%)

22.21 hits per line

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

99.81
/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\Collection;
10
use Illuminate\Support\Facades\ParallelTesting;
11
use Illuminate\Support\Facades\URL;
12
use Illuminate\Support\Str;
13
use ReflectionClass;
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);
105✔
71

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

135
        if (!$this->driver instanceof SwaggerDriverContract) {
99✔
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'])) {
66✔
143
            $view = $this->config['info']['description'];
64✔
144
        }
145

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

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

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

164
        return $data;
66✔
165
    }
166

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

174
    protected function generateSecurityDefinition(): ?array
175
    {
176
        if (empty($this->security)) {
66✔
177
            return null;
63✔
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;
28✔
197

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

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

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

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

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

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

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

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

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

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

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

243
        $result = [];
27✔
244

245
        foreach ($params as $param) {
27✔
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;
27✔
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();
28✔
284
        $this->saveTags();
28✔
285
        $this->saveSecurity();
28✔
286

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

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

292
            return;
3✔
293
        }
294

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

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

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

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

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

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

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

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

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

333
            if (!in_array($type, $types)) {
17✔
334
                $types[] = $type;
17✔
335
                $schemaProperties['items']['allOf'][]['type'] = $type;
17✔
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}", []);
11✔
343

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

483
        return $preparedRules;
24✔
484
    }
485

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

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

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

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

500
        return $rule;
24✔
501
    }
502

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

510
            $rules = collect(explode('|', $rules));
18✔
511

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

515
                continue;
1✔
516
            }
517

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

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

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

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

535
        $availableValues = $inRule ? array_filter(explode(',', Str::after($inRule, 'in:')), fn ($value) => $value !== '') : [];
1✔
536

537
        $filteredValidation = $validation->reject(fn ($rule) => $rule === 'required')->values();
1✔
538

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

544
    protected function saveQueryParameter(string $parameter, Collection|array $validation, array $attributes, array $annotations, ?string $example = null): void
545
    {
546
        $validation = collect($validation)->all();
18✔
547

548
        $existedParameter = Arr::first(
18✔
549
            $this->item['parameters'],
18✔
550
            fn ($existedParameter) => $existedParameter['name'] === $parameter && Arr::get($existedParameter, 'example') === $example,
18✔
551
        );
18✔
552

553
        if (!empty($existedParameter)) {
18✔
554
            return;
1✔
555
        }
556

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

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

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

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

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

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

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

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

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

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

614
            $uselessRules = $this->ruleToTypeMap;
6✔
615
            $uselessRules['required'] = 'required';
6✔
616

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

621
            $rulesArray = array_flip(array_diff_key(array_flip($rulesArray), $uselessRules));
6✔
622

623
            $data['properties'][$parameter]['description'] = $this->generateDescription($parameter, $rulesArray, $attributes, $annotations);
6✔
624
        }
625

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

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

635
        $parameterType = 'string';
23✔
636

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

643
        return $parameterType;
21✔
644
    }
645

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

653
    protected function generateDescription(string $parameter, array $validation, array $attributes, array $annotations): string
654
    {
655
        $description = Arr::get($annotations, $parameter);
23✔
656

657
        if (empty($description)) {
23✔
658
            $description = Arr::get($attributes, $parameter, implode(', ', $validation));
23✔
659
        }
660

661
        return $description;
23✔
662
    }
663

664
    protected function requestHasMoreProperties($actionName): bool
665
    {
666
        $requestParametersCount = count($this->request->all());
6✔
667

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

671
        return $requestParametersCount > $objectParametersCount;
6✔
672
    }
673

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

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

682
        return empty($bodyParamExisted);
6✔
683
    }
684

685
    public function getConcreteRequest()
686
    {
687
        $controller = $this->request->route()->getActionName();
28✔
688

689
        if ($controller === 'Closure') {
28✔
690
            return null;
1✔
691
        }
692

693
        $explodedController = explode('@', $controller);
27✔
694

695
        $class = $explodedController[0];
27✔
696
        $method = Arr::get($explodedController, 1, '__invoke');
27✔
697

698
        if (!method_exists($class, $method)) {
27✔
699
            return null;
1✔
700
        }
701

702
        $parameters = $this->resolveClassMethodDependencies(
26✔
703
            app($class),
26✔
704
            $method,
26✔
705
        );
26✔
706

707
        return Arr::first($parameters, function ($key) {
26✔
708
            return preg_match('/Request/', $key);
26✔
709
        });
26✔
710
    }
711

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

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

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

727
        $explodedUri = explode('/', $this->uri);
28✔
728
        $explodedUri = array_filter($explodedUri);
28✔
729

730
        $tag = array_shift($explodedUri);
28✔
731

732
        if ($globalPrefix === $tag) {
28✔
733
            $tag = array_shift($explodedUri);
2✔
734
        }
735

736
        $this->item['tags'] = [$tag];
28✔
737
    }
738

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

743
        $description = Arr::get($annotations, 'description');
25✔
744

745
        if (!empty($description)) {
25✔
746
            $this->item['description'] = $description;
1✔
747
        }
748
    }
749

750
    protected function saveSecurity()
751
    {
752
        if ($this->requestSupportAuth()) {
28✔
753
            $this->addSecurityToOperation();
5✔
754
        }
755
    }
756

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

761
        if (empty($security)) {
5✔
762
            $security[] = [
5✔
763
                "{$this->security}" => [],
5✔
764
            ];
5✔
765
        }
766
    }
767

768
    protected function getSummary($request, array $annotations)
769
    {
770
        $summary = Arr::get($annotations, 'summary');
25✔
771

772
        if (empty($summary)) {
25✔
773
            $summary = $this->parseRequestName($request);
24✔
774
        }
775

776
        return $summary;
25✔
777
    }
778

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

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

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

796
                break;
1✔
797
            default:
798
                $securityToken = null;
20✔
799
        }
800

801
        return !empty($securityToken);
28✔
802
    }
803

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

810
        $underscoreRequestName = $this->camelCaseToUnderScore($summaryName);
24✔
811

812
        return preg_replace('/[_]/', ' ', $underscoreRequestName);
24✔
813
    }
814

815
    protected function getResponseDescription($code)
816
    {
817
        $defaultDescription = Response::$statusTexts[$code];
28✔
818

819
        $request = $this->getConcreteRequest();
28✔
820

821
        if (empty($request)) {
28✔
822
            return $defaultDescription;
3✔
823
        }
824

825
        $annotations = $this->getClassAnnotations($request);
25✔
826

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

829
        if (!empty($localDescription)) {
25✔
830
            return $localDescription;
1✔
831
        }
832

833
        return Arr::get($this->config, "defaults.code-descriptions.{$code}", $defaultDescription);
24✔
834
    }
835

836
    protected function getActionName($uri): string
837
    {
838
        $action = preg_replace('[\/]', '', $uri);
28✔
839

840
        return Str::camel($action);
28✔
841
    }
842

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

851
                $this->mergeOpenAPIDocs($resultDocContent, $this->data);
2✔
852

853
                return $resultDocContent;
2✔
854
            });
2✔
855
        }
856

857
        $this->driver->saveData();
4✔
858
    }
859

860
    public function getDocFileContent()
861
    {
862
        try {
863
            $documentation = $this->driver->getDocumentation();
49✔
864

865
            $this->openAPIValidator->validate($documentation);
47✔
866
        } catch (Throwable $exception) {
41✔
867
            return $this->generateEmptyData($this->config['defaults']['error'], [
41✔
868
                'message' => $exception->getMessage(),
41✔
869
                'type' => $exception::class,
41✔
870
                'error_place' => $this->getErrorPlace($exception),
41✔
871
            ]);
41✔
872
        }
873

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

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

882
                continue;
3✔
883
            }
884

885
            $this->mergeOpenAPIDocs($documentation, $additionalDocContent);
1✔
886
        }
887

888
        return $documentation;
8✔
889
    }
890

891
    public function getPrettyDocFileContent(): array
892
    {
893
        $documentation = $this->getDocFileContent();
7✔
894

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

905
                            $base = $params->first();
7✔
906
                            $base['schema']['enum'] = $params
7✔
907
                                ->pluck('example')
7✔
908
                                ->filter(fn ($value) => $value !== null)
7✔
909
                                ->values()
7✔
910
                                ->all();
7✔
911

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

920
        return $documentation;
7✔
921
    }
922

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

927
        Arr::forget($firstTraceEntry, 'type');
41✔
928

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

934
        return implode(PHP_EOL, $formattedTraceEntry);
41✔
935
    }
936

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

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

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

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

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

956
        return $example;
6✔
957
    }
958

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

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

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

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

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

978
        return $returnParameters;
6✔
979
    }
980

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

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

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

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

991
        $result = [];
25✔
992

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

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

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

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

1010
        return $result;
25✔
1011
    }
1012

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

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

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

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

1049
        $license = array_filter($license);
66✔
1050

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

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

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

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

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

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

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

1076
        return $fileContent;
1✔
1077
    }
1078

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

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

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

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

1100
        foreach (Arr::get($additionalDocumentation, 'components.schemas', []) as $definitionName => $definitionData) {
3✔
1101
            if (empty($documentation['components']['schemas'][$definitionName])) {
3✔
1102
                $documentation['components']['schemas'][$definitionName] = $definitionData;
3✔
1103
            }
1104
        }
1105
    }
1106
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc