Completed
Push — master ( 92de9c...ca5a09 )
by Renato
04:31
created

ImagineImagick::isBinary()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 1
dl 0
loc 9
ccs 0
cts 8
cp 0
crap 12
rs 9.9666
c 0
b 0
f 0
1
<?php
2
3
namespace NwLaravel\FileStorage;
4
5
use Imagick;
6
use ImagickPixel;
7
8
class ImagineImagick implements Imagine
9
{
10
    /**
11
     * @var Imagick
12
     */
13
    protected $image;
14
15
    /**
16
     * Construct
17
     *
18
     * @param string|blob $data
19
     */
20
    public function __construct($data)
21
    {
22
        if ($this->isBinary($data)) {
23
            $pathTmp = tempnam(sys_get_temp_dir(), 'img');
24
            file_put_contents($pathTmp, $data);
25
            $this->image = new Imagick($pathTmp);
26
            @unlink($pathTmp);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
27
        } else {
28
            $this->image = new Imagick($data);
29
        }
30
    }
31
32
    /**
33
     * Determines if current source data is binary data
34
     *
35
     * @return boolean
36
     */
37
    protected function isBinary($data)
38
    {
39
        if (is_string($data)) {
40
            $mime = finfo_buffer(finfo_open(FILEINFO_MIME_TYPE), $data);
41
            return (substr($mime, 0, 4) != 'text' && $mime != 'application/x-empty');
42
        }
43
44
        return false;
45
    }
46
47
    /**
48
     * Execute in Canvas
49
     *
50
     * @param \Closure $callback
51
     *
52
     * @return Imagine
53
     */
54
    protected function execute($callback)
55
    {
56
        $format = strtolower($this->image->getImageFormat());
57
58
        if ($format == 'gif') {
59
          $this->image = $this->image->coalesceImages();
60
          do {
61
              $callback($this->image);
62
          } while ($this->image->nextImage());
63
64
          $this->image = $this->image->deconstructImages();
65
        } else {
66
          $callback($this->image);
67
        }
68
69
        return $this;
70
    }
71
72
    /**
73
     * Filesize
74
     *
75
     * @return int
76
     */
77
    public function filesize()
78
    {
79
        return $this->image->getImageLength();
80
    }
81
82
    /**
83
     * Define Resize
84
     *
85
     * @param int     $maxWidth
86
     * @param int     $maxHeight
87
     * @param boolean $force
88
     *
89
     * @return Imagine
90
     */
91
    public function resize($maxWidth, $maxHeight, $force = false)
92
    {
93
        return $this->execute(function ($image) use ($maxWidth, $maxHeight, $force) {
94
            $width = $maxWidth;
95
            $height = $maxHeight;
96
            $imageWidth = $image->getImageWidth();
97
            $imageHeight = $image->getImageHeight();
98
99
            if(($maxWidth && $imageWidth > $maxWidth) || !$maxHeight) {
100
                $height = floor(($imageHeight/$imageWidth)*$maxWidth);
101
                if (!$height) {
102
                    $height = $imageHeight;
103
                }
104
105
            } else if(($maxHeight && $imageHeight > $maxHeight) || !$maxWidth) {
106
                $width = floor(($imageWidth/$imageHeight)*$maxHeight);
107
                if (!$width) {
108
                    $width = $imageWidth;
109
                }
110
            }
111
112
            $image->scaleImage($width, $height, !$force);
113
        });
114
    }
115
116
    /**
117
     * Opacity
118
     *
119
     * @return Imagine
120
     */
121
    public function opacity($opacity)
122
    {
123
        $opacity = intval($opacity);
124
125
        if ($opacity > 0 && $opacity < 100) {
126
            $this->execute(function ($image) use ($opacity) {
127
                $image->setImageOpacity($opacity/100);
128
            });
129
        }
130
131
        return $this;
132
    }
133
134
    /**
135
     * Watermark
136
     *
137
     * @param string  $path
138
     * @param string  $position
139
     * @param integer $opacity
140
     *
141
     * @return Imagine
142
     */
143
    public function watermark($path, $position = 'center', $opacity = null)
144
    {
145
        if ($this->isImage($path)) {
146
            $watermark = new \Imagick($path);
147
148
            $opacity = intval($opacity);
149
            if ($opacity > 0 && $opacity < 100) {
150
                $watermark->setImageOpacity($opacity/100);
151
            }
152
153
            $self = $this;
154
155
            $this->execute(function ($image) use ($watermark, $position, $self) {
156
                $self->watermarkCanvas($image, $watermark, $position);
157
            });
158
        }
159
160
        return $this;
161
    }
162
163
    protected function watermarkCanvas(Imagick $image, Imagick $watermark, $position = 'center')
164
    {
165
        // how big are the images?
166
        $iWidth = $image->getImageWidth();
167
        $iHeight = $image->getImageHeight();
168
        $wWidth = $watermark->getImageWidth();
169
        $wHeight = $watermark->getImageHeight();
170
171
        if ($iHeight < $wHeight || $iWidth < $wWidth) {
172
          // resize the watermark
173
          $watermark->scaleImage($iWidth, $iHeight, true);
174
175
          // get new size
176
          $wWidth = $watermark->getImageWidth();
177
          $wHeight = $watermark->getImageHeight();
178
        }
179
180
        $xOffset = 0;
0 ignored issues
show
Unused Code introduced by
$xOffset is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
181
        $yOffset = 0;
0 ignored issues
show
Unused Code introduced by
$yOffset is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
182
183
        switch ($position) {
184
          case 'center':
185
          default:
186
            $x = ($iWidth - $wWidth) / 2;
187
            $y = ($iHeight - $wHeight) / 2;
188
            break;
189
          case 'topLeft':
0 ignored issues
show
Unused Code introduced by
case 'topLeft': $x =... = $yOffset; break; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
190
            $x = $xOffset;
191
            $y = $yOffset;
192
            break;
193
          case 'top':
194
          case 'topCenter':
195
            $x = ($iWidth - $wWidth) / 2;
196
            $y = $yOffset;
197
            break;
198
          case 'topRight':
199
            $x = $iWidth - $wWidth - $xOffset;
200
            $y = $yOffset;
201
            break;
202
          case 'right':
203
          case 'rightCenter':
204
            $x = $iWidth - $wWidth - $xOffset;
205
            $y = ($iHeight - $wHeight) / 2;
206
            break;
207
          case 'bottomRight':
208
            $x = $iWidth - $wWidth - $xOffset;
209
            $y = $iHeight - $wHeight - $yOffset;
210
            break;
211
          case 'bottom':
212
          case 'bottomCenter':
213
            $x = ($iWidth - $wWidth) / 2;
214
            $y = $iHeight - $wHeight - $yOffset;
215
            break;
216
          case 'bottomLeft':
217
            $x = $xOffset;
218
            $y = $iHeight - $wHeight - $yOffset;
219
            break;
220
          case 'left':
221
          case 'leftCenter':
222
            $x = $xOffset;
223
            $y = ($iHeight - $wHeight) / 2;
224
            break;
225
        }
226
227
        $image->compositeImage($watermark, Imagick::COMPOSITE_OVER, $x, $y);
228
    }
229
230
    /**
231
     * Is Image
232
     *
233
     * @param string $path
234
     *
235
     * @return boolean
236
     */
237
    protected function isImage($path)
238
    {
239
        return (bool) ($path && is_file($path) && strpos(mime_content_type($path), 'image/')===0);
240
    }
241
242
    /**
243
     * Crop
244
     *
245
     * @param integer $width
246
     * @param integer $height
247
     * @param integer $x
248
     * @param integer $y
249
     *
250
     * @return binary
251
     */
252
    public function crop($width, $height, $x, $y)
253
    {
254
        return $this->execute(function ($image) use ($width, $height, $x, $y) {
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->execute(fu..., $height, $x, $y); }); (NwLaravel\FileStorage\Imagine) is incompatible with the return type declared by the interface NwLaravel\FileStorage\Imagine::crop of type NwLaravel\FileStorage\binary.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
255
            $image->cropImage($width, $height, $x, $y);
256
        });
