leftypol/inc/Service/Media/FallbackMediaHandler.php

85 lines
2.3 KiB
PHP
Raw Normal View History

<?php
namespace Vichan\Service\Media;
use Vichan\Data\ThumbGenerationResult;
use Vichan\Functions\{Fs, Mime};
class FallbackMediaHandler implements MediaHandler {
2025-03-18 00:40:51 +01:00
private string $path;
private int $width;
private int $height;
private string $mime;
public function __construct(ImageMetadataReader $image_metadate_reader, string $default_thumb_path) {
2025-03-18 00:40:51 +01:00
$res = $image_metadate_reader->getMetadata($default_thumb_path);
$this->path = $default_thumb_path;
$this->width = $res->width;
$this->height = $res->height;
$this->mime = $res->mime;
}
public function supportsMime(string $mime): bool {
return true;
}
2025-03-18 11:51:36 +01:00
public function openHandle(string $file_path, string $file_mime, int $file_kind): mixed {
return [ $file_path, $file_mime, $file_kind ];
}
public function closeHandle(mixed $handle) {
// No-op
}
public function installMediaAndGenerateThumb(
mixed $handle,
string $media_preferred_out_file_dir,
string $media_preferred_out_file_name,
string $thumb_preferred_out_file_dir,
string $thumb_preferred_out_file_name,
string $thumb_preferred_out_mime,
int $thumb_max_width,
int $thumb_max_height
) {
list($source_file_path, $source_file_mime, $source_file_kind) = $handle;
$out_path = $media_preferred_out_file_dir . DIRECTORY_SEPARATOR . $media_preferred_out_file_name . '.' . Mime\mime_to_ext($source_file_mime);
if ($source_file_kind === self::FILE_KIND_UPLOADED) {
if (!Fs\move_or_copy_uploaded($source_file_path, $out_path)) {
throw new \RuntimeException("Could not move or copy uploaded file '$source_file_path' to '$out_path'");
}
} else {
if (!Fs\link_or_copy($source_file_path, $out_path)) {
throw new \RuntimeException("Could not link or copy '$source_file_path' to '$out_path'");
}
}
return $this->generateThumb(
$handle,
$thumb_preferred_out_file_dir,
$thumb_preferred_out_file_name,
$thumb_preferred_out_mime,
$thumb_max_width,
$thumb_max_height
);
2025-03-18 11:31:23 +01:00
}
public function generateThumb(
2025-03-18 11:31:23 +01:00
mixed $handle,
string $preferred_out_file_dir,
string $preferred_out_file_name,
2025-03-18 00:40:51 +01:00
string $preferred_out_mime,
int $max_width,
int $max_height
): ThumbGenerationResult {
2025-03-18 10:09:19 +01:00
return new ThumbGenerationResult(
$this->path,
$this->mime,
false,
\min($this->width, $max_width),
\min($this->height, $max_height)
);
}
}