GalleryBehavior.php 1.76 KB
<?php
namespace common\behaviors;

use Exception;
use yii\base\Behavior;
use yii\db\ActiveRecord;

class GalleryBehavior extends Behavior
{
    /**
     * @var array Массив аттрибутов которые должны быть обработаны с HtmlPurifier
     */
    public $attributes = [];


    /** @var string название переменной в которой храниться галлерея */
    public $galleryRow = '';

    /** @var string сценарий */
    public $scenario = 'backend';

    /** @var string filePath */
    public $path = '';

    /** @var   */
    private $_galleryManagerNamespace = \common\components\GalleryManager::class;

    /** @var null gallery manager */
    private $_galleryManagerModel = null;


    public function events()
    {
        return [
            ActiveRecord::EVENT_BEFORE_INSERT => 'saveGallery',
            ActiveRecord::EVENT_BEFORE_UPDATE => 'saveGallery',
        ];
    }

    /**
     * Save seo model
     */
    public function saveGallery()
    {
        $model = $this->owner;
        if (isset($model->{$this->galleryRow})) {
            $galleryManager = $this->getGalleryManager();
            $model->{$this->galleryRow} = $galleryManager->getOptionsForSaving($model->{$this->galleryRow}, $this->path);
            if (! $model->isScenario($this->scenario)) {
                throw new Exception(get_class($model) . '::' . $this->scenario . " scenario doesn't exist");
            }
        }
    }

    /**
     * Gallery manager
     * @return null
     */
    private function getGalleryManager()
    {
        if ($this->_galleryManagerModel === null) {
            $this->_galleryManagerModel = new $this->_galleryManagerNamespace();
        }

        return $this->_galleryManagerModel;
    }
}