Skip to content

Commit 1ec3937

Browse files
committed
catch error cases when generating OG images
1 parent d8dd33e commit 1ec3937

1 file changed

Lines changed: 19 additions & 11 deletions

File tree

codepoints.net/lib/Controller/OGImage.php

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -16,24 +16,26 @@ final class OGImage extends Controller {
1616
*/
1717
#[\Override]
1818
public function __invoke($match, Array $env) : string {
19-
$cp = Codepoint::getCached($env['db']->getOne('SELECT cp, gc, name
20-
FROM codepoints
21-
WHERE cp = ?', hexdec($match[1])), $env['db']);
22-
23-
/* send an expiry of 1 year. This mirrors the Apache config for the
24-
* cached files. */
25-
$cache_duration = 365*24*60*60;
2619
header('Content-Type: image/png');
27-
header('Cache-Control: public, max-age='.$cache_duration);
28-
header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + $cache_duration));
20+
/* in the error case we send a 1x1 black pixel PNG w/o caching headers */
2921

30-
/** @var ?Array{width: int, height: int, image: string} */
22+
/** @var Array{cp: int, gc: string, name: string}|false */
23+
$cp_data = $env['db']->getOne('SELECT cp, gc, name
24+
FROM codepoints
25+
WHERE cp = ?', hexdec($match[1]));
26+
if (! $cp_data) {
27+
http_response_code(404);
28+
return base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQAAAAA3bvkkAAAACklEQVR4AWNgAAAAAgABc3UBGAAAAABJRU5ErkJggg==');
29+
}
30+
$cp = Codepoint::getCached($cp_data, $env['db']);
31+
32+
/** @var Array{width: int, height: int, image: string}|false */
3133
$dbimage = $env['db']->getOne('SELECT width, height, image
3234
FROM codepoint_image
3335
WHERE cp = ?', get_printable_codepoint($cp->id, $cp->gc));
3436
if (! $dbimage) {
3537
http_response_code(404);
36-
return '';
38+
return base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQAAAAA3bvkkAAAACklEQVR4AWNgAAAAAgABc3UBGAAAAABJRU5ErkJggg==');
3739
}
3840
$svg = (string)preg_replace(
3941
'/viewBox="[^"]+"/',
@@ -81,6 +83,12 @@ public function __invoke($match, Array $env) : string {
8183
* their place in the docroot */
8284
$canonical = str_pad(strtoupper(dechex($cp->id)), 4, '0', STR_PAD_LEFT);
8385
$img->writeImage(dirname(dirname(__DIR__)).'/image/og-'.$canonical.'.png');
86+
87+
/* send an expiry of 1 year. This mirrors the Apache config for the
88+
* cached files. */
89+
$cache_duration = 365*24*60*60;
90+
header('Cache-Control: public, max-age='.$cache_duration);
91+
header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + $cache_duration));
8492
return $img->getImageBlob();
8593
}
8694
}

0 commit comments

Comments
 (0)