Completed
Push — master ( f62520...989a06 )
by Davide
04:00
created

ResponsiveGalleryFactory::getGallery()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 32
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 16
nc 4
nop 2
dl 0
loc 32
ccs 15
cts 15
cp 1
crap 4
rs 9.7333
c 0
b 0
f 0
1
<?php
2
3
namespace DavideCasiraghi\ResponsiveGallery;
4
5
use DavideCasiraghi\ResponsiveGallery\Models\GalleryImage;
6
7
class ResponsiveGalleryFactory
8
{
9
    /************************************************************************/
10
11
    /**
12
     *  Returns the plugin parameters.
13
     *  @param array $matches       result from the regular expression on the string from the article
14
     *  @return array $ret          the array containing the parameters
15
     **/
16 2
    public static function getGalleryParameters($matches, $publicPath)
17
    {
18 2
        $ret = [];
19
20
        // Get Paths
21 2
        $sitePath = '/';
0 ignored issues
show
Unused Code introduced by
The assignment to $sitePath is dead and can be removed.
Loading history...
22 2
        $siteUrl = $publicPath;
0 ignored issues
show
Unused Code introduced by
The assignment to $siteUrl is dead and can be removed.
Loading history...
23
24
        // Get activation string parameters (from article)
25 2
        $ret['token'] = $matches[0];
26 2
        $subDir = $matches[2];
27 2
        $ret['column_width'] = $matches[4];
28 2
        $ret['gutter'] = $matches[6];
29
30
        // Directories
31 2
        $ret['images_dir'] = $publicPath.'/'.$subDir.'/';
32 2
        $ret['thumbs_dir'] = $publicPath.'/'.$subDir.'/thumb/';
33
34
        // Thumbnails size
35 2
        $ret['thumbs_size']['width'] = 300;
36 2
        $ret['thumbs_size']['height'] = 300;
37
38
        // URL variables
39 2
        $ret['gallery_url'] = $subDir.'/';
40 2
        $ret['thumb_url'] = $subDir.'/thumbs/';
41
42 2
        return $ret;
43
    }
44
45
    /************************************************************************/
46
47
    /**
48
     *  Generate a single thumbnail file from an image.
49
     *  @param array $src               path of the original image
50
     *  @param array $dest              path of the generated thumbnail
51
     *  @param array $desired_width     width of the thumbnail
52
     *  @return create a file
0 ignored issues
show
Bug introduced by
The type DavideCasiraghi\ResponsiveGallery\create was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
53
     **/
54 2
    public function generate_single_thumb_file($src, $dest, $desired_width, $desired_height)
0 ignored issues
show
Unused Code introduced by
The parameter $desired_width is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

54
    public function generate_single_thumb_file($src, $dest, /** @scrutinizer ignore-unused */ $desired_width, $desired_height)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $desired_height is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

54
    public function generate_single_thumb_file($src, $dest, $desired_width, /** @scrutinizer ignore-unused */ $desired_height)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
55
    {
56
        // Read the source image
57 2
        $source_image = imagecreatefromjpeg($src);
0 ignored issues
show
Bug introduced by
$src of type array is incompatible with the type string expected by parameter $filename of imagecreatefromjpeg(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

57
        $source_image = imagecreatefromjpeg(/** @scrutinizer ignore-type */ $src);
Loading history...
58
59
        // Get width and height of the original image
60 2
        $width = imagesx($source_image);
61 2
        $height = imagesy($source_image);
62
63
        // Horizontal image
64 2
        if ($width > $height) {
65 2
            $desired_width = 400;
66 2
            $desired_height = floor($height * ($desired_width / $width));
67
        }
68
        // Vertical image
69
        else {
70 1
            $desired_height = 500;
71 1
            $desired_width = floor($width * ($desired_height / $height));
72
        }
73
74
        // Create a new, "virtual" image
75 2
        $virtual_image = imagecreatetruecolor($desired_width, $desired_height);
0 ignored issues
show
Bug introduced by
It seems like $desired_height can also be of type double; however, parameter $height of imagecreatetruecolor() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

75
        $virtual_image = imagecreatetruecolor($desired_width, /** @scrutinizer ignore-type */ $desired_height);
Loading history...
Bug introduced by
It seems like $desired_width can also be of type double; however, parameter $width of imagecreatetruecolor() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

75
        $virtual_image = imagecreatetruecolor(/** @scrutinizer ignore-type */ $desired_width, $desired_height);
Loading history...
76
77
        // Copy source image at a resized size
78 2
        imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);
0 ignored issues
show
Bug introduced by
It seems like $desired_width can also be of type double; however, parameter $dst_w of imagecopyresampled() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

78
        imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, /** @scrutinizer ignore-type */ $desired_width, $desired_height, $width, $height);
Loading history...
Bug introduced by
It seems like $desired_height can also be of type double; however, parameter $dst_h of imagecopyresampled() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

78
        imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, /** @scrutinizer ignore-type */ $desired_height, $width, $height);
