Created
March 20, 2018 15:27
-
-
Save zhuravljov/c70889eda12aff87723864eacfafe0cd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace common\models; | |
use Yii; | |
use yii\base\Behavior; | |
use yii\base\Model; | |
use yii\base\ModelEvent; | |
/** | |
* ScalarBehavior | |
* | |
* Поведение пресекает хакерские попытки просунуть массивы в атрибуты формы, где должны быть | |
* скалярные значения. Это создает ошибки в хелпере Html. Перед валидацией проверяются входящие | |
* данные, и, если значение какого-то из атрибутов не скалярное, оно заменяется на `null`. | |
* | |
* @author Roman Zhuravlev <[email protected]> | |
*/ | |
class ScalarBehavior extends Behavior | |
{ | |
/** | |
* @var Model | |
* @inheritdoc | |
*/ | |
public $owner; | |
/** | |
* @var null|array список атрибутов, которые должны быть скалярными. Если список не указан | |
* скалярность будет проверяться для всех safe-аттрибутов. | |
*/ | |
public $scalarAttributes; | |
/** | |
* @inheritdoc | |
*/ | |
public function events() | |
{ | |
return [ | |
Model::EVENT_BEFORE_VALIDATE => 'beforeValidate', | |
]; | |
} | |
/** | |
* @param ModelEvent $event | |
*/ | |
public function beforeValidate(ModelEvent $event) | |
{ | |
if ($this->scalarAttributes === null) { | |
$this->scalarAttributes = $this->owner->safeAttributes(); | |
} | |
foreach ($this->scalarAttributes as $attribute) { | |
$value = $this->owner->$attribute; | |
if (!is_scalar($value) && !is_null($value)) { | |
$this->owner->$attribute = null; | |
$this->owner->addError($attribute, Yii::t('yii', '{attribute} is invalid.', [ | |
'attribute' => $this->owner->getAttributeLabel($attribute), | |
])); | |
Yii::warning('Not a scalar value', __CLASS__); | |
$event->isValid = false; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment