1
0
mirror of https://github.com/Intervention/image.git synced 2025-08-29 00:29:55 +02:00

Add Format::tryCreate()

This commit is contained in:
Oliver Vogel
2024-07-03 16:51:45 +02:00
parent 4bc03a2304
commit f130eb0985
2 changed files with 27 additions and 0 deletions

View File

@@ -64,6 +64,21 @@ enum Format
return $format;
}
/**
* Try to create format from given identifier and return null on failure
*
* @param string|Format|MediaType|FileExtension $identifier
* @return Format|null
*/
public static function tryCreate(string|self|MediaType|FileExtension $identifier): self|null
{
try {
return self::create($identifier);
} catch (NotSupportedException) {
return null;
}
}
/**
* Return the possible media (MIME) types for the current format
*

View File

@@ -38,6 +38,18 @@ final class FormatTest extends BaseTestCase
Format::create('foo');
}
public function testTryCreate(): void
{
$this->assertEquals(Format::JPEG, Format::tryCreate(Format::JPEG));
$this->assertEquals(Format::JPEG, Format::tryCreate('jpg'));
$this->assertEquals(Format::JPEG, Format::tryCreate('jpeg'));
$this->assertEquals(Format::JPEG, Format::tryCreate('image/jpeg'));
$this->assertEquals(Format::GIF, Format::tryCreate('image/gif'));
$this->assertEquals(Format::PNG, Format::tryCreate(FileExtension::PNG));
$this->assertEquals(Format::WEBP, Format::tryCreate(MediaType::IMAGE_WEBP));
$this->assertNull(Format::tryCreate('no-format'));
}
public function testMediaTypesJpeg(): void
{
$format = Format::JPEG;