| 1: | <?php |
| 2: | declare(strict_types=1); |
| 3: | |
| 4: | namespace om\ICal\Value; |
| 5: | |
| 6: | use om\ICal\Exception\InvalidValueException; |
| 7: | |
| 8: | |
| 9: | |
| 10: | |
| 11: | final class UtcOffset { |
| 12: | |
| 13: | |
| 14: | |
| 15: | public static function parse(string $value): int { |
| 16: | if (!preg_match('/^([+-])(\d{2})(\d{2})(\d{2})?$/D', trim($value), $match)) { |
| 17: | throw InvalidValueException::create('value.invalid-utc-offset', "Invalid UTC-OFFSET value: $value", rawValue: $value); |
| 18: | } |
| 19: | $seconds = (int) $match[2] * 3600 + (int) $match[3] * 60 + (int) ($match[4] ?? 0); |
| 20: | return $match[1] === '-' ? -$seconds : $seconds; |
| 21: | } |
| 22: | |
| 23: | public static function format(int $seconds): string { |
| 24: | $sign = $seconds < 0 ? '-' : '+'; |
| 25: | $seconds = abs($seconds); |
| 26: | $result = sprintf('%s%02d%02d', $sign, intdiv($seconds, 3600), intdiv($seconds % 3600, 60)); |
| 27: | return $seconds % 60 ? $result . sprintf('%02d', $seconds % 60) : $result; |
| 28: | } |
| 29: | } |
| 30: | |