Intl.php 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. /*
  3. * This file is part of Twig.
  4. *
  5. * (c) 2010 Fabien Potencier
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. class Twig_Extensions_Extension_Intl extends Twig_Extension
  11. {
  12. public function __construct()
  13. {
  14. if (!class_exists('IntlDateFormatter')) {
  15. throw new RuntimeException('The intl extension is needed to use intl-based filters.');
  16. }
  17. }
  18. /**
  19. * Returns a list of filters to add to the existing list.
  20. *
  21. * @return array An array of filters
  22. */
  23. public function getFilters()
  24. {
  25. return array(
  26. 'localizeddate' => new Twig_Filter_Function('twig_localized_date_filter'),
  27. );
  28. }
  29. /**
  30. * Returns the name of the extension.
  31. *
  32. * @return string The extension name
  33. */
  34. public function getName()
  35. {
  36. return 'intl';
  37. }
  38. }
  39. function twig_localized_date_filter($date, $dateFormat = 'medium', $timeFormat = 'medium', $locale = null)
  40. {
  41. $formatValues = array(
  42. 'none' => IntlDateFormatter::NONE,
  43. 'short' => IntlDateFormatter::SHORT,
  44. 'medium' => IntlDateFormatter::MEDIUM,
  45. 'long' => IntlDateFormatter::LONG,
  46. 'full' => IntlDateFormatter::FULL,
  47. );
  48. $formatter = IntlDateFormatter::create(
  49. $locale !== null ? $locale : Locale::getDefault(),
  50. $formatValues[$dateFormat],
  51. $formatValues[$timeFormat]
  52. );
  53. if (!$date instanceof DateTime) {
  54. if (ctype_digit((string) $date)) {
  55. $date = new DateTime('@'.$date);
  56. $date->setTimezone(new DateTimeZone(date_default_timezone_get()));
  57. } else {
  58. $date = new DateTime($date);
  59. }
  60. }
  61. return $formatter->format($date->getTimestamp());
  62. }