MarkdownFileExtension.php 919 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. <?php
  2. namespace App\Rules;
  3. use Closure;
  4. use Illuminate\Contracts\Validation\ValidationRule;
  5. use Illuminate\Http\UploadedFile;
  6. class MarkdownFileExtension implements ValidationRule
  7. {
  8. /**
  9. * @param array<int, string> $allowedExtensions
  10. */
  11. public function __construct(
  12. private readonly array $allowedExtensions = ['md', 'markdown', 'txt']
  13. ) {
  14. }
  15. public function validate(string $attribute, mixed $value, Closure $fail): void
  16. {
  17. if (blank($value)) {
  18. return;
  19. }
  20. $file = is_array($value) ? ($value[0] ?? null) : $value;
  21. if (!($file instanceof UploadedFile)) {
  22. return;
  23. }
  24. $ext = strtolower((string) $file->getClientOriginalExtension());
  25. if (!in_array($ext, $this->allowedExtensions, true)) {
  26. $fail('Markdown 文件格式不正确,请上传 .md / .markdown / .txt');
  27. }
  28. }
  29. }