GalleryManager.php 5.87 KB
<?php

namespace common\components;

use Yii;


/**
 * Класс для работы с галереей
 * Class GalleryManager
 */
class GalleryManager
{

    public $sorts = null;
    public $image = null;
    public $imageTitle = null;


    /** @var array Новые Сформированы параметры галереи */
    private $_newGalleryParams = [];

    /** @var null Сформированы параметры галереи с post запросса */
    private $_postParamsGalleryManager = null;

    /** поле сортировки */
    const NAME_SORT = 'sort';

    /** поле фотки */
    const NAME_IMAGE = 'image';

    /** поле фотки */
    const NAME_IMAGE_TITLE = 'title';

    /** image path */
    const NAME_IMAGE_PATH = 'image_path';


    /**
     * @param $json
     * @return array
     */
    public function getFileNames($json)
    {
        $fileNames = [];
        if (is_string($json)) {
            $params = json_decode($json, true);
            if ($params) {
                foreach ($params as $param) {
                    $fileNames[] = $param['image'];
                }
            }
        }

        return $fileNames;
    }


    private function fileExist($filePath, $fileName)
    {
        return (file_exists($filePath . '/' . $fileName) && $fileName) ? true : false;
    }


    /**
     * получаем параметры для сохранения
     * @param $fileNames
     * @return string (json)
     */
    public function getOptionsForSaving($fileNames, $filePath)
    {
        $this->getGalleryManagerPostParams();
        $this->generateGalleryParams($fileNames);
        $newFiles = $this->getNewFiles($fileNames, true);
        if ($newFiles) {
            foreach ($newFiles as $fileName) {
                $param = ($this->getGalleryManagerPostParams($fileName))
                    ? $this->getGalleryManagerPostParams($fileName)
                    : $this->generateGalleryParams($fileName);
                if ($this->fileExist($filePath, $param[self::NAME_IMAGE])) {
                    $this->_newGalleryParams[] = $param;
                }
            }
        }
        $this->mergeOldFiles($fileNames, $filePath);
        if ($this->_newGalleryParams) {
            uasort($this->_newGalleryParams, [$this, 'gallerySort']);
        }

        return json_encode($this->_newGalleryParams);
    }

    /**
     * склеиваем старые файлы с новыми
     * @param $fileNames
     * @param $filePath
     */
    public function mergeOldFiles($fileNames, $filePath)
    {

        if (is_string($fileNames) && json_decode($fileNames)) {
            $oldFifes = json_decode($fileNames, true);
            foreach ($oldFifes as $param) {
                $fileName = (isset($param[self::NAME_IMAGE])) ? $param[self::NAME_IMAGE] : '';

                if ($this->fileExist($filePath, $fileName)) {
                    $this->_newGalleryParams[] = ($this->getGalleryManagerPostParams($fileName))
                        ? $this->getGalleryManagerPostParams($fileName)
                        : $param;
                }
            }
        }
    }


    /**
     * Получаем новые файлы из параметров
     * @param $fileNames
     * @param bool $clearLineFromNewFiles - очищаем строку с файлами от новых файлов
     * @return array
     */

    private function getNewFiles(& $fileNames, $clearLineFromNewFiles = false)
    {
        $fileNames = explode(',', $fileNames);
        $newFiles = [];
        if ($fileNames) {
            foreach ($fileNames as $key => $param) {
                if (preg_match('/^.*.(jpg|png|jpeg|gif)$/i', $param)) {
                    $newFiles[] = $param;
                    if ($clearLineFromNewFiles === true) {
                        unset($fileNames[$key]);
                    }
                }
            }
        }
        $fileNames = implode(',', $fileNames);

        return $newFiles;
    }


    /**
     * @param $fileName
     * @return array
     */
    public function generateGalleryParams($fileName)
    {
        return [
            self::NAME_IMAGE => $fileName,
            self::NAME_IMAGE_TITLE => '',
            self::NAME_SORT => 1,
            self::NAME_IMAGE_PATH => '',
        ];
    }

    /**
     * @param null $fileName
     * @return null
     */
    private function getGalleryManagerPostParams($fileName = null)
    {
        $galleryParams = null;

        if ($this->_postParamsGalleryManager === null) {
            $galleryParams = Yii::$app->getRequest()->post('GalleryManager', null);

            if ($galleryParams) {
                foreach ($galleryParams[self::NAME_IMAGE] as $key => $value) {
                    $filename = $value;

                    if (strripos($value, '/') !== false) {
                        $filename = substr($value, strripos($value, '/') + 1);
                    }

                    $this->_postParamsGalleryManager[$filename] = [
                        self::NAME_IMAGE => $filename,
                        self::NAME_IMAGE_TITLE => $galleryParams[self::NAME_IMAGE_TITLE][$key],
                        self::NAME_SORT => $galleryParams[self::NAME_SORT][$key],
                        self::NAME_IMAGE_PATH => '',
                    ];
                }
            }
        }

        if ($fileName !== null) {
            $galleryParams = isset($this->_postParamsGalleryManager[$fileName]) ? $this->_postParamsGalleryManager[$fileName] : null;
        }

        return ($fileName === null) ? $this->_postParamsGalleryManager : $galleryParams;
    }

    /** Сортируем галлерею */
    private function gallerySort($a, $b)
    {
        $a = isset($a['sort']) ? $a['sort'] : null;
        $b = isset($b['sort']) ? $b['sort'] : null;

        if ($a == $b || ($a === null || $b === null)) {
            return 0;
        }
        return ($a < $b) ? -1 : 1;
    }


}