Debian Codegraph @

lib/3rdParty/composer/nesbot/carbon/src/Carbon/Traits/Converter.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\Traits;
15
16 use Carbon\Carbon;
17 use Carbon\CarbonImmutable;
18 use Carbon\CarbonInterface;
19 use Carbon\CarbonInterval;
20 use Carbon\CarbonPeriod;
21 use Carbon\CarbonPeriodImmutable;
22 use Carbon\Exceptions\UnitException;
23 use Closure;
24 use DateTime;
25 use DateTimeImmutable;
26 use DateTimeInterface;
27
28 /**
29 * Trait Converter.
30 *
31 * Change date into different string formats and types and
32 * handle the string cast.
33 *
34 * Depends on the following methods:
35 *
36 * @method static copy()
37 */
38 trait Converter
39 {
40 use ToStringFormat;
41
42 /**
43 * Returns the formatted date string on success or FALSE on failure.
44 *
45 * @see https://php.net/manual/en/datetime.format.php
46 */
47 public function format(string $format): string
48 {
49 $function = $this->localFormatFunction
50 ?? $this->getFactory()->getSettings()['formatFunction']
51 ?? static::$formatFunction;
52
53 if (!$function) {
54 return $this->rawFormat($format);
55 }
56
57 if (\is_string($function) && method_exists($this, $function)) {
58 $function = [$this, $function];
59 }
60
61 return $function(...\func_get_args());
62 }
63
64 /**
65 * @see https://php.net/manual/en/datetime.format.php
66 */
67 public function rawFormat(string $format): string
68 {
69 return parent::format($format);
70 }
71
72 /**
73 * Format the instance as a string using the set format
74 *
75 * @example
76 * ```
77 * echo Carbon::now(); // Carbon instances can be cast to string
78 * ```
79 */
80 public function __toString(): string
81 {
82 $format = $this->localToStringFormat
83 ?? $this->getFactory()->getSettings()['toStringFormat']
84 ?? null;
85
86 return $format instanceof Closure
87 ? $format($this)
88 : $this->rawFormat($format ?: (
89 \defined('static::DEFAULT_TO_STRING_FORMAT')
90 ? static::DEFAULT_TO_STRING_FORMAT
91 : CarbonInterface::DEFAULT_TO_STRING_FORMAT
92 ));
93 }
94
95 /**
96 * Format the instance as date
97 *
98 * @example
99 * ```
100 * echo Carbon::now()->toDateString();
101 * ```
102 */
103 public function toDateString(): string
104 {
105 return $this->rawFormat('Y-m-d');
106 }
107
108 /**
109 * Format the instance as a readable date
110 *
111 * @example
112 * ```
113 * echo Carbon::now()->toFormattedDateString();
114 * ```
115 */
116 public function toFormattedDateString(): string
117 {
118 return $this->rawFormat('M j, Y');
119 }
120
121 /**
122 * Format the instance with the day, and a readable date
123 *
124 * @example
125 * ```
126 * echo Carbon::now()->toFormattedDayDateString();
127 * ```
128 */
129 public function toFormattedDayDateString(): string
130 {
131 return $this->rawFormat('D, M j, Y');
132 }
133
134 /**
135 * Format the instance as time
136 *
137 * @example
138 * ```
139 * echo Carbon::now()->toTimeString();
140 * ```
141 */
142 public function toTimeString(string $unitPrecision = 'second'): string
143 {
144 return $this->rawFormat(static::getTimeFormatByPrecision($unitPrecision));
145 }
146
147 /**
148 * Format the instance as date and time
149 *
150 * @example
151 * ```
152 * echo Carbon::now()->toDateTimeString();
153 * ```
154 */
155 public function toDateTimeString(string $unitPrecision = 'second'): string
156 {
157 return $this->rawFormat('Y-m-d '.static::getTimeFormatByPrecision($unitPrecision));
158 }
159
160 /**
161 * Return a format from H:i to H:i:s.u according to given unit precision.
162 *
163 * @param string $unitPrecision "minute", "second", "millisecond" or "microsecond"
164 */
165 public static function getTimeFormatByPrecision(string $unitPrecision): string
166 {
167 return match (static::singularUnit($unitPrecision)) {
168 'minute' => 'H:i',
169 'second' => 'H:i:s',
170 'm', 'millisecond' => 'H:i:s.v',
171 'ยต', 'microsecond' => 'H:i:s.u',
172 default => throw new UnitException('Precision unit expected among: minute, second, millisecond and microsecond.'),
173 };
174 }
175
176 /**
177 * Format the instance as date and time T-separated with no timezone
178 *
179 * @example
180 * ```
181 * echo Carbon::now()->toDateTimeLocalString();
182 * echo "\n";
183 * echo Carbon::now()->toDateTimeLocalString('minute'); // You can specify precision among: minute, second, millisecond and microsecond
184 * ```
185 */
186 public function toDateTimeLocalString(string $unitPrecision = 'second'): string
187 {
188 return $this->rawFormat('Y-m-d\T'.static::getTimeFormatByPrecision($unitPrecision));
189 }
190
191 /**
192 * Format the instance with day, date and time
193 *
194 * @example
195 * ```
196 * echo Carbon::now()->toDayDateTimeString();
197 * ```
198 */
199 public function toDayDateTimeString(): string
200 {
201 return $this->rawFormat('D, M j, Y g:i A');
202 }
203
204 /**
205 * Format the instance as ATOM
206 *
207 * @example
208 * ```
209 * echo Carbon::now()->toAtomString();
210 * ```
211 */
212 public function toAtomString(): string
213 {
214 return $this->rawFormat(DateTime::ATOM);
215 }
216
217 /**
218 * Format the instance as COOKIE
219 *
220 * @example
221 * ```
222 * echo Carbon::now()->toCookieString();
223 * ```
224 */
225 public function toCookieString(): string
226 {
227 return $this->rawFormat(DateTimeInterface::COOKIE);
228 }
229
230 /**
231 * Format the instance as ISO8601
232 *
233 * @example
234 * ```
235 * echo Carbon::now()->toIso8601String();
236 * ```
237 */
238 public function toIso8601String(): string
239 {
240 return $this->toAtomString();
241 }
242
243 /**
244 * Format the instance as RFC822
245 *
246 * @example
247 * ```
248 * echo Carbon::now()->toRfc822String();
249 * ```
250 */
251 public function toRfc822String(): string
252 {
253 return $this->rawFormat(DateTimeInterface::RFC822);
254 }
255
256 /**
257 * Convert the instance to UTC and return as Zulu ISO8601
258 *
259 * @example
260 * ```
261 * echo Carbon::now()->toIso8601ZuluString();
262 * ```
263 */
264 public function toIso8601ZuluString(string $unitPrecision = 'second'): string
265 {
266 return $this->avoidMutation()
267 ->utc()
268 ->rawFormat('Y-m-d\T'.static::getTimeFormatByPrecision($unitPrecision).'\Z');
269 }
270
271 /**
272 * Format the instance as RFC850
273 *
274 * @example
275 * ```
276 * echo Carbon::now()->toRfc850String();
277 * ```
278 */
279 public function toRfc850String(): string
280 {
281 return $this->rawFormat(DateTimeInterface::RFC850);
282 }
283
284 /**
285 * Format the instance as RFC1036
286 *
287 * @example
288 * ```
289 * echo Carbon::now()->toRfc1036String();
290 * ```
291 */
292 public function toRfc1036String(): string
293 {
294 return $this->rawFormat(DateTimeInterface::RFC1036);
295 }
296
297 /**
298 * Format the instance as RFC1123
299 *
300 * @example
301 * ```
302 * echo Carbon::now()->toRfc1123String();
303 * ```
304 */
305 public function toRfc1123String(): string
306 {
307 return $this->rawFormat(DateTimeInterface::RFC1123);
308 }
309
310 /**
311 * Format the instance as RFC2822
312 *
313 * @example
314 * ```
315 * echo Carbon::now()->toRfc2822String();
316 * ```
317 */
318 public function toRfc2822String(): string
319 {
320 return $this->rawFormat(DateTimeInterface::RFC2822);
321 }
322
323 /**
324 * Format the instance as RFC3339.
325 *
326 * @example
327 * ```
328 * echo Carbon::now()->toRfc3339String() . "\n";
329 * echo Carbon::now()->toRfc3339String(true) . "\n";
330 * ```
331 */
332 public function toRfc3339String(bool $extended = false): string
333 {
334 return $this->rawFormat($extended ? DateTimeInterface::RFC3339_EXTENDED : DateTimeInterface::RFC3339);
335 }
336
337 /**
338 * Format the instance as RSS
339 *
340 * @example
341 * ```
342 * echo Carbon::now()->toRssString();
343 * ```
344 */
345 public function toRssString(): string
346 {
347 return $this->rawFormat(DateTimeInterface::RSS);
348 }
349
350 /**
351 * Format the instance as W3C
352 *
353 * @example
354 * ```
355 * echo Carbon::now()->toW3cString();
356 * ```
357 */
358 public function toW3cString(): string
359 {
360 return $this->rawFormat(DateTimeInterface::W3C);
361 }
362
363 /**
364 * Format the instance as RFC7231
365 *
366 * @example
367 * ```
368 * echo Carbon::now()->toRfc7231String();
369 * ```
370 */
371 public function toRfc7231String(): string
372 {
373 return $this->avoidMutation()
374 ->setTimezone('GMT')
375 ->rawFormat(\defined('static::RFC7231_FORMAT') ? static::RFC7231_FORMAT : CarbonInterface::RFC7231_FORMAT);
376 }
377
378 /**
379 * Get default array representation.
380 *
381 * @example
382 * ```
383 * var_dump(Carbon::now()->toArray());
384 * ```
385 */
386 public function toArray(): array
387 {
388 return [
389 'year' => $this->year,
390 'month' => $this->month,
391 'day' => $this->day,
392 'dayOfWeek' => $this->dayOfWeek,
393 'dayOfYear' => $this->dayOfYear,
394 'hour' => $this->hour,
395 'minute' => $this->minute,
396 'second' => $this->second,
397 'micro' => $this->micro,
398 'timestamp' => $this->timestamp,
399 'formatted' => $this->rawFormat(\defined('static::DEFAULT_TO_STRING_FORMAT') ? static::DEFAULT_TO_STRING_FORMAT : CarbonInterface::DEFAULT_TO_STRING_FORMAT),
400 'timezone' => $this->timezone,
401 ];
402 }
403
404 /**
405 * Get default object representation.
406 *
407 * @example
408 * ```
409 * var_dump(Carbon::now()->toObject());
410 * ```
411 */
412 public function toObject(): object
413 {
414 return (object) $this->toArray();
415 }
416
417 /**
418 * Returns english human-readable complete date string.
419 *
420 * @example
421 * ```
422 * echo Carbon::now()->toString();
423 * ```
424 */
425 public function toString(): string
426 {
427 return $this->avoidMutation()->locale('en')->isoFormat('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
428 }
429
430 /**
431 * Return the ISO-8601 string (ex: 1977-04-22T06:00:00Z, if $keepOffset truthy, offset will be kept:
432 * 1977-04-22T01:00:00-05:00).
433 *
434 * @example
435 * ```
436 * echo Carbon::now('America/Toronto')->toISOString() . "\n";
437 * echo Carbon::now('America/Toronto')->toISOString(true) . "\n";
438 * ```
439 *
440 * @param bool $keepOffset Pass true to keep the date offset. Else forced to UTC.
441 */
442 public function toISOString(bool $keepOffset = false): ?string
443 {
444 if (!$this->isValid()) {
445 return null;
446 }
447
448 $yearFormat = $this->year < 0 || $this->year > 9999 ? 'YYYYYY' : 'YYYY';
449 $timezoneFormat = $keepOffset ? 'Z' : '[Z]';
450 $date = $keepOffset ? $this : $this->avoidMutation()->utc();
451
452 return $date->isoFormat("$yearFormat-MM-DD[T]HH:mm:ss.SSSSSS$timezoneFormat");
453 }
454
455 /**
456 * Return the ISO-8601 string (ex: 1977-04-22T06:00:00Z) with UTC timezone.
457 *
458 * @example
459 * ```
460 * echo Carbon::now('America/Toronto')->toJSON();
461 * ```
462 */
463 public function toJSON(): ?string
464 {
465 return $this->toISOString();
466 }
467
468 /**
469 * Return native DateTime PHP object matching the current instance.
470 *
471 * @example
472 * ```
473 * var_dump(Carbon::now()->toDateTime());
474 * ```
475 */
476 public function toDateTime(): DateTime
477 {
478 return DateTime::createFromFormat('U.u', $this->rawFormat('U.u'))
479 ->setTimezone($this->getTimezone());
480 }
481
482 /**
483 * Return native toDateTimeImmutable PHP object matching the current instance.
484 *
485 * @example
486 * ```
487 * var_dump(Carbon::now()->toDateTimeImmutable());
488 * ```
489 */
490 public function toDateTimeImmutable(): DateTimeImmutable
491 {
492 return DateTimeImmutable::createFromFormat('U.u', $this->rawFormat('U.u'))
493 ->setTimezone($this->getTimezone());
494 }
495
496 /**
497 * @alias toDateTime
498 *
499 * Return native DateTime PHP object matching the current instance.
500 *
501 * @example
502 * ```
503 * var_dump(Carbon::now()->toDate());
504 * ```
505 */
506 public function toDate(): DateTime
507 {
508 return $this->toDateTime();
509 }
510
511 /**
512 * Create a iterable CarbonPeriod object from current date to a given end date (and optional interval).
513 *
514 * @param \DateTimeInterface|Carbon|CarbonImmutable|int|null $end period end date or recurrences count if int
515 * @param int|\DateInterval|string|null $interval period default interval or number of the given $unit
516 * @param string|null $unit if specified, $interval must be an integer
517 */
518 public function toPeriod($end = null, $interval = null, $unit = null): CarbonPeriod
519 {
520 if ($unit) {
521 $interval = CarbonInterval::make("$interval ".static::pluralUnit($unit));
522 }
523
524 $isDefaultInterval = !$interval;
525 $interval ??= CarbonInterval::day();
526 $class = $this->isMutable() ? CarbonPeriod::class : CarbonPeriodImmutable::class;
527
528 if (\is_int($end) || (\is_string($end) && ctype_digit($end))) {
529 $end = (int) $end;
530 }
531
532 $end ??= 1;
533
534 if (!\is_int($end)) {
535 $end = $this->resolveCarbon($end);
536 }
537
538 return new $class(
539 raw: [$this, CarbonInterval::make($interval), $end],
540 dateClass: static::class,
541 isDefaultInterval: $isDefaultInterval,
542 );
543 }
544
545 /**
546 * Create a iterable CarbonPeriod object from current date to a given end date (and optional interval).
547 *
548 * @param \DateTimeInterface|Carbon|CarbonImmutable|null $end period end date
549 * @param int|\DateInterval|string|null $interval period default interval or number of the given $unit
550 * @param string|null $unit if specified, $interval must be an integer
551 */
552 public function range($end = null, $interval = null, $unit = null): CarbonPeriod
553 {
554 return $this->toPeriod($end, $interval, $unit);
555 }
556 }