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

RonasIT / laravel-swagger / 25786988811

13 May 2026 08:14AM UTC coverage: 99.67% (+0.01%) from 99.656%
25786988811

Pull #198

github

web-flow
Merge cf2fc2d7b 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.

905 of 908 relevant lines covered (99.67%)

21.84 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\Enums\RelationQueryParam;
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);
104✔
71

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

164
        return $data;
65✔
165
    }
166

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

174
    protected function generateSecurityDefinition(): ?array
175
    {
176
        if (empty($this->security)) {
65✔
177
            return null;
62✔
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($rules, array $attributes, array $annotations)
504
    {
505
        foreach ($rules as $parameter => $rule) {
19✔
506
            if (in_array($parameter, RelationQueryParam::values())) {
18✔
507
                continue;
1✔
508
            }
509

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

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

515
                continue;
1✔
516
            }
517

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

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

528
        return in_array(substr($parameter, 0, -2), RelationQueryParam::values());
1✔
529
    }
530

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

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

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

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

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

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

555
        $description = Arr::get($annotations, $parameter)
17✔
556
            ?: Arr::get($attributes, $parameter, implode(', ', $validation));
17✔
557

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

634
        $parameterType = 'string';
23✔
635

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

642
        return $parameterType;
21✔
643
    }
644

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

780
        return $summary;
25✔
781
    }
782

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

886
                continue;
3✔
887
            }
888

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

892
        return $documentation;
8✔
893
    }
894

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

899
        $arrayParamNames = array_map(fn ($case) => "{$case->value}[]", RelationQueryParam::cases());
7✔
900

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

911
                            $base = $params->first();
1✔
912
                            $base['schema']['enum'] = $params->pluck('example')->filter()->values()->all();
1✔
913

914
                            return $base;
1✔
915
                        })
7✔
916
                        ->values()
7✔
917
                        ->all();
7✔
918
                }
919
            }
920
        }
921

922
        return $documentation;
7✔
923
    }
924

925
    protected function getErrorPlace(Throwable $exception): string
926
    {
927
        $firstTraceEntry = Arr::first($exception->getTrace());
40✔
928

929
        Arr::forget($firstTraceEntry, 'type');
40✔
930

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

936
        return implode(PHP_EOL, $formattedTraceEntry);
40✔
937
    }
938

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

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

948
        return implode('_', $ret);
24✔
949
    }
950

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

956
        $this->replaceNullValues($parameters, $properties, $example);
6✔
957

958
        return $example;
6✔
959
    }
960

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

967
        $parameters = Arr::dot($parameters);
6✔
968
        $returnParameters = [];
6✔
969

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

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

977
            Arr::set($returnParameters, $parameter, $value);
6✔
978
        }
979

980
        return $returnParameters;
6✔
981
    }
982

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

987
        $annotations = $reflection->getDocComment();
25✔
988

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

991
        $blocks = explode("\n", $annotations);
25✔
992

993
        $result = [];
25✔
994

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

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

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

1008
                $result[$paramName] = $paramValue;
1✔
1009
            }
1010
        }
1011

1012
        return $result;
25✔
1013
    }
1014

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

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

1044
        return $values[$type];
5✔
1045
    }
1046

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

1051
        $license = array_filter($license);
65✔
1052

1053
        if (!empty($license)) {
65✔
UNCOV
1054
            $info['license'] = $license;
×
1055
        }
1056

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

1061
        return array_merge($this->config['info'], $info);
65✔
1062
    }
1063

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

1070
        $fileContent = json_decode(file_get_contents($filePath), true);
3✔
1071

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

1076
        $this->openAPIValidator->validate($fileContent);
2✔
1077

1078
        return $fileContent;
1✔
1079
    }
1080

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

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

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

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

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