diff --git a/app/Jobs/GenerateSocialShareImage.php b/app/Jobs/GenerateSocialShareImage.php index e7c60489a..ff3bd7b70 100644 --- a/app/Jobs/GenerateSocialShareImage.php +++ b/app/Jobs/GenerateSocialShareImage.php @@ -12,7 +12,7 @@ final class GenerateSocialShareImage { const TEXT_X_POSITION = 50; - const TEXT_Y_POSITION = 150; + const TEXT_Y_BASE_POSITION = 90; const TEXT_COLOUR = '#161e2e'; @@ -32,18 +32,32 @@ public function handle(): Response $text = wordwrap($this->article->title(), self::CHARACTERS_PER_LINE); return Cache::remember( - 'articleSocialImage-'.$this->article->id, + 'articleSocialImage-' . $this->article->id, now()->addDay(), - fn () => response( - $image->read(resource_path('images/'.self::TEMPLATE)) - ->text($text, self::TEXT_X_POSITION, self::TEXT_Y_POSITION, function ($font) { - $font->file(resource_path('fonts/'.self::FONT)); - $font->size(self::FONT_SIZE); - $font->color(self::TEXT_COLOUR); - }) + fn() => response( + $image->read(resource_path('images/' . self::TEMPLATE)) + ->text( + $text, + self::TEXT_X_POSITION, + self::calculateTextYPosition($text), + function ($font) { + $font->file(resource_path('fonts/' . self::FONT)); + $font->size(self::FONT_SIZE); + $font->color(self::TEXT_COLOUR); + } + ) ->toPng() - )->header('Content-Type', 'image/png') + ) + ->header('Content-Type', 'image/png') ->header('Cache-Control', 'max-age=86400, public') ); } + + private function calculateTextYPosition(string $text): int + { + $noOfLinesInText = substr_count($text, "\n"); + + return self::TEXT_Y_BASE_POSITION + + ((self::FONT_SIZE * $noOfLinesInText) - $noOfLinesInText); + } } diff --git a/tests/Integration/Jobs/GenerateSocialShareImageTest.php b/tests/Integration/Jobs/GenerateSocialShareImageTest.php index b966dd5fc..57deaa5f9 100644 --- a/tests/Integration/Jobs/GenerateSocialShareImageTest.php +++ b/tests/Integration/Jobs/GenerateSocialShareImageTest.php @@ -24,7 +24,7 @@ expect( Pixelmatch::new( $generatedSocialShareImagePath, - __DIR__.'/stubs/generate_social_share_image.png' + base_path('tests/stubs/generate_social_share_image.png') )->matches() )->toBeTrue(); diff --git a/tests/stubs/generate_social_share_image.png b/tests/stubs/generate_social_share_image.png index a915202f6..6f46569d3 100644 Binary files a/tests/stubs/generate_social_share_image.png and b/tests/stubs/generate_social_share_image.png differ