ImageHelper.php 1.79 KB
<?php
    namespace artbox\core\helpers;
    
    use yii\base\InvalidConfigException;
    use Yii;
    
    /**
     * Class ImageHelper
     *
     * @package artbox\core\helpers
     */
    class ImageHelper
    {
        /**
         * Parse $given path and creates image manipulator instance
         *
         * @param $path
         *
         * @return ImageManipulator
         * @throws \yii\base\InvalidConfigException
         */
        public static function set($path)
        {
            self::checkDir();
    
            $path = Yii::getAlias($path);
    
            if (!file_exists($path) || empty($path)) {
                $path = Yii::getAlias('@frontend/web/img/no-image.png');
            }
            
            $matches = [];
            if (!preg_match("~^(.+\/)([a-zA-Z0-9_-]+)\.(jpg|jpeg|gif|png)$~i", $path, $matches)) {
                throw new InvalidConfigException('Wrong file path');
            }
            /**
             * @var ImageManipulator $obj
             */
            $obj = Yii::createObject(
                [
                    'class'     => ImageManipulator::className(),
                    'fullPath'  => $matches[ 0 ],
                    'path'      => $matches[ 1 ],
                    'name'      => $matches[ 2 ],
                    'extension' => $matches[ 3 ],

                ]
            );
    
            return $obj;
        }
    
        /**
         * Check if helper directory exists, if not - create it
         */
        protected static function checkDir()
        {
            $dir = Yii::getAlias('@storage/helper');
            $stor = Yii::getAlias('@storage');
    
            if (!is_dir($stor)) {
                mkdir($stor);
            }
            if (!is_dir($dir)) {
                mkdir($dir);
            }
        }
    }