for testing and deploying your application
for finding and fixing issues
for empowering human code reviews
<?php
namespace Horat1us\Yii\Traits;
use yii\base\Model;
use yii\db\ActiveRecord;
use yii\db\ActiveRecordInterface;
/**
* Class ModelExceptionTrait
* @package Horat1us\Yii\Traits
* @see \Exception
*/
trait ModelExceptionTrait
{
/** @var Model */
protected $model;
* ModelExceptionTrait constructor.
* @param Model $model
* @param int $code
* @param \Throwable $previous
public function __construct(Model $model, int $code = 0, \Throwable $previous = null)
$message = get_class($model) . " validation errors";
parent::__construct($message, $code, $previous);
$this->model = $model;
}
* @return Model
public function getModel(): Model
return $this->model;
public static function validateOrThrow(Model $model): Model
if (!$model->validate()) {
throw new static($model);
return $model;
* @param ActiveRecordInterface $record
* @return ActiveRecordInterface|ActiveRecord
public static function saveOrThrow(ActiveRecordInterface $record): ActiveRecordInterface
if (!$record->save() && $record instanceof Model) {
throw new static($record);
return $record;
* @param string $attribute
* @param string $error
public static function addAndThrow(string $attribute, string $error, Model $model)
$model->addError($attribute, $error);