getGallerySnippetOccurrences()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 1
dl 0
loc 13
ccs 5
cts 5
cp 1
crap 2
rs 10
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
     *  @param string $publicPath
15
     *  @return array $ret          The array containing the parameters
16
     **/
17 2
    public static function getGalleryParameters($matches, $publicPath)
18
    {
19 2
        $ret = [];
20
21
        // Get activation string parameters (from article)
22 2
        $ret['token'] = $matches[0];
23 2
        $subDir = $matches[2];
24 2
        $ret['column_width'] = $matches[4];
25 2
        $ret['gutter'] = $matches[6];
26
27
        // Directories
28 2
        $ret['images_dir'] = $publicPath.'/'.$subDir.'/';
29 2
        $ret['thumbs_dir'] = $publicPath.'/'.$subDir.'/thumb/';
30
31
        // Thumbnails size
32 2
        $ret['thumbs_size']['width'] = 300;
33 2
        $ret['thumbs_size']['height'] = 300;
34
35
        // URL variables
36 2
        $ret['gallery_url'] = $subDir.'/';
37 2
        $ret['thumb_url'] = $subDir.'/thumbs/';
38
39 2
        return $ret;
40
    }
41
42
    /************************************************************************/
43
44
    /**
45
     *  Generate a single thumbnail file from an image.
46
     *  @param array $src               path of the original image
47
     *  @param array $dest              path of the generated thumbnail
48
     *  @param array $desired_width     width of the thumbnail
49
     *  @param array $desired_height    height of the thumbnail
50
     *  @return void
51
     **/
52 2
    public function generate_single_thumb_file($src, $dest, $desired_width, $desired_height): void
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

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

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

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

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...
53
    {
54
        // Read the source image
55 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

55
        $source_image = imagecreatefromjpeg(/** @scrutinizer ignore-type */ $src);
Loading history...
56
57
        // Get width and height of the original image
58 2
        $width = imagesx($source_image);
0 ignored issues
show
Bug introduced by
It seems like $source_image can also be of type false; however, parameter $image of imagesx() does only seem to accept resource, 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

58
        $width = imagesx(/** @scrutinizer ignore-type */ $source_image);
Loading history...
59 2
        $height = imagesy($source_image);
0 ignored issues
show
Bug introduced by
It seems like $source_image can also be of type false; however, parameter $image of imagesy() does only seem to accept resource, 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

59
        $height = imagesy(/** @scrutinizer ignore-type */ $source_image);
Loading history...
60
61
        // Horizontal image
62 2
        if ($width > $height) {
63 2
            $desired_width = 400;
64 2
            $desired_height = floor($height * ($desired_width / $width));
65
        }
66
        // Vertical image
67
        else {
68 1
            $desired_height = 500;
69 1
            $desired_width = floor($width * ($desired_height / $height));
70
        }
71
72
        // Create a new, "virtual" image
73 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

73
        $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

73
        $virtual_image = imagecreatetruecolor(/** @scrutinizer ignore-type */ $desired_width, $desired_height);
Loading history...
74
75
        // Copy source image at a resized size
76 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_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

76
        imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, /** @scrutinizer ignore-type */ $desired_height, $width, $height);
Loading history...
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

76
        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 $source_image can also be of type false; however, parameter $src_image of imagecopyresampled() does only seem to accept resource, 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

76
        imagecopyresampled($virtual_image, /** @scrutinizer ignore-type */ $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);
Loading history...
Bug introduced by
It seems like $virtual_image can also be of type false; however, parameter $dst_image of imagecopyresampled() does only seem to accept resource, 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

76
        imagecopyresampled(/** @scrutinizer ignore-type */ $virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);
Loading history...
77
78
        //Create the physical thumbnail image to its destination
79 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

79
        imagejpeg($virtual_image, /** @scrutinizer ignore-type */ $dest);
Loading history...
Bug introduced by
It seems like $virtual_image can also be of type false; however, parameter $image of imagejpeg() does only seem to accept resource, 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

79
        imagejpeg(/** @scrutinizer ignore-type */ $virtual_image, $dest);
Loading history...
80 2
    }
81
82
    /************************************************************************/
83
84
    /**
85
     *  Generate all the thumbnails of the gallery.
86
     *  @param string $images_dir      Images dir on the server
87
     *  @param string $thumbs_dir      Thumb dir on the server
88
     *  @param string $thumbs_size
89
     *  @param array  $image_files
90
     *  @return void
91
     **/
92 2
    public function generateThumbs($images_dir, $thumbs_dir, $thumbs_size, $image_files): void
