Skip to content

Commit

Permalink
Images verifyBase64Encoded update (#8)
Browse files Browse the repository at this point in the history
Co-authored-by: Davis Puciriuss <[email protected]>
  • Loading branch information
DavisPuciriuss and Davis Puciriuss authored Oct 31, 2024
1 parent ccb838d commit b96d582
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 10 deletions.
10 changes: 8 additions & 2 deletions src/Endpoints/Media/Update/Images.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,12 +80,18 @@ private function verifyBase64Encoded(?string $value): bool
return false;
}

$decoded = base64_decode($value, true);
if (!str_contains($value, 'data:') || !str_contains($value, 'base64,')) {
return false;
}

$base64 = substr($value, strpos($value, 'base64,') + strlen('base64,'));

$decoded = base64_decode($base64, true);

if ($decoded === false) {
return false;
}

return base64_encode($decoded) === $value;
return base64_encode($decoded) === $base64;
}
}
47 changes: 39 additions & 8 deletions tests/Endpoints/Media/Update/ImagesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,23 +13,54 @@ public function test(): void
{
$images = new Images();

$images->thumbnail('aW1hZ2ViYXNlNjRfMQ==')
->placeholder('aW1hZ2ViYXNlNjRfMg==')
->playbutton('aW1hZ2ViYXNlNjRfMw==')
->logo('aW1hZ2ViYXNlNjRfNA==');
$encodedImage = 'data:image/png;base64,' . base64_encode('imagebase64_1');

$images->thumbnail($encodedImage)
->placeholder($encodedImage)
->playbutton($encodedImage)
->logo($encodedImage);

$this->assertEquals([
'thumbnail' => 'aW1hZ2ViYXNlNjRfMQ==',
'placeholder' => 'aW1hZ2ViYXNlNjRfMg==',
'playbutton' => 'aW1hZ2ViYXNlNjRfMw==',
'logo' => 'aW1hZ2ViYXNlNjRfNA==',
'thumbnail' => $encodedImage,
'placeholder' => $encodedImage,
'playbutton' => $encodedImage,
'logo' => $encodedImage,
], $images->compileAsArray());
}

public function test_with_non_base64(): void
{
$images = new Images();

try {
$images->thumbnail('data:image/png;base64,imagebase64_1');
} catch (\InvalidArgumentException $e) {
$this->assertEquals('thumbnail must be a base64 encoded string', $e->getMessage());
}

try {
$images->placeholder('data:image/png;base64,imagebase64_1');
} catch (\InvalidArgumentException $e) {
$this->assertEquals('placeholder must be a base64 encoded string', $e->getMessage());
}

try {
$images->playbutton('data:image/png;base64,imagebase64_1');
} catch (\InvalidArgumentException $e) {
$this->assertEquals('playbutton must be a base64 encoded string', $e->getMessage());
}

try {
$images->logo('data:image/png;base64,imagebase64_1');
} catch (\InvalidArgumentException $e) {
$this->assertEquals('logo must be a base64 encoded string', $e->getMessage());
}
}

public function test_without_metadata(): void
{
$images = new Images();

try {
$images->thumbnail('imagebase64_1');
} catch (\InvalidArgumentException $e) {
Expand Down

0 comments on commit b96d582

Please sign in to comment.