horat1us/yii2-validation-exception

Yii2 Validation Exception

1.1.0 2022-11-14 14:21 UTC

This package is auto-updated.

Last update: 2024-12-14 19:19:45 UTC


README

Test & Lint codecov

This package add additional methods and exception for model validation.
Main purpose is to prevent mistakes while models validations (forgot to check validation result for failse etc).

Previous implementation was available in horat1us/yii2-base package as ModelExceptionInterface and ModelException.

Installation

Using packagist.org:

composer require horat1us/yii2-validation-exception:^1.0

Structure

Should be used when ActiveRecord is implemented out of project repository (working with dependencies).

Should be used when ActiveRecord implemented in project repository and may implement interfaces and use traits.

  • Validation\Failure\ModelInterface - extends \yii\base\Model with methods validateOrFail and checkOrFail.
    • Model - trait with implementation.
  • [Validation\Failure\ActiveRecordInterface] - extends \yii\db\ActiveRecord with saveOrFail method.

Example

With extension for model and active record:

<?php

namespace App;

use Horat1us\Yii\Validation;
use yii\base;

class Model extends base\Model implements Validation\Failure\ModelInterface
{
    use Validation\Failure\Model;
    
    public $id;
    
    public function rules(): array {
        return [
            [['id',], 'required',],    
        ];
    }
}

$model = new Model;
try {
    $model->validateOrFail();
} catch (Validation\Failure $failure) {
    // handle
}

With exceptions factory:

<?php

namespace App;

use Horat1us\Yii\Validation;
use yii\base;

class Model extends base\Model 
{
    /** @var string  */
    public $id;
    
    public function rules() {
        return [
            [['id',], 'required',],
        ];
    }
}

$model = new Model;

try {
    Validation\Exception::validateOrThrow($model);
} catch (Validation\Failure $failure) {
    // handle
}

License

MIT