Locale.php 974 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <?php
  2. namespace Elgg\I18n;
  3. /**
  4. * WARNING: API IN FLUX. DO NOT USE DIRECTLY.
  5. *
  6. * Language class to ensure only valid languages are used.
  7. *
  8. * @since 1.11
  9. *
  10. * @access private
  11. */
  12. final class Locale {
  13. /** @var string */
  14. private $locale;
  15. /**
  16. * Use Locale::parse to construct
  17. *
  18. * @param string $locale A string representation of the locale
  19. */
  20. private function __construct($locale) {
  21. $this->locale = $locale;
  22. }
  23. /** @inheritDoc */
  24. public function __toString() {
  25. return $this->locale;
  26. }
  27. /**
  28. * Create a language, asserting that the language code is valid.
  29. *
  30. * @param string $locale Language code
  31. *
  32. * @return Locale
  33. *
  34. * @throws InvalidLocaleException
  35. */
  36. public static function parse($locale) {
  37. // TODO(evan): Better sanitizing of locales using \Locale perhaps
  38. if (!preg_match('~^[a-z0-9_]{2,20}$~', $locale)) {
  39. throw new InvalidLocaleException("Unrecognized locale: $locale");
  40. }
  41. return new Locale($locale);
  42. }
  43. }