Untitled
unknown
plain_text
7 months ago
2.1 kB
5
Indexable
Never
<?php namespace app\commands; use OpenApi\Generator; use yii\console\Controller; use yii\console\ExitCode; class OpenApiController extends Controller { private string $_filePath = ''; private string $_prefix = 'docs/'; /** * @inheritDoc * @return void */ public function init(): void { $this->_filePath = realpath(dirname(__FILE__)) . '/../web' . DIRECTORY_SEPARATOR; parent::init(); } /** * Generate multiple json file OpenAPI */ public function actionIndex(): void { # Generate initial file. just example $this->generate('./controllers/SiteController.php', 'openapi.json'); # Generate controllers $files = glob("./modules/v1/controllers/*.php"); $exclude = []; foreach ($files as $file){ $fileNameWithoutController = basename($file, '.php'); $fileNameWithoutController = str_replace('Controller', '', $fileNameWithoutController); if(!in_array($fileNameWithoutController, $exclude)){ $jsonFileName = strtolower($fileNameWithoutController) . '.json'; $this->generate($file, $jsonFileName); } } } protected function scanDirectory($path): void { $openapi = Generator::scan([$path]); file_put_contents($this->_filePath . $this->_prefix . 'openapi', $openapi->toJson()); echo $openapi->toJson(); } /** * Generate file json, load di swagger-ui * @param string $file * @param string $fileName * @return int */ protected function generate(string $file, string $fileName): int { // Scan the file, and write those OA annotation into a json file with complete file path $openapi = Generator::scan([$file]); if (file_put_contents($this->_filePath . $this->_prefix . $fileName, $openapi->toJson())) { $this->stdout("Generate: $fileName is success\n"); return ExitCode::OK; } return ExitCode::UNSPECIFIED_ERROR; } }
Leave a Comment