• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

Cecilapp / Cecil / 12140629565

03 Dec 2024 01:25PM UTC coverage: 83.433% (-0.01%) from 83.447%
12140629565

push

github

ArnaudLigny
fix: router headers

2941 of 3525 relevant lines covered (83.43%)

0.83 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

68.92
/src/Assets/Image.php
1
<?php
2

3
declare(strict_types=1);
4

5
/*
6
 * This file is part of Cecil.
7
 *
8
 * Copyright (c) Arnaud Ligny <arnaud@ligny.fr>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13

14
namespace Cecil\Assets;
15

16
use Cecil\Exception\RuntimeException;
17
use Intervention\Image\Encoders\AutoEncoder;
18
use Intervention\Image\ImageManager;
19

20
class Image
21
{
22
    /**
23
     * Create new manager instance with desired driver.
24
     */
25
    private static function manager(): ImageManager
26
    {
27
        if (\extension_loaded('gd') && \function_exists('gd_info')) {
1✔
28
            return ImageManager::gd();
1✔
29
        }
30
        if (\extension_loaded('imagick') && class_exists('Imagick')) {
×
31
            return ImageManager::imagick();
×
32
        }
33

34
        throw new RuntimeException('PHP GD or Imagick extension is required.');
×
35
    }
36

37
    /**
38
     * Resize an image Asset.
39
     *
40
     * @throws RuntimeException
41
     */
42
    public static function resize(Asset $asset, int $width, int $quality): string
43
    {
44
        try {
45
            // is image?
46
            if (!self::isImage($asset)) {
1✔
47
                throw new RuntimeException(\sprintf('Not an image.'));
×
48
            }
49
            // creates image object from source
50
            $image = self::manager()->read($asset['content_source']);
1✔
51
            // resizes to $width with constraint the aspect-ratio and unwanted upsizing
52
            $image->scaleDown(width: $width);
1✔
53
            // return image data
54
            return (string) $image->encodeByMediaType($asset['subtype'], /** @scrutinizer ignore-type */ progressive: true, /** @scrutinizer ignore-type */ interlaced: false, quality: $quality);
1✔
55
        } catch (\Exception $e) {
×
56
            throw new RuntimeException(\sprintf('Not able to resize "%s": %s', $asset['path'], $e->getMessage()));
×
57
        }
58
    }
59

60
    /**
61
     * Converts an image Asset to the target format.
62
     *
63
     * @throws RuntimeException
64
     */
65
    public static function convert(Asset $asset, string $format, int $quality): string
66
    {
67
        try {
68
            if ($asset['type'] !== 'image') {
1✔
69
                throw new RuntimeException(\sprintf('Not an image.'));
×
70
            }
71
            $image = self::manager()->read($asset['content']);
1✔
72

73
            if (!\function_exists("image$format")) {
1✔
74
                throw new RuntimeException(\sprintf('Function "image%s" is not available.', $format));
×
75
            }
76

77
            return (string) $image->encodeByExtension($format, /** @scrutinizer ignore-type */ progressive: true, /** @scrutinizer ignore-type */ interlaced: false, quality: $quality);
1✔
78
        } catch (\Exception $e) {
×
79
            throw new RuntimeException(\sprintf('Not able to convert "%s": %s', $asset['path'], $e->getMessage()));
×
80
        }
81
    }
82

83
    /**
84
     * Returns the Data URL (encoded in Base64).
85
     *
86
     * @throws RuntimeException
87
     */
88
    public static function getDataUrl(Asset $asset, int $quality): string
89
    {
90
        try {
91
            // is image?
92
            if (!self::isImage($asset)) {
1✔
93
                throw new RuntimeException(\sprintf('Not an image.'));
×
94
            }
95
            $image = self::manager()->read($asset['content']);
1✔
96

97
            return (string) $image->encode(new AutoEncoder(quality: $quality))->toDataUri();
1✔
98
        } catch (\Exception $e) {
×
99
            throw new RuntimeException(\sprintf('Can\'t get Data URL of "%s": %s', $asset['path'], $e->getMessage()));
×
100
        }
101
    }
102

103
    /**
104
     * Returns the dominant RGB color of an image asset.
105
     *
106
     * @throws RuntimeException
107
     */
108
    public static function getDominantColor(Asset $asset): string
109
    {
110
        try {
111
            // is image?
112
            if (!self::isImage($asset)) {
1✔
113
                throw new RuntimeException(\sprintf('Not an image.'));
×
114
            }
115
            $assetColor = clone $asset;
1✔
116
            $assetColor = $assetColor->resize(100);
1✔
117
            $image = self::manager()->read($assetColor['content']);
1✔
118

119
            return $image->pickColor(0, 0)->toString();
1✔
120
        } catch (\Exception $e) {
×
121
            throw new RuntimeException(\sprintf('Can\'t get dominant color of "%s": %s', $asset['path'], $e->getMessage()));
×
122
        }
123
    }
