1: <?php
2:
3: /**
4: * PhpOptions
5: * @link https://github.com/masicek/PhpOptions
6: * @author Viktor Mašíček <viktor@masicek.net>
7: * @license "New" BSD License
8: */
9:
10: namespace PhpOptions\Types;
11:
12: require_once __DIR__ . '/AType.php';
13:
14: /**
15: * Time type
16: *
17: * Format: HOURS[(-|:)MINUTES[(-|:)SECONDS]][ HOURS_FORMAT]
18: * HOURS = one-digit or two-digit number
19: * MINUTES = one-digit or two-digit number
20: * SECONDS = one-digit or two-digit number
21: * HOURS_FORMAT = hour format = (AM|am|A|a|PM|pm|P|p)
22: *
23: * @author Viktor Mašíček <viktor@masicek.net>
24: */
25: class TimeType extends AType
26: {
27:
28:
29: /**
30: * Check type of value.
31: *
32: * @param mixed $value Checked value
33: *
34: * @return bool
35: */
36: public function check($value)
37: {
38: $dateString = $this->getTimeString($value);
39:
40: $isDate = FALSE;
41: if ($dateString)
42: {
43: // check validation
44: try {
45: $dateObj = new \DateTime($dateString);
46: $isDate = ($dateObj) ? TRUE : FALSE;
47: } catch (\Exception $e) {
48: $isDate = FALSE;
49: }
50: }
51:
52: return $isDate;
53: }
54:
55:
56: /**
57: * Return modified value
58: *
59: * @param mixed $value Filtered value
60: *
61: * @return mixed
62: */
63: protected function useFilter($value)
64: {
65: return $this->getTimeString($value);
66: }
67:
68:
69: /**
70: * Return input date formated for DateTime object.
71: *
72: * @param string $value
73: *
74: * @return string
75: */
76: private function getTimeString($value)
77: {
78: // parse value
79: $match = preg_match('/^([0-9]{1,2})([-:]([0-9]{1,2})([-:]([0-9]{1,2}))?)?( *(AM|am|A|a|PM|pm|P|p))?$/', $value, $matches);
80: $date = '';
81: if ($match)
82: {
83: // prepare date string
84: $hours = $this->complete(isset($matches[1]) ? $matches[1] : '');
85: $minutes = $this->complete(isset($matches[3]) ? $matches[3] : '');
86: $seconds = $this->complete(isset($matches[5]) ? $matches[5] : '');
87: $hoursFormat = isset($matches[7]) ? $matches[7] : '';
88: if (strlen($hoursFormat) == 1)
89: {
90: $hoursFormat = $hoursFormat . 'M';
91: }
92: $hoursFormat = strtoupper($hoursFormat);
93: $date = $hours . ':' . $minutes . ':' . $seconds . $hoursFormat;
94: }
95:
96: return $date;
97: }
98:
99:
100: /**
101: * Add zero if input value have only one character
102: * Return two zero '00' if input value have not any character
103: *
104: * @param string $value
105: *
106: * @return string
107: */
108: private function complete($value)
109: {
110: $length = strlen($value);
111: if ($length == 1)
112: {
113: $value = '0' . $value;
114: }
115: elseif ($length == 0)
116: {
117: $value = '00';
118: }
119:
120: return $value;
121: }
122:
123:
124: }
125: