Extension.php 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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 SplFileInfo;
  9. use function is_string;
  10. use function pathinfo;
  11. use const PATHINFO_EXTENSION;
  12. /**
  13. * Validate file extensions.
  14. *
  15. * @author Danilo Correa <danilosilva87@gmail.com>
  16. * @author Henrique Moody <henriquemoody@gmail.com>
  17. */
  18. final class Extension extends AbstractRule
  19. {
  20. /**
  21. * @var string
  22. */
  23. private $extension;
  24. /**
  25. * Initializes the rule.
  26. */
  27. public function __construct(string $extension)
  28. {
  29. $this->extension = $extension;
  30. }
  31. /**
  32. * {@inheritDoc}
  33. */
  34. public function validate($input): bool
  35. {
  36. if ($input instanceof SplFileInfo) {
  37. return $this->extension === $input->getExtension();
  38. }
  39. if (!is_string($input)) {
  40. return false;
  41. }
  42. return $this->extension === pathinfo($input, PATHINFO_EXTENSION);
  43. }
  44. }