format(); } if ($identifier instanceof FileExtension) { return $identifier->format(); } try { $format = MediaType::from(strtolower($identifier))->format(); } catch (Error) { try { $format = FileExtension::from(strtolower($identifier))->format(); } catch (Error) { throw new NotSupportedException('Unable to create format from "' . $identifier . '".'); } } 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 { try { return self::create($identifier); } catch (NotSupportedException) { return null; } } /** * Return the possible media (MIME) types for the current format * * @return array */ public function mediaTypes(): array { return array_filter(MediaType::cases(), function ($mediaType) { return $mediaType->format() === $this; }); } /** * Return the first found media type for the current format * * @return MediaType */ public function mediaType(): MediaType { $types = $this->mediaTypes(); return reset($types); } /** * Return the possible file extension for the current format * * @return array */ public function fileExtensions(): array { return array_filter(FileExtension::cases(), function ($fileExtension) { return $fileExtension->format() === $this; }); } /** * Return the first found file extension for the current format * * @return FileExtension */ public function fileExtension(): FileExtension { $extensions = $this->fileExtensions(); return reset($extensions); } /** * Create an encoder instance with given options that matches the format * * @param mixed $options * @return EncoderInterface */ public function encoder(mixed ...$options): EncoderInterface { // get classname of target encoder from current format $classname = match ($this) { self::AVIF => AvifEncoder::class, self::BMP => BmpEncoder::class, self::GIF => GifEncoder::class, self::HEIC => HeicEncoder::class, self::JP2 => Jpeg2000Encoder::class, self::JPEG => JpegEncoder::class, self::PNG => PngEncoder::class, self::TIFF => TiffEncoder::class, self::WEBP => WebpEncoder::class, }; // get parameters of target encoder $parameters = []; $reflectionClass = new ReflectionClass($classname); if ($constructor = $reflectionClass->getConstructor()) { $parameters = array_map( fn ($parameter) => $parameter->getName(), $constructor->getParameters(), ); } // filter out unavailable options of target encoder $options = array_filter( $options, fn ($key) => in_array($key, $parameters), ARRAY_FILTER_USE_KEY, ); return new $classname(...$options); } }