257
    }
258
259
    /**
260
     * Rotate Image
261
     *
262
     * @param integer $angle
263
     *
264
     * @return binary
265
     */
266
    public function rotate($angle)
267
    {
268
        $angle = intval($angle);
269
270
        if ($angle > -360 && $angle < 360) {
271
            $this->execute(function ($image) use ($angle) {
272
                $image->rotateImage('#ffffff', $angle);
273
            });
274
        }
275
276
        return $this;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this; (NwLaravel\FileStorage\ImagineImagick) is incompatible with the return type declared by the interface NwLaravel\FileStorage\Imagine::rotate of type NwLaravel\FileStorage\binary.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
277
    }
278
279
    /**
280
     * Strip Profiles
281
     *
282
     * @param string $except
0 ignored issues
show
Bug introduced by
There is no parameter named $except. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
283
     *
284
     * @return this
285
     */
286
    public function stripProfiles()
287
    {
288
        $profiles = $this->image->getImageProfiles('icc', true);
289
290
        $this->image->stripImage();
291
292
        if(!empty($profiles))
293
            $this->image->profileImage('icc', $profiles['icc']);
294
295
        return $this;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this; (NwLaravel\FileStorage\ImagineImagick) is incompatible with the return type declared by the interface NwLaravel\FileStorage\Imagine::stripProfiles of type NwLaravel\FileStorage\this.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
296
    }
297
298
    /**
299
     * Encode
300
     *
301
     * @param string  $format
302
     * @param integer $quality
303
     *
304
     * @return binary
305
     */
306
    public function encode($format = null, $quality = null)
307
    {
308
        return $this->image->getImagesBlob();
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->image->getImagesBlob(); (string) is incompatible with the return type declared by the interface NwLaravel\FileStorage\Imagine::encode of type NwLaravel\FileStorage\binary.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
309
    }
310
311
    /**
312
     * Save
313
     *
314
     * @param string  $path
315
     * @param integer $quality
316
     *
317
     * @return binary
318
     */
319
    public function save($path, $quality = null)
320
    {
321
        $quality = intval($quality);
322
        if ($quality > 0 && $quality <= 100) {
323
            $this->image->setImageCompressionQuality($quality);
324
        }
325
        $this->image->writeImage($path);
326
327
        return $this;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this; (NwLaravel\FileStorage\ImagineImagick) is incompatible with the return type declared by the interface NwLaravel\FileStorage\Imagine::save of type NwLaravel\FileStorage\binary.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
328
    }
329
}
330