-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathImageFormatter.php
More file actions
66 lines (55 loc) · 1.61 KB
/
ImageFormatter.php
File metadata and controls
66 lines (55 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<?php
declare(strict_types = 1);
namespace Middlewares\ErrorFormatter;
use Throwable;
class ImageFormatter extends AbstractFormatter
{
protected $contentTypes = [
'image/gif',
'image/jpeg',
'image/png',
'image/webp',
];
protected function format(Throwable $error, string $contentType): string
{
ob_start();
$image = $this->createImage($error);
switch ($contentType) {
case 'image/gif':
imagegif($image);
break;
case 'image/jpeg':
imagejpeg($image);
break;
case 'image/png':
imagepng($image);
break;
case 'image/webp':
imagewebp($image);
break;
}
return (string) ob_get_clean();
}
/**
* Create an image resource from an error
*
* @return resource
*/
private function createImage(Throwable $error)
{
$type = get_class($error);
$code = $error->getCode();
$message = $error->getMessage();
$size = 200;
$image = imagecreatetruecolor($size, $size);
$textColor = imagecolorallocate($image, 255, 255, 255);
/* @phpstan-ignore-next-line */
imagestring($image, 5, 10, 10, "$type $code", $textColor);
/* @phpstan-ignore-next-line */
foreach (str_split($message, intval($size / 10)) as $line => $text) {
/* @phpstan-ignore-next-line */
imagestring($image, 5, 10, ($line * 18) + 28, $text, $textColor);
}
return $image;
}
}