Image.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. /*
  3. * Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
  4. * SPDX-License-Identifier: MIT
  5. */
  6. declare(strict_types=1);
  7. namespace Respect\Validation\Rules;
  8. use finfo;
  9. use SplFileInfo;
  10. use function is_file;
  11. use function is_string;
  12. use function mb_strpos;
  13. use const FILEINFO_MIME_TYPE;
  14. /**
  15. * Validates if the file is a valid image by checking its MIME type.
  16. *
  17. * @author Danilo Benevides <danilobenevides01@gmail.com>
  18. * @author Guilherme Siani <guilherme@siani.com.br>
  19. * @author Henrique Moody <henriquemoody@gmail.com>
  20. */
  21. final class Image extends AbstractRule
  22. {
  23. /**
  24. * @var finfo
  25. */
  26. private $fileInfo;
  27. /**
  28. * Initializes the rule.
  29. */
  30. public function __construct(?finfo $fileInfo = null)
  31. {
  32. $this->fileInfo = $fileInfo ?: new finfo(FILEINFO_MIME_TYPE);
  33. }
  34. /**
  35. * {@inheritDoc}
  36. */
  37. public function validate($input): bool
  38. {
  39. if ($input instanceof SplFileInfo) {
  40. return $this->validate($input->getPathname());
  41. }
  42. if (!is_string($input)) {
  43. return false;
  44. }
  45. if (!is_file($input)) {
  46. return false;
  47. }
  48. return mb_strpos((string) $this->fileInfo->file($input), 'image/') === 0;
  49. }
  50. }