Passed
Branch master (145c86)
by Whallysson
01:22
created

Gd::toImage()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 1
dl 0
loc 17
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace CodeBlog\ToWebP\Convert\Converters;
4
5
use CodeBlog\ToWebP\AbstractConverter;
6
use Exception;
7
8
/** @param bool */
9
define('PHPWEBP_GD_PNG', false);
10
11
/**
12
 * Class Gd
13
 *
14
 * Converts an image to WebP via GD Graphics (Draw)
15
 *
16
 * @author Whallysson Avelino <https://github.com/whallysson>
17
 * @package CodeBlog\ToWebP\Convert\Converters
18
 */
19
class Gd extends AbstractConverter
20
{
21
    /**
22
     * @return bool|mixed
23
     * @throws Exception
24
     */
25
    public function checkRequirements()
26
    {
27
        if (!extension_loaded('gd')) {
28
            throw new Exception('Required GD extension is not available.');
29
        }
30
31
        if (!function_exists('imagewebp')) {
32
            throw new Exception('Required imagewebp() function is not available.');
33
        }
34
35
        return true;
36
    }
37
38
    /**
39
     * @return bool|mixed|resource
40
     */
41
    public function convert()
42
    {
43
        try {
44
            $this->checkRequirements();
45
            switch ($this->extension) {
46
                case 'png':
47
                    if (defined('PHPWEBP_GD_PNG') && PHPWEBP_GD_PNG) {
48
                        return imagecreatefrompng($this->source);
49
                    } else {
50
                        throw new Exception('PNG file conversion failed.');
51
                    }
52
                    break;
53
                default:
54
                    $image = imagecreatefromjpeg($this->source);
55
            }
56
            // Checks if either imagecreatefromjpeg() or imagecreatefrompng() returned false
57
            if ($image === false) {
58
                throw new Exception('Either imagecreatefromjpeg or imagecreatefrompng failed');
59
            }
60
        } catch (Exception $e) {
61
            return false; // TODO: `throw` custom \Exception $e & handle it smoothly on top-level.
62
        }
63
        return $this->toImage($image);
64
    }
65
66
    /**
67
     * @param $image
68
     * @return bool
69
     */
70
    private function toImage($image)
71
    {
72
        $success = imagewebp($image, $this->destination, $this->quality);
73
74
        /*
75
         * This hack solves an `imagewebp` bug
76
         * See https://stackoverflow.com/questions/30078090/imagewebp-php-creates-corrupted-webp-files
77
         *
78
         */
79
80
        if (filesize($this->destination) % 2 == 1) {
81
            file_put_contents($this->destination, "\0", FILE_APPEND);
82
        }
83
84
        imagedestroy($image);
85
86
        return $success;
87
    }
88
}
89