TimezoneField.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Form;
  11. /**
  12. * Represents a field where each timezone is broken down by continent.
  13. *
  14. * @author Bernhard Schussek <bernhard.schussek@symfony-project.com>
  15. */
  16. class TimezoneField extends ChoiceField
  17. {
  18. /**
  19. * Stores the available timezone choices
  20. * @var array
  21. */
  22. protected static $timezones = array();
  23. /**
  24. * {@inheritDoc}
  25. */
  26. public function configure()
  27. {
  28. $this->addOption('choices', self::getTimezoneChoices());
  29. parent::configure();
  30. }
  31. /**
  32. * Preselects the server timezone if the field is empty and required
  33. *
  34. * {@inheritDoc}
  35. */
  36. public function getDisplayedData()
  37. {
  38. $data = parent::getDisplayedData();
  39. if (null == $data && $this->isRequired()) {
  40. $data = date_default_timezone_get();
  41. }
  42. return $data;
  43. }
  44. /**
  45. * Returns the timezone choices
  46. *
  47. * The choices are generated from the ICU function
  48. * \DateTimeZone::listIdentifiers(). They are cached during a single request,
  49. * so multiple timezone fields on the same page don't lead to unnecessary
  50. * overhead.
  51. *
  52. * @return array The timezone choices
  53. */
  54. protected static function getTimezoneChoices()
  55. {
  56. if (count(self::$timezones) == 0) {
  57. foreach (\DateTimeZone::listIdentifiers() as $timezone) {
  58. $parts = explode('/', $timezone);
  59. if (count($parts) > 2) {
  60. $region = $parts[0];
  61. $name = $parts[1].' - '.$parts[2];
  62. } else if (count($parts) > 1) {
  63. $region = $parts[0];
  64. $name = $parts[1];
  65. } else {
  66. $region = 'Other';
  67. $name = $parts[0];
  68. }
  69. if (!isset(self::$timezones[$region])) {
  70. self::$timezones[$region] = array();
  71. }
  72. self::$timezones[$region][$timezone] = str_replace('_', ' ', $name);
  73. }
  74. }
  75. return self::$timezones;
  76. }
  77. }