trypost/app/Rules/ContentTypeCompatibleWithMedia.php
Paulo Castellano beea8a5f97 feat(posts): block combining an image and a video in one post
A Bluesky post embed is images XOR video, so a post that carries both can't
be published there. Enforce it per selected platform:

- Add ContentType::supportsMixedMedia() (false only for BlueskyPost) and reject
  image+video in ContentTypeCompatibleWithMedia when the type forbids it.
- Mirror it client-side (useMediaRules forbidsMixedMedia + usePostCompliance)
  so the editor blocks scheduling with an inline reason before submit, like
  every other per-platform compatibility check.
- Add the no_mixed_media message in all three locales (en/es/pt-BR).
- Cover the rule and enum, including the GIF-counts-as-image case.
2026-06-23 14:30:38 -03:00

93 lines
2.5 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Rules;
use App\Enums\Media\Type as MediaType;
use App\Enums\PostPlatform\ContentType;
use Closure;
use Illuminate\Contracts\Validation\DataAwareRule;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Translation\PotentiallyTranslatedString;
class ContentTypeCompatibleWithMedia implements DataAwareRule, ValidationRule
{
/**
* @var array<string, mixed>
*/
private array $data = [];
/**
* @param array<string, mixed> $data
*/
public function setData(array $data): static
{
$this->data = $data;
return $this;
}
/**
* @param Closure(string, ?string=): PotentiallyTranslatedString $fail
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
$contentType = ContentType::tryFrom((string) $value);
if (! $contentType) {
return;
}
$media = (array) data_get($this->data, 'media', []);
$count = count($media);
if ($contentType->requiresMedia() && $count === 0) {
$fail("{$contentType->label()} requires at least one media file.");
return;
}
if ($count === 0) {
return;
}
$hasImage = collect($media)->contains(fn ($item) => $this->isImage((array) $item));
$hasVideo = collect($media)->contains(fn ($item) => $this->isVideo((array) $item));
if ($hasImage && ! $contentType->supportsImage()) {
$fail("{$contentType->label()} does not support images.");
}
if ($hasVideo && ! $contentType->supportsVideo()) {
$fail("{$contentType->label()} does not support videos.");
}
if ($hasImage && $hasVideo && ! $contentType->supportsMixedMedia()) {
$fail("{$contentType->label()} can't combine an image and a video in the same post.");
}
}
/**
* @param array<string, mixed> $item
*/
private function isImage(array $item): bool
{
if (data_get($item, 'type') === MediaType::Image->value) {
return true;
}
return str_starts_with((string) data_get($item, 'mime_type', ''), 'image/');
}
/**
* @param array<string, mixed> $item
*/
private function isVideo(array $item): bool
{
if (data_get($item, 'type') === MediaType::Video->value) {
return true;
}
return str_starts_with((string) data_get($item, 'mime_type', ''), 'video/');
}
}