| 1 |
<?php declare(strict_types=1); |
| 2 |
|
| 3 |
/** |
| 4 |
* @license Apache 2.0 |
| 5 |
*/ |
| 6 |
|
| 7 |
namespace OpenApi\Processors; |
| 8 |
|
| 9 |
use OpenApi\Analysis; |
| 10 |
use OpenApi\Annotations as OA; |
| 11 |
use OpenApi\Generator; |
| 12 |
|
| 13 |
/** |
| 14 |
* Generate the OperationId based on the context of the OpenApi annotation. |
| 15 |
*/ |
| 16 |
class OperationId |
| 17 |
{ |
| 18 |
protected bool $hash; |
| 19 |
|
| 20 |
public function __construct(bool $hash = true) |
| 21 |
{ |
| 22 |
$this->hash = $hash; |
| 23 |
} |
| 24 |
|
| 25 |
public function isHash(): bool |
| 26 |
{ |
| 27 |
return $this->hash; |
| 28 |
} |
| 29 |
|
| 30 |
/** |
| 31 |
* If set to <code>true</code> generate ids (md5) instead of clear text operation ids. |
| 32 |
*/ |
| 33 |
public function setHash(bool $hash): OperationId |
| 34 |
{ |
| 35 |
$this->hash = $hash; |
| 36 |
|
| 37 |
return $this; |
| 38 |
} |
| 39 |
|
| 40 |
public function __invoke(Analysis $analysis): void |
| 41 |
{ |
| 42 |
$allOperations = $analysis->getAnnotationsOfType(OA\Operation::class); |
| 43 |
|
| 44 |
/** @var OA\Operation $operation */ |
| 45 |
foreach ($allOperations as $operation) { |
| 46 |
if (null === $operation->operationId) { |
| 47 |
$operation->operationId = Generator::UNDEFINED; |
| 48 |
} |
| 49 |
|
| 50 |
if (!Generator::isDefault($operation->operationId)) { |
| 51 |
continue; |
| 52 |
} |
| 53 |
|
| 54 |
$context = $operation->_context; |
| 55 |
if ($context) { |
| 56 |
$source = $context->class ?? $context->interface ?? $context->trait; |
| 57 |
$operationId = null; |
| 58 |
if ($source) { |
| 59 |
$method = $context->method ? ('::' . $context->method) : ''; |
| 60 |
$operationId = $context->namespace ? $context->namespace . '\\' . $source . $method : $source . $method; |
| 61 |
} elseif ($context->method) { |
| 62 |
$operationId = $context->method; |
| 63 |
} |
| 64 |
|
| 65 |
if ($operationId) { |
| 66 |
$operationId = strtoupper($operation->method) . '::' . $operation->path . '::' . $operationId; |
| 67 |
$operation->operationId = $this->hash ? md5($operationId) : $operationId; |
| 68 |
} |
| 69 |
} |
| 70 |
} |
| 71 |
} |
| 72 |
} |