forked from leftypol/leftypol
93 lines
2.5 KiB
PHP
93 lines
2.5 KiB
PHP
<?php
|
|
namespace Vichan\Service\Media;
|
|
|
|
use Vichan\Data\{MediaInstallResult, ThumbGenerationResult};
|
|
use Vichan\Functions\Metadata;
|
|
|
|
|
|
class FallbackMediaHandler implements MediaHandler {
|
|
use MediaHandlerTrait;
|
|
|
|
private string $path;
|
|
private int $width;
|
|
private int $height;
|
|
private string $mime;
|
|
|
|
|
|
private static function getShape(string $file_path) {
|
|
$ret = \getimagesize($file_path);
|
|
if ($ret === false) {
|
|
throw new MediaException("Could not read image sizes of '$file_path'", MediaException::ERR_NO_OPEN);
|
|
}
|
|
if ($ret[2] == \IMAGETYPE_UNKNOWN) {
|
|
throw new \RuntimeException("Error '$file_path' is not an image", MediaException::ERR_BAD_MEDIA_TYPE);
|
|
}
|
|
|
|
$width = $ret[0];
|
|
$height = $ret[1];
|
|
$mime = $ret['mime'];
|
|
return [ $width, $height, $mime ];
|
|
}
|
|
|
|
public function __construct(string $default_thumb_path) {
|
|
list($width, $height, $mime) = self::getShape($default_thumb_path);
|
|
$this->path = $default_thumb_path;
|
|
$this->width = $width;
|
|
$this->height = $height;
|
|
$this->mime = $mime;
|
|
}
|
|
|
|
public function supportsMime(string $mime): bool {
|
|
return true;
|
|
}
|
|
|
|
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
|
|
): MediaInstallResult {
|
|
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 . '.' . Metadata\mime_to_ext($source_file_mime);
|
|
|
|
$this->move_or_link_or_copy($source_file_kind, $source_file_path, $out_path);
|
|
|
|
$thumb = $this->generateThumb(
|
|
$handle,
|
|
$thumb_preferred_out_file_dir,
|
|
$thumb_preferred_out_file_name,
|
|
$thumb_preferred_out_mime,
|
|
$thumb_max_width,
|
|
$thumb_max_height
|
|
);
|
|
return new MediaInstallResult($thumb, $out_path);
|
|
}
|
|
|
|
public function generateThumb(
|
|
mixed $handle,
|
|
string $preferred_out_file_dir,
|
|
string $preferred_out_file_name,
|
|
string $preferred_out_mime,
|
|
int $max_width,
|
|
int $max_height
|
|
): ThumbGenerationResult {
|
|
return new ThumbGenerationResult(
|
|
$this->path,
|
|
$this->mime,
|
|
\min($this->width, $max_width),
|
|
\min($this->height, $max_height)
|
|
);
|
|
}
|
|
}
|