PluginProbe
The Innovative Form Builder – IvyForms / 1.0
The Innovative Form Builder – IvyForms v1.0
1.5.1 1.5 1.4.1 1.4 trunk 0.1.2 0.2 0.2.1 0.3 0.3.1 0.4 0.5 0.6 0.6.1 0.6.1-backup 0.6.1.1 0.7 0.8 0.8.1 0.8.2 0.9 0.9.1 1.0 1.1 1.1.1 All 27 releases
ivyforms / backend / src / Common / Helpers / DateTimeHelper / DateTimeHelper.php

DateTimeHelper.php in The Innovative Form Builder – IvyForms 1.0, at backend/src/Common/Helpers/DateTimeHelper/DateTimeHelper.php

244 lines 7.4 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace IvyForms\Common\Helpers\DateTimeHelper;
4
5 use DateTimeImmutable;
6 use DateTimeZone;
7 use Exception;
8 use RuntimeException;
9 use IvyForms\Services\Translations\BackendStrings;
10
11 /**
12 * Helper utilities for date and time operations.
13 */
14 class DateTimeHelper
15 {
16 /**
17 * Convert time string (HH:MM or HH:MM:SS) to Unix timestamp using current date in WP timezone.
18 *
19 * @param mixed $value Time value (HH:MM, HH:MM:SS, or numeric timestamp)
20 * @return int|null Unix timestamp or null if invalid
21 */
22 public static function timeToTimestamp($value): ?int
23 {
24 if ($value === null || $value === '') {
25 return null;
26 }
27
28 // If already numeric (timestamp), validate and return
29 if (is_numeric($value)) {
30 return (int)$value;
31 }
32
33 $timeString = trim((string)$value);
34 return self::parseTimeStringToTimestamp($timeString);
35 }
36
37 /**
38 * Parse time string (HH:MM or HH:MM:SS) to Unix timestamp.
39 *
40 * @param string $timeString Time string to parse
41 * @return int|null Unix timestamp or null if invalid
42 */
43 private static function parseTimeStringToTimestamp(string $timeString): ?int
44 {
45 if (!preg_match('/^(\d{1,2}):(\d{2})(?::(\d{2}))?$/', $timeString, $matches)) {
46 return null;
47 }
48
49 $hours = (int)$matches[1];
50 $minutes = (int)$matches[2];
51 $seconds = isset($matches[3]) ? (int)$matches[3] : 0;
52
53 if (!self::isValidTimeComponents($hours, $minutes, $seconds)) {
54 return null;
55 }
56
57 return self::createTimestampFromTime($hours, $minutes, $seconds);
58 }
59
60 /**
61 * Validate time components.
62 *
63 * @param int $hours Hours (0-23)
64 * @param int $minutes Minutes (0-59)
65 * @param int $seconds Seconds (0-59)
66 * @return bool True if valid
67 */
68 private static function isValidTimeComponents(int $hours, int $minutes, int $seconds): bool
69 {
70 return $hours <= 23 && $minutes <= 59 && $seconds <= 59;
71 }
72
73 /**
74 * Create Unix timestamp from time components using today's date.
75 *
76 * @param int $hours Hours
77 * @param int $minutes Minutes
78 * @param int $seconds Seconds
79 * @return int Unix timestamp
80 * @throws RuntimeException If unable to create timestamp
81 */
82 private static function createTimestampFromTime(int $hours, int $minutes, int $seconds): int
83 {
84 try {
85 $timezone = self::getWpTimezone();
86 $today = new DateTimeImmutable('today', $timezone);
87 $dateString = $today->format('Y-m-d');
88 $timeString = sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
89 $dateTime = new DateTimeImmutable("$dateString $timeString", $timezone);
90 return $dateTime->getTimestamp();
91 } catch (\Throwable $exception) {
92 throw new RuntimeException(
93 BackendStrings::getExceptionStrings()['time_conversion_failed'] . ': ' . $exception->getMessage()
94 );
95 }
96 }
97
98 /**
99 * Format Unix timestamp back to time string (HH:MM).
100 *
101 * @param int $timestamp Unix timestamp
102 * @return string Formatted time string without seconds
103 */
104 public static function timestampToTime(int $timestamp): string
105 {
106 $timezone = self::getWpTimezone();
107 $dateTime = new DateTimeImmutable('@' . $timestamp);
108 $dateTime = $dateTime->setTimezone($timezone);
109 return $dateTime->format('H:i');
110 }
111
112 /**
113 * Format Unix timestamp back to time string with seconds (HH:MM:SS).
114 *
115 * @param int $timestamp Unix timestamp
116 * @return string Formatted time string with seconds
117 */
118 public static function timestampToTimeWithSeconds(int $timestamp): string
119 {
120 $timezone = self::getWpTimezone();
121 $dateTime = new DateTimeImmutable('@' . $timestamp);
122 $dateTime = $dateTime->setTimezone($timezone);
123 return $dateTime->format('H:i:s');
124 }
125
126 /**
127 * Get WordPress timezone.
128 *
129 * @return DateTimeZone
130 * @throws RuntimeException If unable to get valid timezone
131 */
132 public static function getWpTimezone(): DateTimeZone
133 {
134 if (!function_exists('wp_timezone')) {
135 throw new RuntimeException(BackendStrings::getExceptionStrings()['wp_timezone_not_exist']);
136 }
137
138 return wp_timezone();
139 }
140
141 /**
142 * Normalize time values to Unix timestamp format.
143 *
144 * @param int|string|null $value Field value
145 * @return string Normalized value as string
146 */
147 public static function normalizeTimeValue($value): string
148 {
149 if ($value === null || $value === '') {
150 return '';
151 }
152
153 return (string)(self::timeToTimestamp($value) ?? $value);
154 }
155
156 /**
157 * Convert date string (YYYY-MM-DD or various formats) to Unix timestamp.
158 *
159 * @param mixed $value Date value (YYYY-MM-DD, or numeric timestamp)
160 * @return int|null Unix timestamp or null if invalid
161 */
162 public static function dateToTimestamp($value): ?int
163 {
164 if ($value === null || $value === '') {
165 return null;
166 }
167
168 // If already numeric (timestamp), validate and return
169 if (is_numeric($value)) {
170 return (int)$value;
171 }
172
173 $dateString = trim((string)$value);
174 return self::parseDateStringToTimestamp($dateString);
175 }
176
177 /**
178 * Parse date string to Unix timestamp.
179 *
180 * @param string $dateString Date string to parse
181 * @return int|null Unix timestamp or null if invalid
182 */
183 public static function parseDateStringToTimestamp(string $dateString): ?int
184 {
185 try {
186 $timezone = self::getWpTimezone();
187 $dateTime = new DateTimeImmutable($dateString, $timezone);
188
189 // Set time to midnight (00:00:00) for date-only values
190 $dateTime = $dateTime->setTime(0, 0, 0);
191
192 return $dateTime->getTimestamp();
193 } catch (\Throwable $exception) {
194 return null;
195 }
196 }
197
198 /**
199 * Format Unix timestamp back to date string (YYYY-MM-DD).
200 *
201 * @param int $timestamp Unix timestamp
202 * @return string Formatted date string
203 * @throws Exception
204 */
205 public static function timestampToDate(int $timestamp): string
206 {
207 $timezone = self::getWpTimezone();
208 $dateTime = new DateTimeImmutable('@' . $timestamp);
209 $dateTime = $dateTime->setTimezone($timezone);
210 return $dateTime->format('Y-m-d');
211 }
212
213 /**
214 * Format Unix timestamp to a custom date format.
215 *
216 * @param int $timestamp Unix timestamp
217 * @param string $format PHP date format string
218 * @return string Formatted date string
219 * @throws Exception
220 */
221 public static function timestampToDateFormat(int $timestamp, string $format): string
222 {
223 $timezone = self::getWpTimezone();
224 $dateTime = new DateTimeImmutable('@' . $timestamp);
225 $dateTime = $dateTime->setTimezone($timezone);
226 return $dateTime->format($format);
227 }
228
229 /**
230 * Normalize date values to Unix timestamp format.
231 *
232 * @param int|string|null $value Field value
233 * @return string Normalized value as string
234 */
235 public static function normalizeDateValue($value): string
236 {
237 if ($value === null || $value === '') {
238 return '';
239 }
240
241 return (string)(self::dateToTimestamp($value) ?? $value);
242 }
243 }
244