DarkaOnLine / L5-Swagger

OpenApi or Swagger integration to Laravel
https://github.com/DarkaOnLine/L5-Swagger
MIT License
2.64k stars 394 forks source link

How to use default constants with PHP Attributes. #537

Closed beeyev closed 8 months ago

beeyev commented 1 year ago

phpdoc approach is working correctly as expected:

/**
 *  @OA\Server(
 *      url=L5_SWAGGER_CONST_HOST,
 *      description="L5 Swagger OpenApi dynamic host server"
 *  )
 */

But if I use PHP Attributes, it does not work:

#[OA\Server(url: 'L5_SWAGGER_CONST_HOST', description: 'L5 Swagger OpenApi dynamic host server')]

Is it possible to use dynamic constants inside Attributes ?

SantaRiver commented 1 year ago

Did you find the answer?

DerManoMann commented 1 year ago

If L5_SWAGGER_CONST_HOST is a PHP const that you can use it without quotes. Attributes are regular PHP so usage of consts is the same as for any other PHP code.

mohssineAboutaj commented 1 year ago

your comment is correct just check if the variable exists in .env file and/or in config/l5-swagger.php

 * @OA\Server(url=L5_SWAGGER_CONST_HOST)
Rikj000 commented 9 months ago

Usable work around until this issue has been resolved.

config/l5-swagger.php

Temporarily store the $swagger_config in a variable,
dynamically define all configured constants before returning the $swagger_config.

<?php
// ...
$swagger_config = [
   // ...
   'constants' => [
            'L5_SWAGGER_CONST_HOST' => env(key: 'L5_SWAGGER_CONST_HOST', default: 'https://my-default-host.com'),
            'APP_NAME' => env(key: 'APP_NAME', default: 'MyApp'),
            'APP_VERSION' => env(key: 'APP_VERSION', default: 'v1.0.0')
    ]
];

// Dynamically define constants to make them available in OpenApi\Attributes
foreach ($swagger_config['defaults']['constants'] as $constant_name => $constant_value) {
    define(constant_name: $constant_name, value: $constant_value);
}

return $swagger_config;

app/Http/Controllers/MyController.php

Ignore PhpUndefinedConstantInspections on the dynamically defined constants through a @noinspection tag.

<?php /** @noinspection PhpUndefinedConstantInspection */

namespace App\Http\Controllers;

use OpenApi\Attributes as OA;

#[OA\Info(version: APP_VERSION, title: APP_NAME)]
class MyController {}