|
| 1 | +<?php |
| 2 | +namespace Tqdev\PhpCrudApi\OpenApi; |
| 3 | + |
| 4 | +use Tqdev\PhpCrudApi\Column\ReflectionService; |
| 5 | +use Tqdev\PhpCrudApi\OpenApi\OpenApiDefinition; |
| 6 | + |
| 7 | +class OpenApiBuilder |
| 8 | +{ |
| 9 | + private $openapi; |
| 10 | + private $reflection; |
| 11 | + private $operations = [ |
| 12 | + 'list' => 'get', |
| 13 | + 'create' => 'post', |
| 14 | + 'read' => 'get', |
| 15 | + 'update' => 'put', |
| 16 | + 'delete' => 'delete', |
| 17 | + 'increment' => 'patch', |
| 18 | + ]; |
| 19 | + private $types = [ |
| 20 | + 'integer' => 'integer', |
| 21 | + 'varchar' => 'string', |
| 22 | + 'blob' => 'string', |
| 23 | + 'clob' => 'string', |
| 24 | + 'decimal' => 'string', |
| 25 | + 'timestamp' => 'string', |
| 26 | + 'geometry' => 'string', |
| 27 | + 'boolean' => 'boolean', |
| 28 | + ]; |
| 29 | + |
| 30 | + public function __construct(ReflectionService $reflection, $base) |
| 31 | + { |
| 32 | + $this->reflection = $reflection; |
| 33 | + $this->openapi = new OpenApiDefinition($base); |
| 34 | + } |
| 35 | + |
| 36 | + public function build(): OpenApiDefinition |
| 37 | + { |
| 38 | + $this->openapi->set("openapi", "3.0.0"); |
| 39 | + $tableNames = $this->reflection->getTableNames(); |
| 40 | + foreach ($tableNames as $tableName) { |
| 41 | + $this->setPath("paths", $tableName); |
| 42 | + } |
| 43 | + foreach ($tableNames as $tableName) { |
| 44 | + $this->setComponentSchema("components|schemas", $tableName); |
| 45 | + } |
| 46 | + return $this->openapi; |
| 47 | + } |
| 48 | + |
| 49 | + private function setPath(String $prefix, String $tableName) /*: void*/ |
| 50 | + { |
| 51 | + $table = $this->reflection->getTable($tableName); |
| 52 | + $pk = $table->getPk(); |
| 53 | + $pkName = $pk ? $pk->getName() : ''; |
| 54 | + foreach ($this->operations as $operation => $method) { |
| 55 | + if (in_array($operation, ['list', 'create'])) { |
| 56 | + $path = sprintf('/records/%s', $tableName); |
| 57 | + } else { |
| 58 | + if (!$pkName) { |
| 59 | + continue; |
| 60 | + } |
| 61 | + $path = sprintf('/records/%s/{%s}', $tableName, $pkName); |
| 62 | + } |
| 63 | + $this->openapi->set("$prefix|$path|$method|description", "$operation $tableName"); |
| 64 | + $this->openapi->set("$prefix|$path|$method|responses|200|description", "$operation $tableName succeeded"); |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + private function setComponentSchema(String $prefix, String $tableName) /*: void*/ |
| 69 | + { |
| 70 | + $this->openapi->set("$prefix|$tableName|type", "object"); |
| 71 | + $table = $this->reflection->getTable($tableName); |
| 72 | + foreach ($table->columnNames() as $columnName) { |
| 73 | + $column = $table->get($columnName); |
| 74 | + $type = $this->types[$column->getType()]; |
| 75 | + $this->openapi->set("$prefix|$tableName|properties|$columnName|type", $type); |
| 76 | + } |
| 77 | + } |
| 78 | +} |
0 commit comments