1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84: 85: 86: 87: 88: 89: 90: 91: 92: 93: 94: 95: 96: 97: 98: 99: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117: 118: 119: 120: 121: 122: 123: 124: 125: 126: 127: 128: 129: 130: 131: 132: 133: 134: 135: 136: 137: 138: 139: 140: 141: 142: 143: 144:
<?php
namespace Inteve\Forms;
use Nette;
use Nette\Forms\Form;
class TimeInput extends Nette\Forms\Controls\BaseControl
{
private $hour;
private $minute;
private $rawValue = '';
public function __construct($caption = NULL, $errorMessage = 'Invalid time.')
{
parent::__construct($caption);
$this->addRule([__CLASS__, 'validateTime'], $errorMessage);
}
public function setValue($value)
{
if ($value === NULL) {
$this->hour = NULL;
$this->minute = NULL;
$this->rawValue = '';
} elseif ($value instanceof \DateTimeInterface) {
$this->hour = (int) $value->format('G');
$this->minute = (int) $value->format('i');
$this->rawValue = $value->format('G:i');
} elseif ($value instanceof \DateInterval) {
$this->hour = (int) $value->format('%h');
$this->minute = (int) $value->format('%I');
$this->rawValue = $value->format('%h:%I');
if (!self::validateTime($this)) {
$this->setValue(NULL);
throw new InvalidValueException('Invalid time in DateInterval.');
}
} else {
throw new InvalidArgumentException('Value of type ' . gettype($value) . ' is not supported.');
}
}
public function getValue()
{
if (self::validateTime($this)) {
return new \DateInterval('PT' . $this->hour . 'H' . $this->minute . 'M');
}
return NULL;
}
public function isFilled()
{
return $this->rawValue !== '';
}
public function loadHttpData()
{
$value = $this->getHttpData(Form::DATA_LINE);
$this->rawValue = $value;
$parts = explode(':', $value, 3);
$this->hour = isset($parts[0]) ? self::toInt($parts[0]) : NULL;
$this->minute = isset($parts[1]) ? self::toInt($parts[1]) : NULL;
}
public function getControl()
{
$control = parent::getControl();
$control->value = $this->rawValue;
return $control;
}
public static function validateTime(Nette\Forms\IControl $control)
{
if ($control->hour !== NULL && $control->minute !== NULL) {
if ($control->hour < 0 || $control->hour > 23) {
return FALSE;
}
if ($control->minute < 0 || $control->minute > 59) {
return FALSE;
}
return TRUE;
}
return FALSE;
}
private static function toInt($value)
{
$value = trim($value);
if ($value !== '') {
$value = ltrim($value, '0');
$value = $value !== '' ? $value : '0';
}
$tmp = abs((int) $value);
return ((string) $tmp) === $value ? $tmp : NULL;
}
}