silverstripe-framework/src/Forms/TimeField.php

437 lines
11 KiB
PHP
Raw Normal View History

<?php
namespace SilverStripe\Forms;
use IntlDateFormatter;
use InvalidArgumentException;
use SilverStripe\i18n\i18n;
use SilverStripe\ORM\FieldType\DBDatetime;
FEATURE New DatetimeField class (form field wrapper composed of DateField andTimeField) FEATURE New DateField and TimeField form classes with more consistent API and easier localization API CHANGE Date/time parsing in DateField, TimeField and DatetimeField defaults to i18n::get_locale() ('en_US') instead of using en_NZ/en_GB specific parsing. Use i18n::set_locale('en_NZ') in mysite/_config.php to revert to old behaviour. API CHANGE constructor parameter in TimeField needs to be in ISO date notation (not PHP's date()) API CHANGE TimeField, DateField and related subclasses use Zend_Date for date parsing, meaning they're stricer than the previously used strtotime() API CHANGE Removed DMYCalendarDateField and CalendarDateField, use DateField with setConfig('showcalendar') API CHANGE Removed CompositeDateField, DMYDateField, use DateField with setConfig('dmyfields') API CHANGE Removed DropdownTimeField, use TimeField with setConfig('showdropdown') API CHANGE Removed PopupDateTimeField, use DatetimeField API CHANGE Changed 'date', 'month' and 'year' HTML field names to lowercase in DMYDateField API CHANGE Removed support for ambiguous date formats in DateField, e.g. '06/03/03'. Use DateField->setConfig('dateformat', '<format>') to revert to this behaviour. API CHANGE Removed flag from DateField, CalendarDateField etc., use DateField->setConfig('min') and DateField->setConfig('max') ENHANCEMENT Using Zend_Date for DateField and TimeField, with more robust date handling, starting localization support. Set globally via i18n::set_locale(), or for a field instance through setLocale(). Note: Javascript validation is not localized yet. (from r99360) git-svn-id: svn://svn.silverstripe.com/silverstripe/open/modules/sapphire/trunk@102859 467b73ca-7a2a-4603-9d3b-597d59a354a9
2010-04-14 06:38:40 +02:00
/**
2014-08-15 08:53:05 +02:00
* Form field to display editable time values in an <input type="text"> field.
*
FEATURE New DatetimeField class (form field wrapper composed of DateField andTimeField) FEATURE New DateField and TimeField form classes with more consistent API and easier localization API CHANGE Date/time parsing in DateField, TimeField and DatetimeField defaults to i18n::get_locale() ('en_US') instead of using en_NZ/en_GB specific parsing. Use i18n::set_locale('en_NZ') in mysite/_config.php to revert to old behaviour. API CHANGE constructor parameter in TimeField needs to be in ISO date notation (not PHP's date()) API CHANGE TimeField, DateField and related subclasses use Zend_Date for date parsing, meaning they're stricer than the previously used strtotime() API CHANGE Removed DMYCalendarDateField and CalendarDateField, use DateField with setConfig('showcalendar') API CHANGE Removed CompositeDateField, DMYDateField, use DateField with setConfig('dmyfields') API CHANGE Removed DropdownTimeField, use TimeField with setConfig('showdropdown') API CHANGE Removed PopupDateTimeField, use DatetimeField API CHANGE Changed 'date', 'month' and 'year' HTML field names to lowercase in DMYDateField API CHANGE Removed support for ambiguous date formats in DateField, e.g. '06/03/03'. Use DateField->setConfig('dateformat', '<format>') to revert to this behaviour. API CHANGE Removed flag from DateField, CalendarDateField etc., use DateField->setConfig('min') and DateField->setConfig('max') ENHANCEMENT Using Zend_Date for DateField and TimeField, with more robust date handling, starting localization support. Set globally via i18n::set_locale(), or for a field instance through setLocale(). Note: Javascript validation is not localized yet. (from r99360) git-svn-id: svn://svn.silverstripe.com/silverstripe/open/modules/sapphire/trunk@102859 467b73ca-7a2a-4603-9d3b-597d59a354a9
2010-04-14 06:38:40 +02:00
* # Localization
2014-08-15 08:53:05 +02:00
*
FEATURE New DatetimeField class (form field wrapper composed of DateField andTimeField) FEATURE New DateField and TimeField form classes with more consistent API and easier localization API CHANGE Date/time parsing in DateField, TimeField and DatetimeField defaults to i18n::get_locale() ('en_US') instead of using en_NZ/en_GB specific parsing. Use i18n::set_locale('en_NZ') in mysite/_config.php to revert to old behaviour. API CHANGE constructor parameter in TimeField needs to be in ISO date notation (not PHP's date()) API CHANGE TimeField, DateField and related subclasses use Zend_Date for date parsing, meaning they're stricer than the previously used strtotime() API CHANGE Removed DMYCalendarDateField and CalendarDateField, use DateField with setConfig('showcalendar') API CHANGE Removed CompositeDateField, DMYDateField, use DateField with setConfig('dmyfields') API CHANGE Removed DropdownTimeField, use TimeField with setConfig('showdropdown') API CHANGE Removed PopupDateTimeField, use DatetimeField API CHANGE Changed 'date', 'month' and 'year' HTML field names to lowercase in DMYDateField API CHANGE Removed support for ambiguous date formats in DateField, e.g. '06/03/03'. Use DateField->setConfig('dateformat', '<format>') to revert to this behaviour. API CHANGE Removed flag from DateField, CalendarDateField etc., use DateField->setConfig('min') and DateField->setConfig('max') ENHANCEMENT Using Zend_Date for DateField and TimeField, with more robust date handling, starting localization support. Set globally via i18n::set_locale(), or for a field instance through setLocale(). Note: Javascript validation is not localized yet. (from r99360) git-svn-id: svn://svn.silverstripe.com/silverstripe/open/modules/sapphire/trunk@102859 467b73ca-7a2a-4603-9d3b-597d59a354a9
2010-04-14 06:38:40 +02:00
* See {@link DateField}
2014-08-15 08:53:05 +02:00
*
FEATURE New DatetimeField class (form field wrapper composed of DateField andTimeField) FEATURE New DateField and TimeField form classes with more consistent API and easier localization API CHANGE Date/time parsing in DateField, TimeField and DatetimeField defaults to i18n::get_locale() ('en_US') instead of using en_NZ/en_GB specific parsing. Use i18n::set_locale('en_NZ') in mysite/_config.php to revert to old behaviour. API CHANGE constructor parameter in TimeField needs to be in ISO date notation (not PHP's date()) API CHANGE TimeField, DateField and related subclasses use Zend_Date for date parsing, meaning they're stricer than the previously used strtotime() API CHANGE Removed DMYCalendarDateField and CalendarDateField, use DateField with setConfig('showcalendar') API CHANGE Removed CompositeDateField, DMYDateField, use DateField with setConfig('dmyfields') API CHANGE Removed DropdownTimeField, use TimeField with setConfig('showdropdown') API CHANGE Removed PopupDateTimeField, use DatetimeField API CHANGE Changed 'date', 'month' and 'year' HTML field names to lowercase in DMYDateField API CHANGE Removed support for ambiguous date formats in DateField, e.g. '06/03/03'. Use DateField->setConfig('dateformat', '<format>') to revert to this behaviour. API CHANGE Removed flag from DateField, CalendarDateField etc., use DateField->setConfig('min') and DateField->setConfig('max') ENHANCEMENT Using Zend_Date for DateField and TimeField, with more robust date handling, starting localization support. Set globally via i18n::set_locale(), or for a field instance through setLocale(). Note: Javascript validation is not localized yet. (from r99360) git-svn-id: svn://svn.silverstripe.com/silverstripe/open/modules/sapphire/trunk@102859 467b73ca-7a2a-4603-9d3b-597d59a354a9
2010-04-14 06:38:40 +02:00
* @todo Timezone support
*/
2016-11-29 00:31:16 +01:00
class TimeField extends TextField
{
protected $schemaDataType = FormField::SCHEMA_DATA_TYPE_TIME;
2016-11-29 00:31:16 +01:00
/**
* Override locale. If empty will default to current locale
*
* @var string
2016-11-29 00:31:16 +01:00
*/
protected $locale = null;
2016-11-29 00:31:16 +01:00
/**
* Override time format. If empty will default to that used by the current locale.
*
* @var string
2016-11-29 00:31:16 +01:00
*/
protected $timeFormat = null;
2016-11-29 00:31:16 +01:00
/**
* Length of this date (full, short, etc).
*
* @see http://php.net/manual/en/class.intldateformatter.php#intl.intldateformatter-constants
* @var int
2016-11-29 00:31:16 +01:00
*/
protected $timeLength = null;
2016-11-29 00:31:16 +01:00
/**
* Unparsed value, used exclusively for comparing with internal value
* to detect invalid values.
*
* @var mixed
2016-11-29 00:31:16 +01:00
*/
protected $rawValue = null;
2016-11-29 00:31:16 +01:00
/**
* Set custom timezone
*
* @var string
*/
protected $timezone = null;
2016-11-29 00:31:16 +01:00
/**
* Get time format in CLDR standard format
*
* This can be set explicitly. If not, this will be generated from the current locale
* with the current time length.
*
* @see http://userguide.icu-project.org/formatparse/datetime#TOC-Date-Field-Symbol-Table
*/
public function getTimeFormat()
2016-11-29 00:31:16 +01:00
{
if ($this->timeFormat) {
return $this->timeFormat;
2016-11-29 00:31:16 +01:00
}
// Get from locale
return $this->getFormatter()->getPattern();
2016-11-29 00:31:16 +01:00
}
/**
* Set time format in CLDR standard format.
*
* @see http://userguide.icu-project.org/formatparse/datetime#TOC-Date-Field-Symbol-Table
* @param string $format
* @return $this
*/
public function setTimeFormat($format)
2016-11-29 00:31:16 +01:00
{
$this->timeFormat = $format;
return $this;
2016-11-29 00:31:16 +01:00
}
/**
* Get length of the time format to use. One of:
*
* - IntlDateFormatter::SHORT E.g. '6:31 PM'
* - IntlDateFormatter::MEDIUM E.g. '6:30:48 PM'
* - IntlDateFormatter::LONG E.g. '6:32:09 PM NZDT'
* - IntlDateFormatter::FULL E.g. '6:32:24 PM New Zealand Daylight Time'
*
* @see http://php.net/manual/en/class.intldateformatter.php#intl.intldateformatter-constants
* @return int
*/
public function getTimeLength()
2016-11-29 00:31:16 +01:00
{
if ($this->timeLength) {
return $this->timeLength;
}
return IntlDateFormatter::MEDIUM;
2016-11-29 00:31:16 +01:00
}
/**
* Get length of the time format to use. One of:
*
* - IntlDateFormatter::SHORT E.g. '6:31 PM'
* - IntlDateFormatter::MEDIUM E.g. '6:30:48 PM'
* - IntlDateFormatter::LONG E.g. '6:32:09 PM NZDT'
* - IntlDateFormatter::FULL E.g. '6:32:24 PM New Zealand Daylight Time'
2016-11-29 00:31:16 +01:00
*
* @see http://php.net/manual/en/class.intldateformatter.php#intl.intldateformatter-constants
2016-11-29 00:31:16 +01:00
*
* @param int $length
* @return $this
2016-11-29 00:31:16 +01:00
*/
public function setTimeLength($length)
2016-11-29 00:31:16 +01:00
{
$this->timeLength = $length;
return $this;
}
/**
* Get time formatter with the standard locale / date format
*
* @return IntlDateFormatter
*/
protected function getFormatter()
{
$formatter = IntlDateFormatter::create(
$this->getLocale(),
IntlDateFormatter::NONE,
$this->getTimeLength(),
$this->getTimezone()
);
// Don't invoke getDateFormat() directly to avoid infinite loop
if ($this->timeFormat) {
$ok = $formatter->setPattern($this->timeFormat);
if (!$ok) {
throw new InvalidArgumentException("Invalid time format {$this->timeFormat}");
}
2016-11-29 00:31:16 +01:00
}
return $formatter;
}
/**
* Get a time formatter for the ISO 8601 format
*
* @return IntlDateFormatter
*/
protected function getISO8601Formatter()
{
$formatter = IntlDateFormatter::create(
2017-02-22 04:14:53 +01:00
i18n::config()->uninherited('default_locale'),
IntlDateFormatter::NONE,
IntlDateFormatter::MEDIUM,
date_default_timezone_get() // Default to server timezone
);
$formatter->setLenient(false);
// CLDR iso8601 time
// Note we omit timezone from this format, and we assume server TZ always.
$formatter->setPattern('HH:mm:ss');
return $formatter;
}
2016-11-29 00:31:16 +01:00
public function getAttribute($name)
{
$attributes = parent::getAttributes();
2016-11-29 00:31:16 +01:00
// Merge with client config
$config = $this->getClientConfig();
foreach ($config as $key => $value) {
$attributes["data-{$key}"] = $value;
2016-11-29 00:31:16 +01:00
}
return $attributes;
2016-11-29 00:31:16 +01:00
}
/**
* Get client config options for this field
*
* @return array
*/
public function getClientConfig()
{
return [
// @todo - Support javascript time picker
'timeformat' => $this->getTimeFormat(),
];
}
public function Type()
{
return 'time text';
}
2016-11-29 00:31:16 +01:00
/**
* Assign value posted from form submission
2016-11-29 00:31:16 +01:00
*
* @param mixed $value
* @param mixed $data
2016-11-29 00:31:16 +01:00
* @return $this
*/
public function setSubmittedValue($value, $data = null)
2016-11-29 00:31:16 +01:00
{
// Save raw value for later validation
$this->rawValue = $value;
2016-11-29 00:31:16 +01:00
// Parse from submitted value
$this->value = $this->localisedToISO8601($value);
return $this;
}
2016-11-29 00:31:16 +01:00
/**
* Set time assigned from database value
*
* @param mixed $value
* @param mixed $data
* @return $this
*/
public function setValue($value, $data = null)
{
// Save raw value for later validation
$this->rawValue = $value;
// Null case
if (!$value) {
2016-11-29 00:31:16 +01:00
$this->value = null;
return $this;
2016-11-29 00:31:16 +01:00
}
// Re-run through formatter to tidy up (e.g. remove date component)
$this->value = $this->tidyISO8601($value);
2016-11-29 00:31:16 +01:00
return $this;
}
public function Value()
{
$localised = $this->iso8601ToLocalised($this->value);
if ($localised) {
return $localised;
}
// Show midnight in localised format
return $this->getMidnight();
}
2016-11-29 00:31:16 +01:00
/**
* Show midnight in current format (adjusts for timezone)
*
* @return string
2016-11-29 00:31:16 +01:00
*/
public function getMidnight()
2016-11-29 00:31:16 +01:00
{
$formatter = $this->getFormatter();
$timestamp = $this->withTimezone($this->getTimezone(), function () {
return strtotime('midnight');
});
return $formatter->format($timestamp);
2016-11-29 00:31:16 +01:00
}
/**
* Validate this field
*
* @param Validator $validator
* @return bool
*/
public function validate($validator)
{
// Don't validate empty fields
if (empty($this->rawValue)) {
2016-11-29 00:31:16 +01:00
return true;
}
// We submitted a value, but it couldn't be parsed
if (empty($this->value)) {
2016-11-29 00:31:16 +01:00
$validator->validationError(
$this->name,
_t(
'TimeField.VALIDATEFORMAT',
"Please enter a valid time format ({format})",
['format' => $this->getTimeFormat()]
)
2016-11-29 00:31:16 +01:00
);
return false;
}
return true;
}
/**
* @return string
*/
public function getLocale()
{
return $this->locale ?: i18n::get_locale();
2016-11-29 00:31:16 +01:00
}
/**
* @param string $locale
* @return $this
*/
public function setLocale($locale)
{
$this->locale = $locale;
return $this;
}
/**
* Creates a new readonly field specified below
*
* @return TimeField_Readonly
2016-11-29 00:31:16 +01:00
*/
public function performReadonlyTransformation()
2016-11-29 00:31:16 +01:00
{
/** @var TimeField_Readonly $result */
$result = $this->castedCopy(TimeField_Readonly::class);
return $result;
2016-11-29 00:31:16 +01:00
}
/**
* Convert time localised in the current locale to ISO 8601 time
*
* @param string $time
* @return string The formatted time, or null if not a valid time
2016-11-29 00:31:16 +01:00
*/
public function localisedToISO8601($time)
2016-11-29 00:31:16 +01:00
{
if (!$time) {
return null;
}
$fromFormatter = $this->getFormatter();
$toFormatter = $this->getISO8601Formatter();
$timestamp = $fromFormatter->parse($time);
if ($timestamp === false) {
return null;
2016-11-29 00:31:16 +01:00
}
return $toFormatter->format($timestamp);
2016-11-29 00:31:16 +01:00
}
/**
* Format iso time to localised form
*
* @param string $time
* @return string
2016-11-29 00:31:16 +01:00
*/
public function iso8601ToLocalised($time)
2016-11-29 00:31:16 +01:00
{
$time = $this->tidyISO8601($time);
if (!$time) {
return null;
}
$fromFormatter = $this->getISO8601Formatter();
$toFormatter = $this->getFormatter();
$timestamp = $fromFormatter->parse($time);
if ($timestamp === false) {
return null;
}
return $toFormatter->format($timestamp);
2016-11-29 00:31:16 +01:00
}
/**
* Tidy up iso8601-ish time, or approximation
*
* @param string $time Time in iso8601 or approximate form
* @return string iso8601 time, or null if not valid
*/
public function tidyISO8601($time)
2016-11-29 00:31:16 +01:00
{
if (!$time) {
return null;
}
// Re-run through formatter to tidy up (e.g. remove date component)
$formatter = $this->getISO8601Formatter();
$timestamp = $formatter->parse($time);
if ($timestamp === false) {
// Fallback to strtotime
$timestamp = strtotime($time, DBDatetime::now()->getTimestamp());
if ($timestamp === false) {
return null;
2016-11-29 00:31:16 +01:00
}
}
return $formatter->format($timestamp);
}
/**
* @return string
*/
public function getTimezone()
{
return $this->timezone;
}
/**
* @param string $timezone
* @return $this
*/
public function setTimezone($timezone)
{
if ($this->value && $timezone !== $this->timezone) {
throw new \BadMethodCallException("Can't change timezone after setting a value");
}
$this->timezone = $timezone;
return $this;
}
2016-11-29 00:31:16 +01:00
/**
* Run a callback within a specific timezone
*
* @param string $timezone
* @param callable $callback
*/
protected function withTimezone($timezone, $callback)
{
$currentTimezone = date_default_timezone_get();
try {
if ($timezone) {
date_default_timezone_set($timezone);
}
return $callback();
} finally {
// Restore timezone
if ($timezone) {
date_default_timezone_set($currentTimezone);
}
}
2016-11-29 00:31:16 +01:00
}
}