Loading history...
79
80
        //Create the physical thumbnail image to its destination
81 2
        imagejpeg($virtual_image, $dest);
0 ignored issues
show
Bug introduced by
$dest of type array is incompatible with the type string expected by parameter $filename of imagejpeg(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

81
        imagejpeg($virtual_image, /** @scrutinizer ignore-type */ $dest);
Loading history...
82 2
    }
83
84
    /************************************************************************/
85
86
    /**
87
     *  Generate all the thumbnails of the gallery.
88
     *  @param string $images_dir        images dir on the server
89
     *  @param string $thumbs_dir        thumb dir on the server
90
     *  @param string $$thumbs_size
91
     *  @param array $image_files
92
     *  @return generate thumbnail files
0 ignored issues
show
Bug introduced by
The type DavideCasiraghi\ResponsiveGallery\generate was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
93
     **/
94 2
    public function generateThumbs($images_dir, $thumbs_dir, $thumbs_size, $image_files)
95
    {
96
        // Thumbnails size
97 2
        $thumbs_width = $thumbs_size['width'];
98 2
        $thumbs_height = $thumbs_size['height'];
99
100
        //  Create thumbs dir
101 2
        if (! is_dir($thumbs_dir)) {
102 1
            mkdir($thumbs_dir);
103
        }
104
105
        // Generate missing thumbs
106 2
        if (count($image_files)) {
107 2
            $index = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $index is dead and can be removed.
Loading history...
108 2
            foreach ($image_files as $index=>$file) {
109 2
                $index++;
110 2
                $thumbnail_image = $thumbs_dir.$file;
111 2
                if (! file_exists($thumbnail_image)) {
112 1
                    $extension = self::get_file_extension($thumbnail_image);
113 1
                    if ($extension) {
114
                        //echo $images_dir." ".$file." ".$thumbnail_image." ".$thumbs_width;
115 2
                        $this->generate_single_thumb_file($images_dir.$file, $thumbnail_image, $thumbs_width, $thumbs_height);
0 ignored issues
show
Bug introduced by
$thumbnail_image of type string is incompatible with the type array expected by parameter $dest of DavideCasiraghi\Responsi...ate_single_thumb_file(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

115
                        $this->generate_single_thumb_file($images_dir.$file, /** @scrutinizer ignore-type */ $thumbnail_image, $thumbs_width, $thumbs_height);
Loading history...
Bug introduced by
$images_dir . $file of type string is incompatible with the type array expected by parameter $src of DavideCasiraghi\Responsi...ate_single_thumb_file(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

115
                        $this->generate_single_thumb_file(/** @scrutinizer ignore-type */ $images_dir.$file, $thumbnail_image, $thumbs_width, $thumbs_height);
Loading history...
116
                    }
117
                }
118
            }
119
        }
120 2
    }
121
122
    /************************************************************************/
123
124
    /**
125
     *  Create images array.
126
     *  @param array $image_files           array with all the image names
127
     *  @param $gallery_url
128
     *  @return $ret    array with the images datas
0 ignored issues
show
Documentation Bug introduced by
The doc comment $ret at position 0 could not be parsed: Unknown type name '$ret' at position 0 in $ret.
Loading history...
129
     **/
130 2
    public function createImagesArray($image_file_names, $gallery_url, $dbImageDatas)
131
    {
132 2
        sort($image_file_names);  // Order by image name
133
134 2
        $ret = [];
135
136 2
        foreach ($image_file_names as $k => $image_file_name) {
137 2
            $ret[$k]['file_name'] = $image_file_name;
138 2
            $ret[$k]['file_path'] = $gallery_url.$image_file_name;
139 2
            $ret[$k]['thumb_path'] = $gallery_url.'thumb/'.$image_file_name;
140 2
            $ret[$k]['description'] = '';
141 2
            $ret[$k]['alt'] = '';
142 2
            $ret[$k]['video_link'] = null;
143
            
144 2
            if (! empty($dbImageDatas[$image_file_name])) {
145 1
                $ret[$k]['description'] = $dbImageDatas[$image_file_name]->description;
146 1
                $ret[$k]['alt'] = $dbImageDatas[$image_file_name]->alt;
147 2
                $ret[$k]['video_link'] = $dbImageDatas[$image_file_name]->video_link;
148
            }
149
        }
150
151 2
        return $ret;
152
    }
153
154
    /************************************************************************/
155
156
    /**
157
     *  Get images file names array.
158
     *  @param $images_dir           the images dir on the server
0 ignored issues
show
Bug introduced by
The type DavideCasiraghi\ResponsiveGallery\the was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
159
     *  @return array $ret           array containing all the images file names
160
     **/
161 4
    public function getImageFiles($images_dir)
162
    {
163 4
        $ret = $this->get_files($images_dir);
164
165 4
        return $ret;
166
    }
167
168
    /************************************************************************/
169
170
    /**
171
     *  Prepare the gallery HTML.
172
     *  @param array $images                        Images array [file_path, short_desc, long_desc]
173
     *  @param array $bootstrapDeviceImageWidth     array that contain the sizes of the images
174
     *                                              for the four kind of bootrap devices classes ()
175
     *                                              xs (phones), sm (tablets), md (desktops), and lg (larger desktops)
176
     *  @param ****array $desired_width     width of the thumbnail
0 ignored issues
show
Documentation Bug introduced by
The doc comment $desired_width at position 0 could not be parsed: Unknown type name '$desired_width' at position 0 in $desired_width.
Loading history...
177
     *  @return string $ret             the HTML to print on screen
178
     **/
179 2
    public function prepareGallery($images, $parameters)
180
    {
181
        // Animate box on hover
182 2
        $itemClass = 'animated';
183
184
        // The gallery HTML
185 2
        $ret = "<div class='responsiveGallery bricklayer' id='my-bricklayer' data-column-width='".$parameters['column_width']."' data-gutter='".$parameters['gutter']."'>";
186 2
        foreach ($images as $k => $image) {
187
            // Get item link
188 2
            $imageLink = ($image['video_link'] == null) ? $image['file_path'] : $image['video_link'];
189 2
            $videoPlayIcon = ($image['video_link'] == null) ? '' : "<i class='far fa-play-circle'></i>";
190
191 2
            $ret .= "<div class='box ".$itemClass."'>";
192 2
            $ret .= "<a href='".$imageLink."' data-fancybox='images' data-caption='".$image['description']."'>";
193 2
            $ret .= "<img src='".$image['thumb_path']."' alt='".$image['alt']."'/>";
194 2
            $ret .= $videoPlayIcon;
195 2
            $ret .= '</a>';
196 2
            $ret .= '</div>';
197
        }
198 2
        $ret .= '</div>';
199
200 2
        return $ret;
201
    }
202
203
    /************************************************************************/
204
205
    /**
206
     *  Returns files from dir.
207
     *  @param string $images_dir                 The images directory
208
     *  @param array $exts     the file types (actually doesn't work the thumb with png, it's to study why)
209
     *  @return array $files             the files array
210
     **/
211 4
    public function get_files($images_dir, $exts = ['jpg'])
212
    {
213 4
        $files = [];
214
215 4
        if ($handle = opendir($images_dir)) {
216 4
            while (false !== ($file = readdir($handle))) {
217 4
                $extension = strtolower($this->get_file_extension($file));
218 4
                if ($extension && in_array($extension, $exts)) {
219 4
                    $files[] = $file;
220
                }
221
            }
222 4
            closedir($handle);
223
        }
224
225 4
        return $files;
226
    }
227
228
    /************************************************************************/
229
230
    /**
231
     *  Returns a file's extension.
232
     *  @param string $file_name        the file name
233
     *  @return string                  the extension
234
     **/
235 5
    public static function get_file_extension($file_name)
236
    {
237 5
        return substr(strrchr($file_name, '.'), 1);
238
    }
239
240
    /************************************************************************/
241
242
    /**
243
     *  Find the gallery snippet occurances in the text.
244
     *  @param array $text        the text where to find the gallery snippets
245
     *  @return array $ret        the matches
246
     **/
247 2
    public function getGallerySnippetOccurrences($text)
248
    {
249 2
        $re = '/{\#
250
                \h+gallery
251
                \h+(src|column_width|gutter)=\[([^]]*)]
252
                \h+((?1))=\[([^]]*)]
253
                \h+((?1))=\[([^]]*)]
