|
|
|
<?php
|
|
|
|
|
|
|
|
namespace core\behaviors;
|
|
|
|
|
|
|
|
use core\entities\Meta;
|
|
|
|
use Exception;
|
|
|
|
use yii\base\Behavior;
|
|
|
|
use yii\base\Event;
|
|
|
|
use yii\db\ActiveRecord;
|
|
|
|
use yii\db\BaseActiveRecord;
|
|
|
|
use yii\helpers\ArrayHelper;
|
|
|
|
use yii\helpers\Json;
|
|
|
|
|
|
|
|
class MetaBehavior extends Behavior
|
|
|
|
{
|
|
|
|
public string $attribute = 'meta';
|
|
|
|
public string $jsonAttribute = 'meta_json';
|
|
|
|
|
|
|
|
public function events(): array
|
|
|
|
{
|
|
|
|
return [
|
|
|
|
BaseActiveRecord::EVENT_AFTER_FIND => 'onAfterFind',
|
|
|
|
BaseActiveRecord::EVENT_BEFORE_INSERT => 'onBeforeSave',
|
|
|
|
BaseActiveRecord::EVENT_BEFORE_UPDATE => 'onBeforeSave',
|
|
|
|
];
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param Event $event
|
|
|
|
* @throws Exception
|
|
|
|
*/
|
|
|
|
public function onAfterFind(Event $event): void
|
|
|
|
{
|
|
|
|
$model = $event->sender;
|
|
|
|
$meta = Json::decode($model->getAttribute($this->jsonAttribute));
|
|
|
|
$model->{$this->attribute} = new Meta(
|
|
|
|
ArrayHelper::getValue($meta, 'title'),
|
|
|
|
ArrayHelper::getValue($meta, 'description'),
|
|
|
|
ArrayHelper::getValue($meta, 'keywords')
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
public function onBeforeSave(Event $event): void
|
|
|
|
{
|
|
|
|
$model = $event->sender;
|
|
|
|
$model->setAttribute('meta_json', Json::encode([
|
|
|
|
'title' => $model->{$this->attribute}->title,
|
|
|
|
'description' => $model->{$this->attribute}->description,
|
|
|
|
'keywords' => $model->{$this->attribute}->keywords,
|
|
|
|
]));
|
|
|
|
}
|
|
|
|
}
|