93
    {
94
        // Thumbnails size
95 2
        $thumbs_width = $thumbs_size['width'];
96 2
        $thumbs_height = $thumbs_size['height'];
97
98
        //  Create thumbs dir
99 2
        if (! is_dir($thumbs_dir)) {
100 1
            mkdir($thumbs_dir);
101
        }
102
103
        // Generate missing thumbs
104 2
        if (count($image_files)) {
105 2
            $index = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $index is dead and can be removed.
Loading history...
106 2
            foreach ($image_files as $index=>$file) {
107 2
                $index++;
108 2
                $thumbnail_image = $thumbs_dir.$file;
109 2
                if (! file_exists($thumbnail_image)) {
110 1
                    $extension = self::get_file_extension($thumbnail_image);
111 1
                    if ($extension) {
112 2
                        $this->generate_single_thumb_file($images_dir.$file, $thumbnail_image, $thumbs_width, $thumbs_height);
0 ignored issues
show
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

112
                        $this->generate_single_thumb_file(/** @scrutinizer ignore-type */ $images_dir.$file, $thumbnail_image, $thumbs_width, $thumbs_height);
Loading history...
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

112
                        $this->generate_single_thumb_file($images_dir.$file, /** @scrutinizer ignore-type */ $thumbnail_image, $thumbs_width, $thumbs_height);
Loading history...
113
                    }
114
                }
115
            }
116
        }
117 2
    }
118
119
    /************************************************************************/
120
121
    /**
122
     *  Create images array.
123
     *  @param array        $image_file_names  Array with all the image names
124
     *  @param string       $gallery_url
125
     *  @param GalleryImage $dbImageDatas
126
     *  @return array       $ret               Array with the images datas
127
     **/
128 2
    public function createImagesArray($image_file_names, $gallery_url, $dbImageDatas)
129
    {
130 2
        sort($image_file_names);  // Order by image name
131
132 2
        $ret = [];
133
134 2
        foreach ($image_file_names as $k => $image_file_name) {
135 2
            $ret[$k]['file_name'] = $image_file_name;
136 2
            $ret[$k]['file_path'] = $gallery_url.$image_file_name;
137 2
            $ret[$k]['thumb_path'] = $gallery_url.'thumb/'.$image_file_name;
138 2
            $ret[$k]['description'] = '';
139 2
            $ret[$k]['alt'] = '';
140 2
            $ret[$k]['video_link'] = null;
141
142 2
            if (! empty($dbImageDatas[$image_file_name])) {
143 1
                $ret[$k]['description'] = $dbImageDatas[$image_file_name]->description;
144 1
                $ret[$k]['alt'] = $dbImageDatas[$image_file_name]->alt;
145 2
                $ret[$k]['video_link'] = $dbImageDatas[$image_file_name]->video_link;
146
            }
147
        }
148
149 2
        return $ret;
150
    }
151
152
    /************************************************************************/
153
154
    /**
155
     *  Get images file names array.
156
     *  @param  string $images_dir   The images dir on the server
157
     *  @return array  $ret          All the images file names
158
     **/
159 4
    public function getImageFiles($images_dir)
160
    {
161 4
        $ret = $this->get_files($images_dir);
162
163 4
        return $ret;
164
    }
165
166
    /************************************************************************/
167
168
    /**
169
     *  Prepare the gallery HTML.
170
     *  @param array $images       Images array [file_path, short_desc, long_desc]
171
     *  @param array $parameters
172
     *  @return string $ret        The HTML to print on screen
173
     **/
174 2
    public function prepareGallery($images, $parameters)
175
    {
176
        // Animate image box on hover
177 2
        $itemClass = 'animated';
178
179
        // The gallery HTML
180 2
        $ret = "<div class='responsiveGallery bricklayer' id='my-bricklayer' data-column-width='".$parameters['column_width']."' data-gutter='".$parameters['gutter']."'>";
181 2
        foreach ($images as $k => $image) {
182
            // Get item link
183 2
            $imageLink = ($image['video_link'] == null) ? $image['file_path'] : $image['video_link'];
184 2
            $videoPlayIcon = ($image['video_link'] == null) ? '' : "<i class='far fa-play-circle'></i>";
185
186 2
            $ret .= "<div class='box ".$itemClass."'>";
187 2
            $ret .= "<a href='".$imageLink."' data-fancybox='images' data-caption='".$image['description']."'>";
188 2
            $ret .= "<img src='".$image['thumb_path']."' alt='".$image['alt']."'/>";
189 2
            $ret .= $videoPlayIcon;
190 2
            $ret .= '</a>';
191 2
            $ret .= '</div>';
192
        }
193 2
        $ret .= '</div>';
194
195 2
        return $ret;
196
    }
197
198
    /************************************************************************/
199
200
    /**
201
     *  Returns files from dir.
202
     *  @param string $images_dir  The images directory
203
     *  @param  array $exts        The file types (actually doesn't work the thumb with png, it's to study why)
204
     *  @return array $files       The files array
205
     **/
206 4
    public function get_files($images_dir, $exts = ['jpg'])
