Charset.php 1.2 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 Respect\Validation\Exceptions\ComponentException;
  9. use function array_diff;
  10. use function in_array;
  11. use function mb_detect_encoding;
  12. use function mb_list_encodings;
  13. /**
  14. * Validates if a string is in a specific charset.
  15. *
  16. * @author Alexandre Gomes Gaigalas <alganet@gmail.com>
  17. * @author Henrique Moody <henriquemoody@gmail.com>
  18. * @author William Espindola <oi@williamespindola.com.br>
  19. */
  20. final class Charset extends AbstractRule
  21. {
  22. /**
  23. * @var string[]
  24. */
  25. private $charset;
  26. /**
  27. * Initializes the rule.
  28. *
  29. * @throws ComponentException
  30. */
  31. public function __construct(string ...$charset)
  32. {
  33. $available = mb_list_encodings();
  34. if (!empty(array_diff($charset, $available))) {
  35. throw new ComponentException('Invalid charset');
  36. }
  37. $this->charset = $charset;
  38. }
  39. /**
  40. * {@inheritDoc}
  41. */
  42. public function validate($input): bool
  43. {
  44. return in_array(mb_detect_encoding($input, $this->charset, true), $this->charset, true);
  45. }
  46. }