254
                \h*\#}/x';
255
256 2
        if (preg_match_all($re, $text, $matches, PREG_SET_ORDER, 0)) {
0 ignored issues
show
Unused Code introduced by
The call to preg_match_all() has too many arguments starting with DavideCasiraghi\ResponsiveGallery\PREG_SET_ORDER. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

256
        if (/** @scrutinizer ignore-call */ preg_match_all($re, $text, $matches, PREG_SET_ORDER, 0)) {

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
257 2
            return $matches;
258
        } else {
259 1
            return;
260
        }
261
    }
262
263
    /************************************************************************/
264
265
    /**
266
     *  Retrieve the datas from the package config file (published and edited by the user).
267
     *  @param none
268
     *  @return array $ret - the config parapeters
269
     **/
270 2
    public function getPhotoDatasFromDb()
271
    {
272 2
        $ret = GalleryImage::get()->keyBy('file_name');
273
        //dd($ret);
274 2
        return $ret;
275
    }
276
277
    /************************************************************************/
278
279
    /**
280
     *  Return the post body with the gallery HTML instead of the found snippet.
281
     *  @param array $file_name        the file name
282
     *  @return array $ret             the extension
283
     **/
284 1
    public function getGallery($postBody, $publicPath)
285
    {
286 1
        $matches = $this->getGallerySnippetOccurrences($postBody);
287
288 1
        foreach ($matches as $key => $single_gallery_matches) {
289 1
            $parameters = self::getGalleryParameters($single_gallery_matches, $publicPath);
290
291 1
            if (is_dir($parameters['images_dir'])) {
292
                // Get images file name array
293 1
                $image_files = $this->getImageFiles($parameters['images_dir']);
294
295 1
                if (! empty($image_files)) {
296 1
                    $this->generateThumbs($parameters['images_dir'], $parameters['thumbs_dir'], $parameters['thumbs_size'], $image_files);
297 1
                    $dbImageDatas = $this->getPhotoDatasFromDb();
298
299
                    // Create Images array [file_path, short_desc, long_desc]
300 1
                    $images = $this->createImagesArray($image_files, $parameters['gallery_url'], $dbImageDatas);
301
302
                    // Prepare Gallery HTML
303 1
                    $galleryHtml = $this->prepareGallery($images, $parameters);
304
                } else {
305 1
                    $galleryHtml = "<div class='alert alert-warning' role='alert'>The directory specified exist but it doesn't contain images</div>";
306
                }
307
            } else {
308 1
                $galleryHtml = "<div class='alert alert-warning' role='alert'>Image directory not found<br />".$parameters['images_dir'].'</div>';
309
            }
310
311
            // Replace the TOKEN found in the article with the generatd gallery HTML
312 1
            $postBody = str_replace($parameters['token'], $galleryHtml, $postBody);
313
        }
314
315 1
        return $postBody;
316
    }
317
}
318