124

125
    /**
126
     * Returns a Low Quality Image Placeholder (LQIP) as data URL.
127
     *
128
     * @throws RuntimeException
129
     */
130
    public static function getLqip(Asset $asset): string
131
    {
132
        try {
133
            if ($asset['type'] !== 'image') {
1✔
134
                throw new RuntimeException(\sprintf('Not an image.'));
×
135
            }
136
            $assetLqip = clone $asset;
1✔
137
            $assetLqip = $assetLqip->resize(100);
1✔
138
            $image = self::manager()->read($assetLqip['content']);
1✔
139

140
            return (string) $image->blur(50)->encode()->toDataUri();
1✔
141
        } catch (\Exception $e) {
×
142
            throw new RuntimeException(\sprintf('can\'t create LQIP of "%s": %s', $asset['path'], $e->getMessage()));
×
143
        }
144
    }
145

146
    /**
147
     * Build the `srcset` attribute for responsive images.
148
     * e.g.: `srcset="/img-480.jpg 480w, /img-800.jpg 800w"`.
149
     *
150
     * @throws RuntimeException
151
     */
152
    public static function buildSrcset(Asset $asset, array $widths): string
153
    {
154
        if ($asset['type'] !== 'image') {
1✔
155
            throw new RuntimeException(\sprintf('can\'t build "srcset" of "%s": it\'s not an image file.', $asset['path']));
×
156
        }
157

158
        $srcset = '';
1✔
159
        $widthMax = 0;
1✔
160
        foreach ($widths as $width) {
1✔
161
            if ($asset['width'] < $width) {
1✔
162
                break;
1✔
163
            }
164
            $img = $asset->resize($width);
1✔
165
            $srcset .= \sprintf('%s %sw, ', (string) $img, $width);
1✔
166
            $widthMax = $width;
1✔
167
        }
168
        // adds source image
169
        if (!empty($srcset) && ($asset['width'] < max($widths) && $asset['width'] != $widthMax)) {
1✔
170
            $srcset .= \sprintf('%s %sw', (string) $asset, $asset['width']);
1✔
171
        }
172

173
        return rtrim($srcset, ', ');
1✔
174
    }
175

176
    /**
177
     * Returns the value of the "sizes" attribute corresponding to the configured class.
178
     */
179
    public static function getSizes(string $class, array $sizes = []): string
180
    {
181
        $result = '';
1✔
182
        $classArray = explode(' ', $class);
1✔
183
        foreach ($classArray as $class) {
1✔
184
            if (\array_key_exists($class, $sizes)) {
1✔
185
                $result = $sizes[$class] . ', ';
1✔
186
            }
187
        }
188
        if (!empty($result)) {
1✔
189
            return trim($result, ', ');
1✔
190
        }
191

192
        return $sizes['default'] ?? '100vw';
1✔
193
    }
194

195
    /**
196
     * Checks if an asset is an animated GIF.
197
     */
198
    public static function isAnimatedGif(Asset $asset): bool
199
    {
200
        // an animated GIF contains multiple "frames", with each frame having a header made up of:
201
        // 1. a static 4-byte sequence (\x00\x21\xF9\x04)
202
        // 2. 4 variable bytes
203
        // 3. a static 2-byte sequence (\x00\x2C)
204
        $count = preg_match_all('#\x00\x21\xF9\x04.{4}\x00[\x2C\x21]#s', (string) $asset['content_source']);
1✔
205

206
        return $count > 1;
1✔
207
    }
208

209
    /**
210
     * Returns true if asset is a SVG.
211
     */
212
    public static function isSVG(Asset $asset): bool
213
    {
214
        return \in_array($asset['subtype'], ['image/svg', 'image/svg+xml']) || $asset['ext'] == 'svg';
1✔
215
    }
216

217
    /**
218
     * Asset is a valid image?
219
     */
220
    public static function isImage(Asset $asset): bool
221
    {
222
        if ($asset['type'] !== 'image' || self::isSVG($asset)) {
1✔
223
            return false;
×
224
        }
225

226
        return true;
1✔
227
    }
228

229
    /**
230
     * Returns SVG attributes.
231
     *
232
     * @return \SimpleXMLElement|false
233
     */
234
    public static function getSvgAttributes(Asset $asset)
235
    {
236
        if (!self::isSVG($asset)) {
1✔
237
            return false;
×
238
        }
239

240
        if (false === $xml = simplexml_load_string($asset['content_source'] ?? '')) {
1✔
241
            return false;
×
242
        }
243

244
        return $xml->attributes();
1✔
245
    }
246
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc