PluginProbe
The Innovative Form Builder – IvyForms / 0.5
The Innovative Form Builder – IvyForms v0.5
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 0.5, at backend/src/Common/Helpers/DateTimeHelper/DateTimeHelper.php

159 lines 4.8 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 // phpcs:disable PSR1.Files.SideEffects
6 if (!defined('ABSPATH')) {
7 exit; // Exit if accessed directly
8 }
9 use DateTimeImmutable;
10 use DateTimeZone;
11 use RuntimeException;
12 use IvyForms\Services\Translations\BackendStrings;
13
14 /**
15 * Helper utilities for date and time operations.
16 */
17 class DateTimeHelper
18 {
19 /**
20 * Convert time string (HH:MM or HH:MM:SS) to Unix timestamp using current date in WP timezone.
21 *
22 * @param mixed $value Time value (HH:MM, HH:MM:SS, or numeric timestamp)
23 * @return int|null Unix timestamp or null if invalid
24 */
25 public static function timeToTimestamp($value): ?int
26 {
27 if ($value === null || $value === '') {
28 return null;
29 }
30
31 // If already numeric (timestamp), validate and return
32 if (is_numeric($value)) {
33 return (int)$value;
34 }
35
36 $timeString = trim((string)$value);
37 return self::parseTimeStringToTimestamp($timeString);
38 }
39
40 /**
41 * Parse time string (HH:MM or HH:MM:SS) to Unix timestamp.
42 *
43 * @param string $timeString Time string to parse
44 * @return int|null Unix timestamp or null if invalid
45 */
46 private static function parseTimeStringToTimestamp(string $timeString): ?int
47 {
48 if (!preg_match('/^(\d{1,2}):(\d{2})(?::(\d{2}))?$/', $timeString, $matches)) {
49 return null;
50 }
51
52 $hours = (int)$matches[1];
53 $minutes = (int)$matches[2];
54 $seconds = isset($matches[3]) ? (int)$matches[3] : 0;
55
56 if (!self::isValidTimeComponents($hours, $minutes, $seconds)) {
57 return null;
58 }
59
60 return self::createTimestampFromTime($hours, $minutes, $seconds);
61 }
62
63 /**
64 * Validate time components.
65 *
66 * @param int $hours Hours (0-23)
67 * @param int $minutes Minutes (0-59)
68 * @param int $seconds Seconds (0-59)
69 * @return bool True if valid
70 */
71 private static function isValidTimeComponents(int $hours, int $minutes, int $seconds): bool
72 {
73 return $hours <= 23 && $minutes <= 59 && $seconds <= 59;
74 }
75
76 /**
77 * Create Unix timestamp from time components using today's date.
78 *
79 * @param int $hours Hours
80 * @param int $minutes Minutes
81 * @param int $seconds Seconds
82 * @return int Unix timestamp
83 * @throws RuntimeException If unable to create timestamp
84 */
85 private static function createTimestampFromTime(int $hours, int $minutes, int $seconds): int
86 {
87 try {
88 $timezone = self::getWpTimezone();
89 $today = new DateTimeImmutable('today', $timezone);
90 $dateString = $today->format('Y-m-d');
91 $timeString = sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
92 $dateTime = new DateTimeImmutable("$dateString $timeString", $timezone);
93 return $dateTime->getTimestamp();
94 } catch (\Throwable $exception) {
95 throw new RuntimeException(
96 BackendStrings::getExceptionStrings()['time_conversion_failed'] . ': ' . $exception->getMessage()
97 );
98 }
99 }
100
101 /**
102 * Format Unix timestamp back to time string (HH:MM).
103 *
104 * @param int $timestamp Unix timestamp
105 * @return string Formatted time string without seconds
106 */
107 public static function timestampToTime(int $timestamp): string
108 {
109 $timezone = self::getWpTimezone();
110 $dateTime = new DateTimeImmutable('@' . $timestamp);
111 $dateTime = $dateTime->setTimezone($timezone);
112 return $dateTime->format('H:i');
113 }
114
115 /**
116 * Format Unix timestamp back to time string with seconds (HH:MM:SS).
117 *
118 * @param int $timestamp Unix timestamp
119 * @return string Formatted time string with seconds
120 */
121 public static function timestampToTimeWithSeconds(int $timestamp): string
122 {
123 $timezone = self::getWpTimezone();
124 $dateTime = new DateTimeImmutable('@' . $timestamp);
125 $dateTime = $dateTime->setTimezone($timezone);
126 return $dateTime->format('H:i:s');
127 }
128
129 /**
130 * Get WordPress timezone.
131 *
132 * @return DateTimeZone
133 * @throws RuntimeException If unable to get valid timezone
134 */
135 public static function getWpTimezone(): DateTimeZone
136 {
137 if (!function_exists('wp_timezone')) {
138 throw new RuntimeException(BackendStrings::getExceptionStrings()['wp_timezone_not_exist']);
139 }
140
141 return wp_timezone();
142 }
143
144 /**
145 * Normalize time values to Unix timestamp format.
146 *
147 * @param int|string|null $value Field value
148 * @return string Normalized value as string
149 */
150 public static function normalizeTimeValue($value): string
151 {
152 if ($value === null || $value === '') {
153 return '';
154 }
155
156 return (string)(self::timeToTimestamp($value) ?? $value);
157 }
158 }
159