2016-05-16 04:03:19 +05:30
|
|
|
<?php
|
|
|
|
namespace common\behaviors;
|
|
|
|
|
|
|
|
use yii\base\Behavior;
|
|
|
|
use yii\helpers\ArrayHelper;
|
|
|
|
|
|
|
|
class DataBehavior extends Behavior {
|
2018-04-18 02:17:25 +05:30
|
|
|
|
2016-05-16 04:03:19 +05:30
|
|
|
/**
|
2019-07-15 04:29:56 +05:30
|
|
|
* @var string attribute name to which this behavior will be applied
|
2016-05-16 04:03:19 +05:30
|
|
|
*/
|
|
|
|
public $attribute = '_data';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param string $key
|
|
|
|
* @param mixed $value
|
|
|
|
*/
|
|
|
|
protected function setKey(string $key, $value) {
|
|
|
|
$data = $this->getData();
|
|
|
|
$data[$key] = $value;
|
|
|
|
$this->owner->{$this->attribute} = serialize($data);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param string $key
|
|
|
|
* @return mixed
|
|
|
|
*/
|
|
|
|
protected function getKey(string $key) {
|
|
|
|
return ArrayHelper::getValue($this->getData(), $key);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @return array
|
2019-07-15 04:29:56 +05:30
|
|
|
* @throws \yii\base\ErrorException Yii2 will catch Notice from the wrong deserialization and turn it
|
|
|
|
* into its own Exception, so that the program can continue to work normally (you still should catch an Exception)
|
2016-05-16 04:03:19 +05:30
|
|
|
*/
|
|
|
|
private function getData() {
|
|
|
|
$data = $this->owner->{$this->attribute};
|
|
|
|
if (is_string($data)) {
|
|
|
|
$data = unserialize($data);
|
|
|
|
} else {
|
|
|
|
$data = [];
|
|
|
|
}
|
|
|
|
|
|
|
|
return $data;
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|