Skip to content

Commit 98a450f

Browse files
authoredNov 9, 2022
Merge pull request #5 from davetha/master
Add curl option support in Image class
2 parents 16ed5da + 64ac366 commit 98a450f

File tree

1 file changed

+21
-6
lines changed

1 file changed

+21
-6
lines changed
 

‎src/Image.php

+21-6
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
*/
1313
class Image
1414
{
15+
1516
const ALIGN_LEFT = 'left';
1617
const ALIGN_CENTER = 'center';
1718
const ALIGN_RIGHT = 'right';
@@ -284,27 +285,41 @@ public function base64(string $base64): Image
284285
* (Static method) Open image from URL with cURL.
285286
*
286287
* @param string $url Url of the image file
288+
* @param array $curlOptions cURL options
289+
* @param bool $failOnError If true, throw an exception if the url cannot be loaded
287290
* @return Image Return Image instance
288291
*/
289-
public static function fromCurl(string $url): Image
292+
public static function fromCurl(string $url, array $curlOptions = [], bool $failOnError = false): Image
290293
{
291-
return (new Image)->curl($url);
294+
return (new Image)->curl($url, $curlOptions, $failOnError);
292295
}
293296

294297
/**
295298
* Open image from URL with cURL.
296299
*
297300
* @param string $url Url of the image file
301+
* @param array $curlOptions cURL options
302+
* @param bool $failOnError If true, throw an exception if the url cannot be loaded
298303
* @return $this Fluent interface
299304
*/
300-
public function curl(string $url): Image
305+
public function curl(string $url, array $curlOptions = [], bool $failOnError = false): Image
301306
{
307+
$defaultCurlOptions = [
308+
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:106.0) Gecko/20100101 Firefox/106.0',
309+
CURLOPT_RETURNTRANSFER => 1,
310+
CURLOPT_TIMEOUT => 5,
311+
];
312+
302313
$curl = curl_init();
303314
curl_setopt($curl, CURLOPT_URL, $url);
304-
curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101 Firefox/91.0');
305-
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
306-
curl_setopt($curl, CURLOPT_TIMEOUT, 5);
315+
curl_setopt_array($curl, $defaultCurlOptions + $curlOptions);
316+
307317
$image = curl_exec($curl);
318+
319+
if($failOnError && curl_errno($curl)){
320+
throw new \Exception(curl_error($curl));
321+
}
322+
308323
curl_close($curl);
309324

310325
if ($image === false) {

0 commit comments

Comments
 (0)
Please sign in to comment.