Debian Codegraph @

lib/3rdParty/composer/nesbot/carbon/src/Carbon/CarbonTimeZone.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 /**
6 * This file is part of the Carbon package.
7 *
8 * (c) Brian Nesbitt <[email protected]>
9 *
10 * For the full copyright and license information, please view the LICENSE
11 * file that was distributed with this source code.
12 */
13
14 namespace Carbon;
15
16 use Carbon\Exceptions\InvalidCastException;
17 use Carbon\Exceptions\InvalidTimeZoneException;
18 use Carbon\Traits\LocalFactory;
19 use DateTimeImmutable;
20 use DateTimeInterface;
21 use DateTimeZone;
22 use Exception;
23 use Throwable;
24
25 class CarbonTimeZone extends DateTimeZone
26 {
27 use LocalFactory;
28
29 public const MAXIMUM_TIMEZONE_OFFSET = 99;
30
31 public function __construct(string|int|float $timezone)
32 {
33 $this->initLocalFactory();
34
35 parent::__construct(static::getDateTimeZoneNameFromMixed($timezone));
36 }
37
38 protected static function parseNumericTimezone(string|int|float $timezone): string
39 {
40 if (abs((float) $timezone) > static::MAXIMUM_TIMEZONE_OFFSET) {
41 throw new InvalidTimeZoneException(
42 'Absolute timezone offset cannot be greater than '.
43 static::MAXIMUM_TIMEZONE_OFFSET.'.',
44 );
45 }
46
47 return ($timezone >= 0 ? '+' : '').ltrim((string) $timezone, '+').':00';
48 }
49
50 protected static function getDateTimeZoneNameFromMixed(string|int|float $timezone): string
51 {
52 if (\is_string($timezone)) {
53 $timezone = preg_replace('/^\s*([+-]\d+)(\d{2})\s*$/', '$1:$2', $timezone);
54 }
55
56 if (is_numeric($timezone)) {
57 return static::parseNumericTimezone($timezone);
58 }
59
60 return $timezone;
61 }
62
63 /**
64 * Cast the current instance into the given class.
65 *
66 * @param class-string<DateTimeZone> $className The $className::instance() method will be called to cast the current object.
67 *
68 * @return DateTimeZone|mixed
69 */
70 public function cast(string $className): mixed
71 {
72 if (!method_exists($className, 'instance')) {
73 if (is_a($className, DateTimeZone::class, true)) {
74 return new $className($this->getName());
75 }
76
77 throw new InvalidCastException("$className has not the instance() method needed to cast the date.");
78 }
79
80 return $className::instance($this);
81 }
82
83 /**
84 * Create a CarbonTimeZone from mixed input.
85 *
86 * @param DateTimeZone|string|int|false|null $object original value to get CarbonTimeZone from it.
87 * @param DateTimeZone|string|int|false|null $objectDump dump of the object for error messages.
88 *
89 * @throws InvalidTimeZoneException
90 *
91 * @return static|null
92 */
93 public static function instance(
94 DateTimeZone|string|int|false|null $object,
95 DateTimeZone|string|int|false|null $objectDump = null,
96 ): ?self {
97 $timezone = $object;
98
99 if ($timezone instanceof static) {
100 return $timezone;
101 }
102
103 if ($timezone === null || $timezone === false) {
104 return null;
105 }
106
107 try {
108 if (!($timezone instanceof DateTimeZone)) {
109 $name = static::getDateTimeZoneNameFromMixed($object);
110 $timezone = new static($name);
111 }
112
113 return $timezone instanceof static ? $timezone : new static($timezone->getName());
114 } catch (Exception $exception) {
115 throw new InvalidTimeZoneException(
116 'Unknown or bad timezone ('.($objectDump ?: $object).')',
117 previous: $exception,
118 );
119 }
120 }
121
122 /**
123 * Returns abbreviated name of the current timezone according to DST setting.
124 *
125 * @param bool $dst
126 *
127 * @return string
128 */
129 public function getAbbreviatedName(bool $dst = false): string
130 {
131 $name = $this->getName();
132
133 $date = new DateTimeImmutable($dst ? 'July 1' : 'January 1', $this);
134 $timezone = $date->format('T');
135 $abbreviations = $this->listAbbreviations();
136 $matchingZones = array_merge($abbreviations[$timezone] ?? [], $abbreviations[strtolower($timezone)] ?? []);
137
138 if ($matchingZones !== []) {
139 foreach ($matchingZones as $zone) {
140 if ($zone['timezone_id'] === $name && $zone['dst'] == $dst) {
141 return $timezone;
142 }
143 }
144 }
145
146 foreach ($abbreviations as $abbreviation => $zones) {
147 foreach ($zones as $zone) {
148 if ($zone['timezone_id'] === $name && $zone['dst'] == $dst) {
149 return strtoupper($abbreviation);
150 }
151 }
152 }
153
154 return 'unknown';
155 }
156
157 /**
158 * @alias getAbbreviatedName
159 *
160 * Returns abbreviated name of the current timezone according to DST setting.
161 *
162 * @param bool $dst
163 *
164 * @return string
165 */
166 public function getAbbr(bool $dst = false): string
167 {
168 return $this->getAbbreviatedName($dst);
169 }
170
171 /**
172 * Get the offset as string "sHH:MM" (such as "+00:00" or "-12:30").
173 */
174 public function toOffsetName(?DateTimeInterface $date = null): string
175 {
176 return static::getOffsetNameFromMinuteOffset(
177 $this->getOffset($this->resolveCarbon($date)) / 60,
178 );
179 }
180
181 /**
182 * Returns a new CarbonTimeZone object using the offset string instead of region string.
183 */
184 public function toOffsetTimeZone(?DateTimeInterface $date = null): static
185 {
186 return new static($this->toOffsetName($date));
187 }
188
189 /**
190 * Returns the first region string (such as "America/Toronto") that matches the current timezone or
191 * false if no match is found.
192 *
193 * @see timezone_name_from_abbr native PHP function.
194 */
195 public function toRegionName(?DateTimeInterface $date = null, int $isDST = 1): ?string
196 {
197 $name = $this->getName();
198 $firstChar = substr($name, 0, 1);
199
200 if ($firstChar !== '+' && $firstChar !== '-') {
201 return $name;
202 }
203
204 $date = $this->resolveCarbon($date);
205
206 // Integer construction no longer supported since PHP 8
207 // @codeCoverageIgnoreStart
208 try {
209 $offset = @$this->getOffset($date) ?: 0;
210 } catch (Throwable) {
211 $offset = 0;
212 }
213 // @codeCoverageIgnoreEnd
214
215 $name = @timezone_name_from_abbr('', $offset, $isDST);
216
217 if ($name) {
218 return $name;
219 }
220
221 foreach (timezone_identifiers_list() as $timezone) {
222 if (Carbon::instance($date)->setTimezone($timezone)->getOffset() === $offset) {
223 return $timezone;
224 }
225 }
226
227 return null;
228 }
229
230 /**
231 * Returns a new CarbonTimeZone object using the region string instead of offset string.
232 */
233 public function toRegionTimeZone(?DateTimeInterface $date = null): ?self
234 {
235 $timezone = $this->toRegionName($date);
236
237 if ($timezone !== null) {
238 return new static($timezone);
239 }
240
241 if (Carbon::isStrictModeEnabled()) {
242 throw new InvalidTimeZoneException('Unknown timezone for offset '.$this->getOffset($this->resolveCarbon($date)).' seconds.');
243 }
244
245 return null;
246 }
247
248 /**
249 * Cast to string (get timezone name).
250 *
251 * @return string
252 */
253 public function __toString()
254 {
255 return $this->getName();
256 }
257
258 /**
259 * Return the type number:
260 *
261 * Type 1; A UTC offset, such as -0300
262 * Type 2; A timezone abbreviation, such as GMT
263 * Type 3: A timezone identifier, such as Europe/London
264 */
265 public function getType(): int
266 {
267 return preg_match('/"timezone_type";i:(\d)/', serialize($this), $match) ? (int) $match[1] : 3;
268 }
269
270 /**
271 * Create a CarbonTimeZone from mixed input.
272 *
273 * @param DateTimeZone|string|int|null $object
274 *
275 * @return false|static
276 */
277 public static function create($object = null)
278 {
279 return static::instance($object);
280 }
281
282 /**
283 * Create a CarbonTimeZone from int/float hour offset.
284 *
285 * @param float $hourOffset number of hour of the timezone shift (can be decimal).
286 *
287 * @return false|static
288 */
289 public static function createFromHourOffset(float $hourOffset)
290 {
291 return static::createFromMinuteOffset($hourOffset * Carbon::MINUTES_PER_HOUR);
292 }
293
294 /**
295 * Create a CarbonTimeZone from int/float minute offset.
296 *
297 * @param float $minuteOffset number of total minutes of the timezone shift.
298 *
299 * @return false|static
300 */
301 public static function createFromMinuteOffset(float $minuteOffset)
302 {
303 return static::instance(static::getOffsetNameFromMinuteOffset($minuteOffset));
304 }
305
306 /**
307 * Convert a total minutes offset into a standardized timezone offset string.
308 *
309 * @param float $minutes number of total minutes of the timezone shift.
310 *
311 * @return string
312 */
313 public static function getOffsetNameFromMinuteOffset(float $minutes): string
314 {
315 $minutes = round($minutes);
316 $unsignedMinutes = abs($minutes);
317
318 return ($minutes < 0 ? '-' : '+').
319 str_pad((string) floor($unsignedMinutes / 60), 2, '0', STR_PAD_LEFT).
320 ':'.
321 str_pad((string) ($unsignedMinutes % 60), 2, '0', STR_PAD_LEFT);
322 }
323
324 private function resolveCarbon(?DateTimeInterface $date): DateTimeInterface
325 {
326 if ($date) {
327 return $date;
328 }
329
330 if (isset($this->clock)) {
331 return $this->clock->now()->setTimezone($this);
332 }
333
334 return Carbon::now($this);
335 }
336 }