horat1us/yii2-model-schema

JSON Schema for Yii2 Model using validation rules

Installs: 859

Dependents: 1

Suggesters: 0

Security: 0

Stars: 0

Watchers: 1

Forks: 0

Open Issues: 1

pkg:composer/horat1us/yii2-model-schema

2.0.0 2026-02-19 15:51 UTC

README

Latest Stable Version Total Downloads CI codecov

Create JSON Schema from Yii2 Model using validation rules and other public methods.

Installation

Using composer:

composer require horat1us/yii2-model-schema:^2.0

Usage

base\Model extensions

Additional interfaces that will be used for generating JsonSchema, when they are implemented in model.

AttributesExamples

Will be used to generate property examples

See AttributesExamplesTrait for implementation Since 1.1.0

<?php declare(strict_types=1);

namespace App;

use Horat1us\Yii\Model;
use yii\base;

$model = new class extends base\Model implements Model\AttributesExamples {
    use Model\AttributesExamplesTrait;
    public function attributesExamples(): array {
        return [
            'a' => [1,2],
            'b' => [],
        ];
    }
};
echo $model->getAttributeExamples('a'); // [1,2]
echo $model->getAttributeExamples('b'); // null
echo $model->getAttributeExamples('c'); // null
echo $model->getAttributeExample('a'); // 1
echo $model->getAttributeExample('b'); // null
echo $model->getAttributeExample('c'); // null

Conditional Required Fields

When a RequiredValidator has a when callable, JsonSchema evaluates it against the model at schema-generation time. Only attributes whose when returns true (or have no when) appear in the required array.

$model = new class extends base\Model {
    public string $passport_type = 'idcard';
    public string $passport_number = '';
    public string $idcard_number = '';

    public function rules(): array {
        return [
            [['passport_number'], 'required',
             'when' => fn(base\Model $m): bool => $m->passport_type === 'legacy'],
            [['idcard_number'], 'required',
             'when' => fn(base\Model $m): bool => $m->passport_type === 'idcard'],
        ];
    }
};
// passport_type is 'idcard' → only idcard_number in required
$schema = (new JsonSchema($model))->jsonSerialize();
// $schema['required'] === ['idcard_number']

TODO

Write docs:

Contributors

License

MIT