Skip to content

Commit

Permalink
x-scenarios: name, description.
Browse files Browse the repository at this point in the history
  • Loading branch information
siggi-k committed Aug 22, 2024
1 parent d593a63 commit 444bfae
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/generator/default/dbmodel.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,16 @@
*/
abstract class <?= $model->getClassName() ?> extends \yii\db\ActiveRecord
{
<?php if($scenarios = $model->getScenarios()):
foreach($scenarios as $scenario): ?>
/**
* <?=$scenario['description']?>

*/
public const <?= $scenario['const'] ?> = '<?= $scenario['name'] ?>';

<?php endforeach; ?>
<?php endif ?>
<?php if (count($model->virtualAttributes())):?>
protected $virtualAttributes = ['<?=implode("', '", array_map(function ($attr) {
return $attr->columnName;
Expand Down
56 changes: 56 additions & 0 deletions src/lib/items/DbModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,11 @@ class DbModel extends BaseObject

public $isNotDb = false;

/**
* @var array Automatically generated scenarios from the model 'x-scenarios'.
*/
private array $scenarios;

public function getTableAlias():string
{
return '{{%' . $this->tableName . '}}';
Expand Down Expand Up @@ -178,4 +183,55 @@ public function dbAttributes():array
return !$attribute->isVirtual;
});
}

/**
* @return array
*/
public function getScenarios(): array
{
if (isset($this->scenarios)) {
return $this->scenarios;
}
$this->scenarios = $this->getScenariosByOpenapiSchema();
return $this->scenarios;
}

/**
* @return array
*/
private function getScenariosByOpenapiSchema(): array
{
$x_scenarios = $this->openapiSchema->{'x-scenarios'} ?? [];
if (empty($x_scenarios) || !is_array($x_scenarios)) {
return [];
}

$uniqueNames = [];
$scenarios = array_filter($x_scenarios, function ($scenario) use (&$uniqueNames) {
$name = $scenario['name'] ?? '';

// Check if the name is empty, already used, or does not meet the criteria
if (
empty($name) ||
in_array($name, $uniqueNames) ||
!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $name)
) {
return false; // Exclude this item
}

// Add the name to the uniqueNames array and keep the item
$uniqueNames[] = $name;
return true;
});

foreach ($scenarios as $key => $scenario) {
$scenarios[$key]['const'] = 'SCENARIO_' . strtoupper($scenario['name']);
if (empty($scenario['description'])) {
$scenarios[$key]['description'] = 'Scenario ' . $scenario['name'];
}
}

return $scenarios;
}

}

0 comments on commit 444bfae

Please sign in to comment.