You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 lines
1.4 KiB

7 years ago
<?php
namespace core\behaviors;
use core\entities\Meta;
3 years ago
use Exception;
7 years ago
use yii\base\Behavior;
use yii\base\Event;
use yii\db\ActiveRecord;
3 years ago
use yii\db\BaseActiveRecord;
7 years ago
use yii\helpers\ArrayHelper;
use yii\helpers\Json;
class MetaBehavior extends Behavior
{
3 years ago
public string $attribute = 'meta';
public string $jsonAttribute = 'meta_json';
7 years ago
public function events(): array
{
return [
3 years ago
BaseActiveRecord::EVENT_AFTER_FIND => 'onAfterFind',
BaseActiveRecord::EVENT_BEFORE_INSERT => 'onBeforeSave',
BaseActiveRecord::EVENT_BEFORE_UPDATE => 'onBeforeSave',
7 years ago
];
}
3 years ago
/**
* @param Event $event
* @throws Exception
*/
7 years ago
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,
]));
}
3 years ago
}