ShowImage.php 2.69 KB
<?php

    namespace common\behaviors;

    use common\modules\file\components\UploaderComponent;
    use yii;
    use yii\base\Behavior;

    class ShowImage extends Behavior
    {

        /**
         * Resize image and return its path.
         *
         * @param string              $dir    Original image path
         * @param integer|string      $width  New image width
         * @param null|integer|string $height New image height, set NULL to save ratio
         *
         * @return string Resized image path
         * @throws \Exception
         */
        function minImg($dir, $width, $height = NULL)
        {
            if(empty( $dir )) {
                return '/images/imageNotFound.jpg';
            }

            if($width == 'original') {
                $preg = '/\/(.[^\/]*)$/';
                preg_match('/\.(.[^.]*)$/', $dir, $type);
                if(isset( $type[ 1 ] )) {
                    $dir = preg_replace($preg, '/original.' . $type[ 1 ], $dir);
                }

            } else {
                $preg = '/\/(.[^\/]*)$/';
                preg_match('/\.(.[^.]*)$/', $dir, $type);
                if(isset( $type[ 1 ] )) {
                    $dir = preg_replace($preg, '/' . $width . 'x' . $height . '.' . $type[ 1 ], $dir);
                    $storage = dirname(yii\helpers\Url::to('@storage'));
                    $filename = $storage . $dir;
                    if(!file_exists($filename)) {

                        $original = $storage . dirname($dir) . '/original.' . $type[ 1 ];
                        $resizer = new UploaderComponent();
                        if(file_exists($original)) {
                            $resizer->resizeImg($width, $height, $original, $filename);
                        } else {

                            $imageNotFound = yii\helpers\Url::to('@storage')."/imageNotFound".$width."x".$height.".jpg";
                            if(!file_exists($imageNotFound)){
                                 $resizer->resizeImg($width, $height, yii\helpers\Url::to('@storage')."/imageNotFound.jpg", $imageNotFound );
                            }
                            return "/storage/imageNotFound".$width."x".$height.".jpg";


                        }

                    }

                }

            }

            return $dir;

        }

        /**
         * @param string $array String to split
         *
         * @return array Array of image paths
         */
        function ShowGallery($array)
        {

            $gallery = explode(',', $array);
            if(is_array($gallery)) {
                array_splice($gallery, -1);
                return $gallery;
            } else {
                return [ ];
            }

        }

    }