207
    {
208 4
        $files = [];
209
210 4
        if ($handle = opendir($images_dir)) {
211 4
            while (false !== ($file = readdir($handle))) {
212 4
                $extension = strtolower($this->get_file_extension($file));
213 4
                if ($extension && in_array($extension, $exts)) {
214 4
                    $files[] = $file;
215
                }
216
            }
217 4
            closedir($handle);
218
        }
219
220 4
        return $files;
221
    }
222
223
    /************************************************************************/
224
225
    /**
226
     *  Returns a file's extension.
227
     *  @param  string  $file_name   The file name
228
     *  @return string  $ret         The extension without dot
229
     **/
230 6
    public static function get_file_extension($file_name)
231
    {
232 6
        $ret = substr(strrchr($file_name, '.'), 1);
233
234 6
        return $ret;
235
    }
236
237
    /************************************************************************/
238
239
    /**
240
     *  Find the gallery snippet occurances in the text.
241
     *  @param array $text     The text where to find the gallery snippets
242
     *  @return array $ret     The matches
243
     **/
244 2
    public function getGallerySnippetOccurrences($text)
245
    {
246 2
        $re = '/{\#
247
                \h+gallery
248
                \h+(src|column_width|gutter)=\[([^]]*)]
249
                \h+((?1))=\[([^]]*)]
250
                \h+((?1))=\[([^]]*)]
251
                \h*\#}/x';
252
253 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

253
        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...
254 2
            return $matches;
255
        } else {
256 1
            return;
257
        }
258
    }
259
260
    /************************************************************************/
261
262
    /**
263
     *  Retrieve the datas from the package config file (published and edited by the user).
264
     *  @return array $ret - the config parapeters
265
     **/
266 2
    public function getPhotoDatasFromDb()
267
    {
268 2
        $ret = GalleryImage::get()->keyBy('file_name');
269
270 2
        return $ret;
271
    }
272
273
    /************************************************************************/
274
275
    /**
276
     *  Return the post body with the gallery HTML instead of the found snippet.
277
     *  @param array  $postBody       The text name
278
     *  @param string $publicPath
279
     *  @return array $ret            $postBody with the HTML Galleries
280
     **/
281 1
    public function getGallery($postBody, $publicPath)
282
    {
283 1
        $matches = $this->getGallerySnippetOccurrences($postBody);
284
285 1
        if ($matches) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $matches of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
286 1
            foreach ($matches as $key => $single_gallery_matches) {
287 1
                $parameters = self::getGalleryParameters($single_gallery_matches, $publicPath);
288
289 1
                if (is_dir($parameters['images_dir'])) {
290
                    // Get images file name array
291 1
                    $image_files = $this->getImageFiles($parameters['images_dir']);
292
293 1
                    if (! empty($image_files)) {
294 1
                        $this->generateThumbs($parameters['images_dir'], $parameters['thumbs_dir'], $parameters['thumbs_size'], $image_files);
0 ignored issues
show
Bug introduced by
$parameters['thumbs_size'] of type array is incompatible with the type string expected by parameter $thumbs_size of DavideCasiraghi\Responsi...ctory::generateThumbs(). ( Ignorable by Annotation )

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

294
                        $this->generateThumbs($parameters['images_dir'], $parameters['thumbs_dir'], /** @scrutinizer ignore-type */ $parameters['thumbs_size'], $image_files);
Loading history...
295 1
                        $dbImageDatas = $this->getPhotoDatasFromDb();
296
297
                        // Create Images array [file_path, short_desc, long_desc]
298 1
                        $images = $this->createImagesArray($image_files, $parameters['gallery_url'], $dbImageDatas);
0 ignored issues
show
Bug introduced by
$dbImageDatas of type array is incompatible with the type DavideCasiraghi\Responsi...ery\Models\GalleryImage expected by parameter $dbImageDatas of DavideCasiraghi\Responsi...ry::createImagesArray(). ( Ignorable by Annotation )

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

298
                        $images = $this->createImagesArray($image_files, $parameters['gallery_url'], /** @scrutinizer ignore-type */ $dbImageDatas);
Loading history...
299
300
                        // Prepare Gallery HTML
301 1
                        $galleryHtml = $this->prepareGallery($images, $parameters);
302
                    } else {
303 1
                        $galleryHtml = "<div class='alert alert-warning' role='alert'>The directory specified exist but it doesn't contain images</div>";
304
                    }
305
                } else {
306 1
                    $galleryHtml = "<div class='alert alert-warning' role='alert'>Image directory not found<br />".$parameters['images_dir'].'</div>';
307
                }
308
309
                // Replace the TOKEN found in the article with the generatd gallery HTML
310 1
                $postBody = str_replace($parameters['token'], $galleryHtml, $postBody);
311
            }
312
        }
313
314 1
        return $postBody;
315
    }
316
}
317