Remove the vendor directory in .gitignore as these dependencies are needed for php-imap

This commit is contained in:
johnnyq
2024-06-12 16:15:10 -04:00
parent 779527cf6a
commit 2edd39c16d
2890 changed files with 248719 additions and 2 deletions

View File

@@ -0,0 +1,434 @@
<?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Carbon\Traits;
use Carbon\Exceptions\UnknownUnitException;
use Carbon\WeekDay;
/**
* Trait Boundaries.
*
* startOf, endOf and derived method for each unit.
*
* Depends on the following properties:
*
* @property int $year
* @property int $month
* @property int $daysInMonth
* @property int $quarter
*
* Depends on the following methods:
*
* @method $this setTime(int $hour, int $minute, int $second = 0, int $microseconds = 0)
* @method $this setDate(int $year, int $month, int $day)
* @method $this addMonths(int $value = 1)
*/
trait Boundaries
{
/**
* Resets the time to 00:00:00 start of day
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->startOfDay();
* ```
*
* @return static
*/
public function startOfDay()
{
return $this->setTime(0, 0, 0, 0);
}
/**
* Resets the time to 23:59:59.999999 end of day
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->endOfDay();
* ```
*
* @return static
*/
public function endOfDay()
{
return $this->setTime(static::HOURS_PER_DAY - 1, static::MINUTES_PER_HOUR - 1, static::SECONDS_PER_MINUTE - 1, static::MICROSECONDS_PER_SECOND - 1);
}
/**
* Resets the date to the first day of the month and the time to 00:00:00
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->startOfMonth();
* ```
*
* @return static
*/
public function startOfMonth()
{
return $this->setDate($this->year, $this->month, 1)->startOfDay();
}
/**
* Resets the date to end of the month and time to 23:59:59.999999
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->endOfMonth();
* ```
*
* @return static
*/
public function endOfMonth()
{
return $this->setDate($this->year, $this->month, $this->daysInMonth)->endOfDay();
}
/**
* Resets the date to the first day of the quarter and the time to 00:00:00
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->startOfQuarter();
* ```
*
* @return static
*/
public function startOfQuarter()
{
$month = ($this->quarter - 1) * static::MONTHS_PER_QUARTER + 1;
return $this->setDate($this->year, $month, 1)->startOfDay();
}
/**
* Resets the date to end of the quarter and time to 23:59:59.999999
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->endOfQuarter();
* ```
*
* @return static
*/
public function endOfQuarter()
{
return $this->startOfQuarter()->addMonths(static::MONTHS_PER_QUARTER - 1)->endOfMonth();
}
/**
* Resets the date to the first day of the year and the time to 00:00:00
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->startOfYear();
* ```
*
* @return static
*/
public function startOfYear()
{
return $this->setDate($this->year, 1, 1)->startOfDay();
}
/**
* Resets the date to end of the year and time to 23:59:59.999999
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->endOfYear();
* ```
*
* @return static
*/
public function endOfYear()
{
return $this->setDate($this->year, 12, 31)->endOfDay();
}
/**
* Resets the date to the first day of the decade and the time to 00:00:00
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->startOfDecade();
* ```
*
* @return static
*/
public function startOfDecade()
{
$year = $this->year - $this->year % static::YEARS_PER_DECADE;
return $this->setDate($year, 1, 1)->startOfDay();
}
/**
* Resets the date to end of the decade and time to 23:59:59.999999
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->endOfDecade();
* ```
*
* @return static
*/
public function endOfDecade()
{
$year = $this->year - $this->year % static::YEARS_PER_DECADE + static::YEARS_PER_DECADE - 1;
return $this->setDate($year, 12, 31)->endOfDay();
}
/**
* Resets the date to the first day of the century and the time to 00:00:00
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->startOfCentury();
* ```
*
* @return static
*/
public function startOfCentury()
{
$year = $this->year - ($this->year - 1) % static::YEARS_PER_CENTURY;
return $this->setDate($year, 1, 1)->startOfDay();
}
/**
* Resets the date to end of the century and time to 23:59:59.999999
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->endOfCentury();
* ```
*
* @return static
*/
public function endOfCentury()
{
$year = $this->year - 1 - ($this->year - 1) % static::YEARS_PER_CENTURY + static::YEARS_PER_CENTURY;
return $this->setDate($year, 12, 31)->endOfDay();
}
/**
* Resets the date to the first day of the millennium and the time to 00:00:00
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->startOfMillennium();
* ```
*
* @return static
*/
public function startOfMillennium()
{
$year = $this->year - ($this->year - 1) % static::YEARS_PER_MILLENNIUM;
return $this->setDate($year, 1, 1)->startOfDay();
}
/**
* Resets the date to end of the millennium and time to 23:59:59.999999
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->endOfMillennium();
* ```
*
* @return static
*/
public function endOfMillennium()
{
$year = $this->year - 1 - ($this->year - 1) % static::YEARS_PER_MILLENNIUM + static::YEARS_PER_MILLENNIUM;
return $this->setDate($year, 12, 31)->endOfDay();
}
/**
* Resets the date to the first day of week (defined in $weekStartsAt) and the time to 00:00:00
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->startOfWeek() . "\n";
* echo Carbon::parse('2018-07-25 12:45:16')->locale('ar')->startOfWeek() . "\n";
* echo Carbon::parse('2018-07-25 12:45:16')->startOfWeek(Carbon::SUNDAY) . "\n";
* ```
*
* @param WeekDay|int|null $weekStartsAt optional start allow you to specify the day of week to use to start the week
*
* @return static
*/
public function startOfWeek(WeekDay|int|null $weekStartsAt = null): static
{
return $this
->subDays(
(static::DAYS_PER_WEEK + $this->dayOfWeek - (WeekDay::int($weekStartsAt) ?? $this->firstWeekDay)) %
static::DAYS_PER_WEEK,
)
->startOfDay();
}
/**
* Resets the date to end of week (defined in $weekEndsAt) and time to 23:59:59.999999
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->endOfWeek() . "\n";
* echo Carbon::parse('2018-07-25 12:45:16')->locale('ar')->endOfWeek() . "\n";
* echo Carbon::parse('2018-07-25 12:45:16')->endOfWeek(Carbon::SATURDAY) . "\n";
* ```
*
* @param WeekDay|int|null $weekEndsAt optional start allow you to specify the day of week to use to end the week
*
* @return static
*/
public function endOfWeek(WeekDay|int|null $weekEndsAt = null): static
{
return $this
->addDays(
(static::DAYS_PER_WEEK - $this->dayOfWeek + (WeekDay::int($weekEndsAt) ?? $this->lastWeekDay)) %
static::DAYS_PER_WEEK,
)
->endOfDay();
}
/**
* Modify to start of current hour, minutes and seconds become 0
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->startOfHour();
* ```
*/
public function startOfHour(): static
{
return $this->setTime($this->hour, 0, 0, 0);
}
/**
* Modify to end of current hour, minutes and seconds become 59
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->endOfHour();
* ```
*/
public function endOfHour(): static
{
return $this->setTime($this->hour, static::MINUTES_PER_HOUR - 1, static::SECONDS_PER_MINUTE - 1, static::MICROSECONDS_PER_SECOND - 1);
}
/**
* Modify to start of current minute, seconds become 0
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->startOfMinute();
* ```
*/
public function startOfMinute(): static
{
return $this->setTime($this->hour, $this->minute, 0, 0);
}
/**
* Modify to end of current minute, seconds become 59
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->endOfMinute();
* ```
*/
public function endOfMinute(): static
{
return $this->setTime($this->hour, $this->minute, static::SECONDS_PER_MINUTE - 1, static::MICROSECONDS_PER_SECOND - 1);
}
/**
* Modify to start of current second, microseconds become 0
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16.334455')
* ->startOfSecond()
* ->format('H:i:s.u');
* ```
*/
public function startOfSecond(): static
{
return $this->setTime($this->hour, $this->minute, $this->second, 0);
}
/**
* Modify to end of current second, microseconds become 999999
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16.334455')
* ->endOfSecond()
* ->format('H:i:s.u');
* ```
*/
public function endOfSecond(): static
{
return $this->setTime($this->hour, $this->minute, $this->second, static::MICROSECONDS_PER_SECOND - 1);
}
/**
* Modify to start of current given unit.
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16.334455')
* ->startOf('month')
* ->endOf('week', Carbon::FRIDAY);
* ```
*/
public function startOf(string $unit, mixed ...$params): static
{
$ucfUnit = ucfirst(static::singularUnit($unit));
$method = "startOf$ucfUnit";
if (!method_exists($this, $method)) {
throw new UnknownUnitException($unit);
}
return $this->$method(...$params);
}
/**
* Modify to end of current given unit.
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16.334455')
* ->startOf('month')
* ->endOf('week', Carbon::FRIDAY);
* ```
*/
public function endOf(string $unit, mixed ...$params): static
{
$ucfUnit = ucfirst(static::singularUnit($unit));
$method = "endOf$ucfUnit";
if (!method_exists($this, $method)) {
throw new UnknownUnitException($unit);
}
return $this->$method(...$params);
}
}

View File

@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Carbon\Traits;
use Carbon\Exceptions\InvalidCastException;
use DateTimeInterface;
/**
* Trait Cast.
*
* Utils to cast into an other class.
*/
trait Cast
{
/**
* Cast the current instance into the given class.
*
* @template T
*
* @param class-string<T> $className The $className::instance() method will be called to cast the current object.
*
* @return T
*/
public function cast(string $className): mixed
{
if (!method_exists($className, 'instance')) {
if (is_a($className, DateTimeInterface::class, true)) {
return new $className($this->rawFormat('Y-m-d H:i:s.u'), $this->getTimezone());
}
throw new InvalidCastException("$className has not the instance() method needed to cast the date.");
}
return $className::instance($this);
}
}

View File

@@ -0,0 +1,974 @@
<?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Carbon\Traits;
use BadMethodCallException;
use Carbon\CarbonInterface;
use Carbon\Exceptions\BadComparisonUnitException;
use Carbon\FactoryImmutable;
use DateTimeInterface;
use InvalidArgumentException;
/**
* Trait Comparison.
*
* Comparison utils and testers. All the following methods return booleans.
* nowWithSameTz
*
* Depends on the following methods:
*
* @method static resolveCarbon($date)
* @method static copy()
* @method static nowWithSameTz()
* @method static static yesterday($timezone = null)
* @method static static tomorrow($timezone = null)
*/
trait Comparison
{
protected bool $endOfTime = false;
protected bool $startOfTime = false;
/**
* Determines if the instance is equal to another
*
* @example
* ```
* Carbon::parse('2018-07-25 12:45:16')->eq('2018-07-25 12:45:16'); // true
* Carbon::parse('2018-07-25 12:45:16')->eq(Carbon::parse('2018-07-25 12:45:16')); // true
* Carbon::parse('2018-07-25 12:45:16')->eq('2018-07-25 12:45:17'); // false
* ```
*
* @see equalTo()
*/
public function eq(DateTimeInterface|string $date): bool
{
return $this->equalTo($date);
}
/**
* Determines if the instance is equal to another
*
* @example
* ```
* Carbon::parse('2018-07-25 12:45:16')->equalTo('2018-07-25 12:45:16'); // true
* Carbon::parse('2018-07-25 12:45:16')->equalTo(Carbon::parse('2018-07-25 12:45:16')); // true
* Carbon::parse('2018-07-25 12:45:16')->equalTo('2018-07-25 12:45:17'); // false
* ```
*/
public function equalTo(DateTimeInterface|string $date): bool
{
return $this == $this->resolveCarbon($date);
}
/**
* Determines if the instance is not equal to another
*
* @example
* ```
* Carbon::parse('2018-07-25 12:45:16')->ne('2018-07-25 12:45:16'); // false
* Carbon::parse('2018-07-25 12:45:16')->ne(Carbon::parse('2018-07-25 12:45:16')); // false
* Carbon::parse('2018-07-25 12:45:16')->ne('2018-07-25 12:45:17'); // true
* ```
*
* @see notEqualTo()
*/
public function ne(DateTimeInterface|string $date): bool
{
return $this->notEqualTo($date);
}
/**
* Determines if the instance is not equal to another
*
* @example
* ```
* Carbon::parse('2018-07-25 12:45:16')->notEqualTo('2018-07-25 12:45:16'); // false
* Carbon::parse('2018-07-25 12:45:16')->notEqualTo(Carbon::parse('2018-07-25 12:45:16')); // false
* Carbon::parse('2018-07-25 12:45:16')->notEqualTo('2018-07-25 12:45:17'); // true
* ```
*/
public function notEqualTo(DateTimeInterface|string $date): bool
{
return !$this->equalTo($date);
}
/**
* Determines if the instance is greater (after) than another
*
* @example
* ```
* Carbon::parse('2018-07-25 12:45:16')->gt('2018-07-25 12:45:15'); // true
* Carbon::parse('2018-07-25 12:45:16')->gt('2018-07-25 12:45:16'); // false
* Carbon::parse('2018-07-25 12:45:16')->gt('2018-07-25 12:45:17'); // false
* ```
*
* @see greaterThan()
*/
public function gt(DateTimeInterface|string $date): bool
{
return $this->greaterThan($date);
}
/**
* Determines if the instance is greater (after) than another
*
* @example
* ```
* Carbon::parse('2018-07-25 12:45:16')->greaterThan('2018-07-25 12:45:15'); // true
* Carbon::parse('2018-07-25 12:45:16')->greaterThan('2018-07-25 12:45:16'); // false
* Carbon::parse('2018-07-25 12:45:16')->greaterThan('2018-07-25 12:45:17'); // false
* ```
*/
public function greaterThan(DateTimeInterface|string $date): bool
{
return $this > $this->resolveCarbon($date);
}
/**
* Determines if the instance is greater (after) than another
*
* @example
* ```
* Carbon::parse('2018-07-25 12:45:16')->isAfter('2018-07-25 12:45:15'); // true
* Carbon::parse('2018-07-25 12:45:16')->isAfter('2018-07-25 12:45:16'); // false
* Carbon::parse('2018-07-25 12:45:16')->isAfter('2018-07-25 12:45:17'); // false
* ```
*
* @see greaterThan()
*/
public function isAfter(DateTimeInterface|string $date): bool
{
return $this->greaterThan($date);
}
/**
* Determines if the instance is greater (after) than or equal to another
*
* @example
* ```
* Carbon::parse('2018-07-25 12:45:16')->gte('2018-07-25 12:45:15'); // true
* Carbon::parse('2018-07-25 12:45:16')->gte('2018-07-25 12:45:16'); // true
* Carbon::parse('2018-07-25 12:45:16')->gte('2018-07-25 12:45:17'); // false
* ```
*
* @see greaterThanOrEqualTo()
*/
public function gte(DateTimeInterface|string $date): bool
{
return $this->greaterThanOrEqualTo($date);
}
/**
* Determines if the instance is greater (after) than or equal to another
*
* @example
* ```
* Carbon::parse('2018-07-25 12:45:16')->greaterThanOrEqualTo('2018-07-25 12:45:15'); // true
* Carbon::parse('2018-07-25 12:45:16')->greaterThanOrEqualTo('2018-07-25 12:45:16'); // true
* Carbon::parse('2018-07-25 12:45:16')->greaterThanOrEqualTo('2018-07-25 12:45:17'); // false
* ```
*/
public function greaterThanOrEqualTo(DateTimeInterface|string $date): bool
{
return $this >= $this->resolveCarbon($date);
}
/**
* Determines if the instance is less (before) than another
*
* @example
* ```
* Carbon::parse('2018-07-25 12:45:16')->lt('2018-07-25 12:45:15'); // false
* Carbon::parse('2018-07-25 12:45:16')->lt('2018-07-25 12:45:16'); // false
* Carbon::parse('2018-07-25 12:45:16')->lt('2018-07-25 12:45:17'); // true
* ```
*
* @see lessThan()
*/
public function lt(DateTimeInterface|string $date): bool
{
return $this->lessThan($date);
}
/**
* Determines if the instance is less (before) than another
*
* @example
* ```
* Carbon::parse('2018-07-25 12:45:16')->lessThan('2018-07-25 12:45:15'); // false
* Carbon::parse('2018-07-25 12:45:16')->lessThan('2018-07-25 12:45:16'); // false
* Carbon::parse('2018-07-25 12:45:16')->lessThan('2018-07-25 12:45:17'); // true
* ```
*/
public function lessThan(DateTimeInterface|string $date): bool
{
return $this < $this->resolveCarbon($date);
}
/**
* Determines if the instance is less (before) than another
*
* @example
* ```
* Carbon::parse('2018-07-25 12:45:16')->isBefore('2018-07-25 12:45:15'); // false
* Carbon::parse('2018-07-25 12:45:16')->isBefore('2018-07-25 12:45:16'); // false
* Carbon::parse('2018-07-25 12:45:16')->isBefore('2018-07-25 12:45:17'); // true
* ```
*
* @see lessThan()
*/
public function isBefore(DateTimeInterface|string $date): bool
{
return $this->lessThan($date);
}
/**
* Determines if the instance is less (before) or equal to another
*
* @example
* ```
* Carbon::parse('2018-07-25 12:45:16')->lte('2018-07-25 12:45:15'); // false
* Carbon::parse('2018-07-25 12:45:16')->lte('2018-07-25 12:45:16'); // true
* Carbon::parse('2018-07-25 12:45:16')->lte('2018-07-25 12:45:17'); // true
* ```
*
* @see lessThanOrEqualTo()
*/
public function lte(DateTimeInterface|string $date): bool
{
return $this->lessThanOrEqualTo($date);
}
/**
* Determines if the instance is less (before) or equal to another
*
* @example
* ```
* Carbon::parse('2018-07-25 12:45:16')->lessThanOrEqualTo('2018-07-25 12:45:15'); // false
* Carbon::parse('2018-07-25 12:45:16')->lessThanOrEqualTo('2018-07-25 12:45:16'); // true
* Carbon::parse('2018-07-25 12:45:16')->lessThanOrEqualTo('2018-07-25 12:45:17'); // true
* ```
*/
public function lessThanOrEqualTo(DateTimeInterface|string $date): bool
{
return $this <= $this->resolveCarbon($date);
}
/**
* Determines if the instance is between two others.
*
* The third argument allow you to specify if bounds are included or not (true by default)
* but for when you including/excluding bounds may produce different results in your application,
* we recommend to use the explicit methods ->betweenIncluded() or ->betweenExcluded() instead.
*
* @example
* ```
* Carbon::parse('2018-07-25')->between('2018-07-14', '2018-08-01'); // true
* Carbon::parse('2018-07-25')->between('2018-08-01', '2018-08-20'); // false
* Carbon::parse('2018-07-25')->between('2018-07-25', '2018-08-01'); // true
* Carbon::parse('2018-07-25')->between('2018-07-25', '2018-08-01', false); // false
* ```
*
* @param bool $equal Indicates if an equal to comparison should be done
*/
public function between(DateTimeInterface|string $date1, DateTimeInterface|string $date2, bool $equal = true): bool
{
$date1 = $this->resolveCarbon($date1);
$date2 = $this->resolveCarbon($date2);
if ($date1->greaterThan($date2)) {
[$date1, $date2] = [$date2, $date1];
}
if ($equal) {
return $this >= $date1 && $this <= $date2;
}
return $this > $date1 && $this < $date2;
}
/**
* Determines if the instance is between two others, bounds included.
*
* @example
* ```
* Carbon::parse('2018-07-25')->betweenIncluded('2018-07-14', '2018-08-01'); // true
* Carbon::parse('2018-07-25')->betweenIncluded('2018-08-01', '2018-08-20'); // false
* Carbon::parse('2018-07-25')->betweenIncluded('2018-07-25', '2018-08-01'); // true
* ```
*/
public function betweenIncluded(DateTimeInterface|string $date1, DateTimeInterface|string $date2): bool
{
return $this->between($date1, $date2, true);
}
/**
* Determines if the instance is between two others, bounds excluded.
*
* @example
* ```
* Carbon::parse('2018-07-25')->betweenExcluded('2018-07-14', '2018-08-01'); // true
* Carbon::parse('2018-07-25')->betweenExcluded('2018-08-01', '2018-08-20'); // false
* Carbon::parse('2018-07-25')->betweenExcluded('2018-07-25', '2018-08-01'); // false
* ```
*/
public function betweenExcluded(DateTimeInterface|string $date1, DateTimeInterface|string $date2): bool
{
return $this->between($date1, $date2, false);
}
/**
* Determines if the instance is between two others
*
* @example
* ```
* Carbon::parse('2018-07-25')->isBetween('2018-07-14', '2018-08-01'); // true
* Carbon::parse('2018-07-25')->isBetween('2018-08-01', '2018-08-20'); // false
* Carbon::parse('2018-07-25')->isBetween('2018-07-25', '2018-08-01'); // true
* Carbon::parse('2018-07-25')->isBetween('2018-07-25', '2018-08-01', false); // false
* ```
*
* @param bool $equal Indicates if an equal to comparison should be done
*/
public function isBetween(DateTimeInterface|string $date1, DateTimeInterface|string $date2, bool $equal = true): bool
{
return $this->between($date1, $date2, $equal);
}
/**
* Determines if the instance is a weekday.
*
* @example
* ```
* Carbon::parse('2019-07-14')->isWeekday(); // false
* Carbon::parse('2019-07-15')->isWeekday(); // true
* ```
*/
public function isWeekday(): bool
{
return !$this->isWeekend();
}
/**
* Determines if the instance is a weekend day.
*
* @example
* ```
* Carbon::parse('2019-07-14')->isWeekend(); // true
* Carbon::parse('2019-07-15')->isWeekend(); // false
* ```
*/
public function isWeekend(): bool
{
return \in_array(
$this->dayOfWeek,
$this->transmitFactory(static fn () => static::getWeekendDays()),
true,
);
}
/**
* Determines if the instance is yesterday.
*
* @example
* ```
* Carbon::yesterday()->isYesterday(); // true
* Carbon::tomorrow()->isYesterday(); // false
* ```
*/
public function isYesterday(): bool
{
return $this->toDateString() === $this->transmitFactory(
fn () => static::yesterday($this->getTimezone())->toDateString(),
);
}
/**
* Determines if the instance is today.
*
* @example
* ```
* Carbon::today()->isToday(); // true
* Carbon::tomorrow()->isToday(); // false
* ```
*/
public function isToday(): bool
{
return $this->toDateString() === $this->nowWithSameTz()->toDateString();
}
/**
* Determines if the instance is tomorrow.
*
* @example
* ```
* Carbon::tomorrow()->isTomorrow(); // true
* Carbon::yesterday()->isTomorrow(); // false
* ```
*/
public function isTomorrow(): bool
{
return $this->toDateString() === $this->transmitFactory(
fn () => static::tomorrow($this->getTimezone())->toDateString(),
);
}
/**
* Determines if the instance is in the future, ie. greater (after) than now.
*
* @example
* ```
* Carbon::now()->addHours(5)->isFuture(); // true
* Carbon::now()->subHours(5)->isFuture(); // false
* ```
*/
public function isFuture(): bool
{
return $this->greaterThan($this->nowWithSameTz());
}
/**
* Determines if the instance is in the past, ie. less (before) than now.
*
* @example
* ```
* Carbon::now()->subHours(5)->isPast(); // true
* Carbon::now()->addHours(5)->isPast(); // false
* ```
*/
public function isPast(): bool
{
return $this->lessThan($this->nowWithSameTz());
}
/**
* Determines if the instance is a leap year.
*
* @example
* ```
* Carbon::parse('2020-01-01')->isLeapYear(); // true
* Carbon::parse('2019-01-01')->isLeapYear(); // false
* ```
*/
public function isLeapYear(): bool
{
return $this->rawFormat('L') === '1';
}
/**
* Determines if the instance is a long year (using calendar year).
*
* ⚠️ This method completely ignores month and day to use the numeric year number,
* it's not correct if the exact date matters. For instance as `2019-12-30` is already
* in the first week of the 2020 year, if you want to know from this date if ISO week
* year 2020 is a long year, use `isLongIsoYear` instead.
*
* @example
* ```
* Carbon::create(2015)->isLongYear(); // true
* Carbon::create(2016)->isLongYear(); // false
* ```
*
* @see https://en.wikipedia.org/wiki/ISO_8601#Week_dates
*/
public function isLongYear(): bool
{
return static::create($this->year, 12, 28, 0, 0, 0, $this->tz)->weekOfYear === static::WEEKS_PER_YEAR + 1;
}
/**
* Determines if the instance is a long year (using ISO 8601 year).
*
* @example
* ```
* Carbon::parse('2015-01-01')->isLongIsoYear(); // true
* Carbon::parse('2016-01-01')->isLongIsoYear(); // true
* Carbon::parse('2016-01-03')->isLongIsoYear(); // false
* Carbon::parse('2019-12-29')->isLongIsoYear(); // false
* Carbon::parse('2019-12-30')->isLongIsoYear(); // true
* ```
*
* @see https://en.wikipedia.org/wiki/ISO_8601#Week_dates
*/
public function isLongIsoYear(): bool
{
return static::create($this->isoWeekYear, 12, 28, 0, 0, 0, $this->tz)->weekOfYear === 53;
}
/**
* Compares the formatted values of the two dates.
*
* @example
* ```
* Carbon::parse('2019-06-13')->isSameAs('Y-d', Carbon::parse('2019-12-13')); // true
* Carbon::parse('2019-06-13')->isSameAs('Y-d', Carbon::parse('2019-06-14')); // false
* ```
*
* @param string $format date formats to compare.
* @param DateTimeInterface|string $date instance to compare with or null to use current day.
*/
public function isSameAs(string $format, DateTimeInterface|string $date): bool
{
return $this->rawFormat($format) === $this->resolveCarbon($date)->rawFormat($format);
}
/**
* Determines if the instance is in the current unit given.
*
* @example
* ```
* Carbon::parse('2019-01-13')->isSameUnit('year', Carbon::parse('2019-12-25')); // true
* Carbon::parse('2018-12-13')->isSameUnit('year', Carbon::parse('2019-12-25')); // false
* ```
*
* @param string $unit singular unit string
* @param DateTimeInterface|string $date instance to compare with or null to use current day.
*
* @throws BadComparisonUnitException
*
* @return bool
*/
public function isSameUnit(string $unit, DateTimeInterface|string $date): bool
{
if ($unit === /* @call isSameUnit */ 'quarter') {
$other = $this->resolveCarbon($date);
return $other->year === $this->year && $other->quarter === $this->quarter;
}
$units = [
// @call isSameUnit
'year' => 'Y',
// @call isSameUnit
'month' => 'Y-n',
// @call isSameUnit
'week' => 'o-W',
// @call isSameUnit
'day' => 'Y-m-d',
// @call isSameUnit
'hour' => 'Y-m-d H',
// @call isSameUnit
'minute' => 'Y-m-d H:i',
// @call isSameUnit
'second' => 'Y-m-d H:i:s',
// @call isSameUnit
'milli' => 'Y-m-d H:i:s.v',
// @call isSameUnit
'millisecond' => 'Y-m-d H:i:s.v',
// @call isSameUnit
'micro' => 'Y-m-d H:i:s.u',
// @call isSameUnit
'microsecond' => 'Y-m-d H:i:s.u',
];
if (isset($units[$unit])) {
return $this->isSameAs($units[$unit], $date);
}
if (isset($this->$unit)) {
return $this->resolveCarbon($date)->$unit === $this->$unit;
}
if ($this->isLocalStrictModeEnabled()) {
throw new BadComparisonUnitException($unit);
}
return false;
}
/**
* Determines if the instance is in the current unit given.
*
* @example
* ```
* Carbon::now()->isCurrentUnit('hour'); // true
* Carbon::now()->subHours(2)->isCurrentUnit('hour'); // false
* ```
*
* @param string $unit The unit to test.
*
* @throws BadMethodCallException
*/
public function isCurrentUnit(string $unit): bool
{
return $this->{'isSame'.ucfirst($unit)}('now');
}
/**
* Checks if the passed in date is in the same quarter as the instance quarter (and year if needed).
*
* @example
* ```
* Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2019-03-01')); // true
* Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2019-04-01')); // false
* Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2018-03-01')); // false
* Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2018-03-01'), false); // true
* ```
*
* @param DateTimeInterface|string $date The instance to compare with or null to use current day.
* @param bool $ofSameYear Check if it is the same month in the same year.
*
* @return bool
*/
public function isSameQuarter(DateTimeInterface|string $date, bool $ofSameYear = true): bool
{
$date = $this->resolveCarbon($date);
return $this->quarter === $date->quarter && (!$ofSameYear || $this->isSameYear($date));
}
/**
* Checks if the passed in date is in the same month as the instance´s month.
*
* @example
* ```
* Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2019-01-01')); // true
* Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2019-02-01')); // false
* Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2018-01-01')); // false
* Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2018-01-01'), false); // true
* ```
*
* @param DateTimeInterface|string $date The instance to compare with or null to use the current date.
* @param bool $ofSameYear Check if it is the same month in the same year.
*
* @return bool
*/
public function isSameMonth(DateTimeInterface|string $date, bool $ofSameYear = true): bool
{
return $this->isSameAs($ofSameYear ? 'Y-m' : 'm', $date);
}
/**
* Checks if this day is a specific day of the week.
*
* @example
* ```
* Carbon::parse('2019-07-17')->isDayOfWeek(Carbon::WEDNESDAY); // true
* Carbon::parse('2019-07-17')->isDayOfWeek(Carbon::FRIDAY); // false
* Carbon::parse('2019-07-17')->isDayOfWeek('Wednesday'); // true
* Carbon::parse('2019-07-17')->isDayOfWeek('Friday'); // false
* ```
*
* @param int|string $dayOfWeek
*
* @return bool
*/
public function isDayOfWeek($dayOfWeek): bool
{
if (\is_string($dayOfWeek) && \defined($constant = static::class.'::'.strtoupper($dayOfWeek))) {
$dayOfWeek = \constant($constant);
}
return $this->dayOfWeek === $dayOfWeek;
}
/**
* Check if its the birthday. Compares the date/month values of the two dates.
*
* @example
* ```
* Carbon::now()->subYears(5)->isBirthday(); // true
* Carbon::now()->subYears(5)->subDay()->isBirthday(); // false
* Carbon::parse('2019-06-05')->isBirthday(Carbon::parse('2001-06-05')); // true
* Carbon::parse('2019-06-05')->isBirthday(Carbon::parse('2001-06-06')); // false
* ```
*
* @param DateTimeInterface|string|null $date The instance to compare with or null to use current day.
*
* @return bool
*/
public function isBirthday(DateTimeInterface|string|null $date = null): bool
{
return $this->isSameAs('md', $date ?? 'now');
}
/**
* Check if today is the last day of the Month
*
* @example
* ```
* Carbon::parse('2019-02-28')->isLastOfMonth(); // true
* Carbon::parse('2019-03-28')->isLastOfMonth(); // false
* Carbon::parse('2019-03-30')->isLastOfMonth(); // false
* Carbon::parse('2019-03-31')->isLastOfMonth(); // true
* Carbon::parse('2019-04-30')->isLastOfMonth(); // true
* ```
*/
public function isLastOfMonth(): bool
{
return $this->day === $this->daysInMonth;
}
/**
* Check if the instance is start of day / midnight.
*
* @example
* ```
* Carbon::parse('2019-02-28 00:00:00')->isStartOfDay(); // true
* Carbon::parse('2019-02-28 00:00:00.999999')->isStartOfDay(); // true
* Carbon::parse('2019-02-28 00:00:01')->isStartOfDay(); // false
* Carbon::parse('2019-02-28 00:00:00.000000')->isStartOfDay(true); // true
* Carbon::parse('2019-02-28 00:00:00.000012')->isStartOfDay(true); // false
* ```
*
* @param bool $checkMicroseconds check time at microseconds precision
*/
public function isStartOfDay(bool $checkMicroseconds = false): bool
{
/* @var CarbonInterface $this */
return $checkMicroseconds
? $this->rawFormat('H:i:s.u') === '00:00:00.000000'
: $this->rawFormat('H:i:s') === '00:00:00';
}
/**
* Check if the instance is end of day.
*
* @example
* ```
* Carbon::parse('2019-02-28 23:59:59.999999')->isEndOfDay(); // true
* Carbon::parse('2019-02-28 23:59:59.123456')->isEndOfDay(); // true
* Carbon::parse('2019-02-28 23:59:59')->isEndOfDay(); // true
* Carbon::parse('2019-02-28 23:59:58.999999')->isEndOfDay(); // false
* Carbon::parse('2019-02-28 23:59:59.999999')->isEndOfDay(true); // true
* Carbon::parse('2019-02-28 23:59:59.123456')->isEndOfDay(true); // false
* Carbon::parse('2019-02-28 23:59:59')->isEndOfDay(true); // false
* ```
*
* @param bool $checkMicroseconds check time at microseconds precision
*/
public function isEndOfDay(bool $checkMicroseconds = false): bool
{
/* @var CarbonInterface $this */
return $checkMicroseconds
? $this->rawFormat('H:i:s.u') === '23:59:59.999999'
: $this->rawFormat('H:i:s') === '23:59:59';
}
/**
* Check if the instance is start of day / midnight.
*
* @example
* ```
* Carbon::parse('2019-02-28 00:00:00')->isMidnight(); // true
* Carbon::parse('2019-02-28 00:00:00.999999')->isMidnight(); // true
* Carbon::parse('2019-02-28 00:00:01')->isMidnight(); // false
* ```
*/
public function isMidnight(): bool
{
return $this->isStartOfDay();
}
/**
* Check if the instance is midday.
*
* @example
* ```
* Carbon::parse('2019-02-28 11:59:59.999999')->isMidday(); // false
* Carbon::parse('2019-02-28 12:00:00')->isMidday(); // true
* Carbon::parse('2019-02-28 12:00:00.999999')->isMidday(); // true
* Carbon::parse('2019-02-28 12:00:01')->isMidday(); // false
* ```
*/
public function isMidday(): bool
{
/* @var CarbonInterface $this */
return $this->rawFormat('G:i:s') === static::$midDayAt.':00:00';
}
/**
* Checks if the (date)time string is in a given format.
*
* @example
* ```
* Carbon::hasFormat('11:12:45', 'h:i:s'); // true
* Carbon::hasFormat('13:12:45', 'h:i:s'); // false
* ```
*/
public static function hasFormat(string $date, string $format): bool
{
return FactoryImmutable::getInstance()->hasFormat($date, $format);
}
/**
* Checks if the (date)time string is in a given format.
*
* @example
* ```
* Carbon::hasFormatWithModifiers('31/08/2015', 'd#m#Y'); // true
* Carbon::hasFormatWithModifiers('31/08/2015', 'm#d#Y'); // false
* ```
*
* @param string $date
* @param string $format
*
* @return bool
*/
public static function hasFormatWithModifiers(?string $date, string $format): bool
{
return FactoryImmutable::getInstance()->hasFormatWithModifiers($date, $format);
}
/**
* Checks if the (date)time string is in a given format and valid to create a
* new instance.
*
* @example
* ```
* Carbon::canBeCreatedFromFormat('11:12:45', 'h:i:s'); // true
* Carbon::canBeCreatedFromFormat('13:12:45', 'h:i:s'); // false
* ```
*/
public static function canBeCreatedFromFormat(?string $date, string $format): bool
{
if ($date === null) {
return false;
}
try {
// Try to create a DateTime object. Throws an InvalidArgumentException if the provided time string
// doesn't match the format in any way.
if (!static::rawCreateFromFormat($format, $date)) {
return false;
}
} catch (InvalidArgumentException) {
return false;
}
return static::hasFormatWithModifiers($date, $format);
}
/**
* Returns true if the current date matches the given string.
*
* @example
* ```
* var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2019')); // true
* var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2018')); // false
* var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2019-06')); // true
* var_dump(Carbon::parse('2019-06-02 12:23:45')->is('06-02')); // true
* var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2019-06-02')); // true
* var_dump(Carbon::parse('2019-06-02 12:23:45')->is('Sunday')); // true
* var_dump(Carbon::parse('2019-06-02 12:23:45')->is('June')); // true
* var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12:23')); // true
* var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12:23:45')); // true
* var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12:23:00')); // false
* var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12h')); // true
* var_dump(Carbon::parse('2019-06-02 15:23:45')->is('3pm')); // true
* var_dump(Carbon::parse('2019-06-02 15:23:45')->is('3am')); // false
* ```
*
* @param string $tester day name, month name, hour, date, etc. as string
*/
public function is(string $tester): bool
{
$tester = trim($tester);
if (preg_match('/^\d+$/', $tester)) {
return $this->year === (int) $tester;
}
if (preg_match('/^(?:Jan|January|Feb|February|Mar|March|Apr|April|May|Jun|June|Jul|July|Aug|August|Sep|September|Oct|October|Nov|November|Dec|December)$/i', $tester)) {
return $this->isSameMonth(
$this->transmitFactory(static fn () => static::parse($tester)),
false,
);
}
if (preg_match('/^\d{3,}-\d{1,2}$/', $tester)) {
return $this->isSameMonth(
$this->transmitFactory(static fn () => static::parse($tester)),
);
}
if (preg_match('/^\d{1,2}-\d{1,2}$/', $tester)) {
return $this->isSameDay(
$this->transmitFactory(fn () => static::parse($this->year.'-'.$tester)),
);
}
$modifier = preg_replace('/(\d)h$/i', '$1:00', $tester);
/* @var CarbonInterface $max */
$median = $this->transmitFactory(static fn () => static::parse('5555-06-15 12:30:30.555555'))
->modify($modifier);
$current = $this->avoidMutation();
/* @var CarbonInterface $other */
$other = $this->avoidMutation()->modify($modifier);
if ($current->eq($other)) {
return true;
}
if (preg_match('/\d:\d{1,2}:\d{1,2}$/', $tester)) {
return $current->startOfSecond()->eq($other);
}
if (preg_match('/\d:\d{1,2}$/', $tester)) {
return $current->startOfMinute()->eq($other);
}
if (preg_match('/\d(?:h|am|pm)$/', $tester)) {
return $current->startOfHour()->eq($other);
}
if (preg_match(
'/^(?:january|february|march|april|may|june|july|august|september|october|november|december)(?:\s+\d+)?$/i',
$tester,
)) {
return $current->startOfMonth()->eq($other->startOfMonth());
}
$units = [
'month' => [1, 'year'],
'day' => [1, 'month'],
'hour' => [0, 'day'],
'minute' => [0, 'hour'],
'second' => [0, 'minute'],
'microsecond' => [0, 'second'],
];
foreach ($units as $unit => [$minimum, $startUnit]) {
if ($minimum === $median->$unit) {
$current = $current->startOf($startUnit);
break;
}
}
return $current->eq($other);
}
/**
* Returns true if the date was created using CarbonImmutable::startOfTime()
*
* @return bool
*/
public function isStartOfTime(): bool
{
return $this->startOfTime ?? false;
}
/**
* Returns true if the date was created using CarbonImmutable::endOfTime()
*
* @return bool
*/
public function isEndOfTime(): bool
{
return $this->endOfTime ?? false;
}
}

View File

@@ -0,0 +1,554 @@
<?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Carbon\Traits;
use Carbon\Carbon;
use Carbon\CarbonImmutable;
use Carbon\CarbonInterface;
use Carbon\CarbonInterval;
use Carbon\CarbonPeriod;
use Carbon\CarbonPeriodImmutable;
use Carbon\Exceptions\UnitException;
use Closure;
use DateTime;
use DateTimeImmutable;
use DateTimeInterface;
/**
* Trait Converter.
*
* Change date into different string formats and types and
* handle the string cast.
*
* Depends on the following methods:
*
* @method static copy()
*/
trait Converter
{
use ToStringFormat;
/**
* Returns the formatted date string on success or FALSE on failure.
*
* @see https://php.net/manual/en/datetime.format.php
*/
public function format(string $format): string
{
$function = $this->localFormatFunction
?? $this->getFactory()->getSettings()['formatFunction']
?? static::$formatFunction;
if (!$function) {
return $this->rawFormat($format);
}
if (\is_string($function) && method_exists($this, $function)) {
$function = [$this, $function];
}
return $function(...\func_get_args());
}
/**
* @see https://php.net/manual/en/datetime.format.php
*/
public function rawFormat(string $format): string
{
return parent::format($format);
}
/**
* Format the instance as a string using the set format
*
* @example
* ```
* echo Carbon::now(); // Carbon instances can be cast to string
* ```
*/
public function __toString(): string
{
$format = $this->localToStringFormat
?? $this->getFactory()->getSettings()['toStringFormat']
?? null;
return $format instanceof Closure
? $format($this)
: $this->rawFormat($format ?: (
\defined('static::DEFAULT_TO_STRING_FORMAT')
? static::DEFAULT_TO_STRING_FORMAT
: CarbonInterface::DEFAULT_TO_STRING_FORMAT
));
}
/**
* Format the instance as date
*
* @example
* ```
* echo Carbon::now()->toDateString();
* ```
*/
public function toDateString(): string
{
return $this->rawFormat('Y-m-d');
}
/**
* Format the instance as a readable date
*
* @example
* ```
* echo Carbon::now()->toFormattedDateString();
* ```
*/
public function toFormattedDateString(): string
{
return $this->rawFormat('M j, Y');
}
/**
* Format the instance with the day, and a readable date
*
* @example
* ```
* echo Carbon::now()->toFormattedDayDateString();
* ```
*/
public function toFormattedDayDateString(): string
{
return $this->rawFormat('D, M j, Y');
}
/**
* Format the instance as time
*
* @example
* ```
* echo Carbon::now()->toTimeString();
* ```
*/
public function toTimeString(string $unitPrecision = 'second'): string
{
return $this->rawFormat(static::getTimeFormatByPrecision($unitPrecision));
}
/**
* Format the instance as date and time
*
* @example
* ```
* echo Carbon::now()->toDateTimeString();
* ```
*/
public function toDateTimeString(string $unitPrecision = 'second'): string
{
return $this->rawFormat('Y-m-d '.static::getTimeFormatByPrecision($unitPrecision));
}
/**
* Return a format from H:i to H:i:s.u according to given unit precision.
*
* @param string $unitPrecision "minute", "second", "millisecond" or "microsecond"
*/
public static function getTimeFormatByPrecision(string $unitPrecision): string
{
return match (static::singularUnit($unitPrecision)) {
'minute' => 'H:i',
'second' => 'H:i:s',
'm', 'millisecond' => 'H:i:s.v',
'µ', 'microsecond' => 'H:i:s.u',
default => throw new UnitException('Precision unit expected among: minute, second, millisecond and microsecond.'),
};
}
/**
* Format the instance as date and time T-separated with no timezone
*
* @example
* ```
* echo Carbon::now()->toDateTimeLocalString();
* echo "\n";
* echo Carbon::now()->toDateTimeLocalString('minute'); // You can specify precision among: minute, second, millisecond and microsecond
* ```
*/
public function toDateTimeLocalString(string $unitPrecision = 'second'): string
{
return $this->rawFormat('Y-m-d\T'.static::getTimeFormatByPrecision($unitPrecision));
}
/**
* Format the instance with day, date and time
*
* @example
* ```
* echo Carbon::now()->toDayDateTimeString();
* ```
*/
public function toDayDateTimeString(): string
{
return $this->rawFormat('D, M j, Y g:i A');
}
/**
* Format the instance as ATOM
*
* @example
* ```
* echo Carbon::now()->toAtomString();
* ```
*/
public function toAtomString(): string
{
return $this->rawFormat(DateTime::ATOM);
}
/**
* Format the instance as COOKIE
*
* @example
* ```
* echo Carbon::now()->toCookieString();
* ```
*/
public function toCookieString(): string
{
return $this->rawFormat(DateTimeInterface::COOKIE);
}
/**
* Format the instance as ISO8601
*
* @example
* ```
* echo Carbon::now()->toIso8601String();
* ```
*/
public function toIso8601String(): string
{
return $this->toAtomString();
}
/**
* Format the instance as RFC822
*
* @example
* ```
* echo Carbon::now()->toRfc822String();
* ```
*/
public function toRfc822String(): string
{
return $this->rawFormat(DateTimeInterface::RFC822);
}
/**
* Convert the instance to UTC and return as Zulu ISO8601
*
* @example
* ```
* echo Carbon::now()->toIso8601ZuluString();
* ```
*/
public function toIso8601ZuluString(string $unitPrecision = 'second'): string
{
return $this->avoidMutation()
->utc()
->rawFormat('Y-m-d\T'.static::getTimeFormatByPrecision($unitPrecision).'\Z');
}
/**
* Format the instance as RFC850
*
* @example
* ```
* echo Carbon::now()->toRfc850String();
* ```
*/
public function toRfc850String(): string
{
return $this->rawFormat(DateTimeInterface::RFC850);
}
/**
* Format the instance as RFC1036
*
* @example
* ```
* echo Carbon::now()->toRfc1036String();
* ```
*/
public function toRfc1036String(): string
{
return $this->rawFormat(DateTimeInterface::RFC1036);
}
/**
* Format the instance as RFC1123
*
* @example
* ```
* echo Carbon::now()->toRfc1123String();
* ```
*/
public function toRfc1123String(): string
{
return $this->rawFormat(DateTimeInterface::RFC1123);
}
/**
* Format the instance as RFC2822
*
* @example
* ```
* echo Carbon::now()->toRfc2822String();
* ```
*/
public function toRfc2822String(): string
{
return $this->rawFormat(DateTimeInterface::RFC2822);
}
/**
* Format the instance as RFC3339.
*
* @example
* ```
* echo Carbon::now()->toRfc3339String() . "\n";
* echo Carbon::now()->toRfc3339String(true) . "\n";
* ```
*/
public function toRfc3339String(bool $extended = false): string
{
return $this->rawFormat($extended ? DateTimeInterface::RFC3339_EXTENDED : DateTimeInterface::RFC3339);
}
/**
* Format the instance as RSS
*
* @example
* ```
* echo Carbon::now()->toRssString();
* ```
*/
public function toRssString(): string
{
return $this->rawFormat(DateTimeInterface::RSS);
}
/**
* Format the instance as W3C
*
* @example
* ```
* echo Carbon::now()->toW3cString();
* ```
*/
public function toW3cString(): string
{
return $this->rawFormat(DateTimeInterface::W3C);
}
/**
* Format the instance as RFC7231
*
* @example
* ```
* echo Carbon::now()->toRfc7231String();
* ```
*/
public function toRfc7231String(): string
{
return $this->avoidMutation()
->setTimezone('GMT')
->rawFormat(\defined('static::RFC7231_FORMAT') ? static::RFC7231_FORMAT : CarbonInterface::RFC7231_FORMAT);
}
/**
* Get default array representation.
*
* @example
* ```
* var_dump(Carbon::now()->toArray());
* ```
*/
public function toArray(): array
{
return [
'year' => $this->year,
'month' => $this->month,
'day' => $this->day,
'dayOfWeek' => $this->dayOfWeek,
'dayOfYear' => $this->dayOfYear,
'hour' => $this->hour,
'minute' => $this->minute,
'second' => $this->second,
'micro' => $this->micro,
'timestamp' => $this->timestamp,
'formatted' => $this->rawFormat(\defined('static::DEFAULT_TO_STRING_FORMAT') ? static::DEFAULT_TO_STRING_FORMAT : CarbonInterface::DEFAULT_TO_STRING_FORMAT),
'timezone' => $this->timezone,
];
}
/**
* Get default object representation.
*
* @example
* ```
* var_dump(Carbon::now()->toObject());
* ```
*/
public function toObject(): object
{
return (object) $this->toArray();
}
/**
* Returns english human-readable complete date string.
*
* @example
* ```
* echo Carbon::now()->toString();
* ```
*/
public function toString(): string
{
return $this->avoidMutation()->locale('en')->isoFormat('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
}
/**
* Return the ISO-8601 string (ex: 1977-04-22T06:00:00Z, if $keepOffset truthy, offset will be kept:
* 1977-04-22T01:00:00-05:00).
*
* @example
* ```
* echo Carbon::now('America/Toronto')->toISOString() . "\n";
* echo Carbon::now('America/Toronto')->toISOString(true) . "\n";
* ```
*
* @param bool $keepOffset Pass true to keep the date offset. Else forced to UTC.
*/
public function toISOString(bool $keepOffset = false): ?string
{
if (!$this->isValid()) {
return null;
}
$yearFormat = $this->year < 0 || $this->year > 9999 ? 'YYYYYY' : 'YYYY';
$timezoneFormat = $keepOffset ? 'Z' : '[Z]';
$date = $keepOffset ? $this : $this->avoidMutation()->utc();
return $date->isoFormat("$yearFormat-MM-DD[T]HH:mm:ss.SSSSSS$timezoneFormat");
}
/**
* Return the ISO-8601 string (ex: 1977-04-22T06:00:00Z) with UTC timezone.
*
* @example
* ```
* echo Carbon::now('America/Toronto')->toJSON();
* ```
*/
public function toJSON(): ?string
{
return $this->toISOString();
}
/**
* Return native DateTime PHP object matching the current instance.
*
* @example
* ```
* var_dump(Carbon::now()->toDateTime());
* ```
*/
public function toDateTime(): DateTime
{
return new DateTime($this->rawFormat('Y-m-d H:i:s.u'), $this->getTimezone());
}
/**
* Return native toDateTimeImmutable PHP object matching the current instance.
*
* @example
* ```
* var_dump(Carbon::now()->toDateTimeImmutable());
* ```
*/
public function toDateTimeImmutable(): DateTimeImmutable
{
return new DateTimeImmutable($this->rawFormat('Y-m-d H:i:s.u'), $this->getTimezone());
}
/**
* @alias toDateTime
*
* Return native DateTime PHP object matching the current instance.
*
* @example
* ```
* var_dump(Carbon::now()->toDate());
* ```
*/
public function toDate(): DateTime
{
return $this->toDateTime();
}
/**
* Create a iterable CarbonPeriod object from current date to a given end date (and optional interval).
*
* @param \DateTimeInterface|Carbon|CarbonImmutable|int|null $end period end date or recurrences count if int
* @param int|\DateInterval|string|null $interval period default interval or number of the given $unit
* @param string|null $unit if specified, $interval must be an integer
*/
public function toPeriod($end = null, $interval = null, $unit = null): CarbonPeriod
{
if ($unit) {
$interval = CarbonInterval::make("$interval ".static::pluralUnit($unit));
}
$isDefaultInterval = !$interval;
$interval ??= CarbonInterval::day();
$class = $this->isMutable() ? CarbonPeriod::class : CarbonPeriodImmutable::class;
if (\is_int($end) || (\is_string($end) && ctype_digit($end))) {
$end = (int) $end;
}
$end ??= 1;
if (!\is_int($end)) {
$end = $this->resolveCarbon($end);
}
return new $class(
raw: [$this, CarbonInterval::make($interval), $end],
dateClass: static::class,
isDefaultInterval: $isDefaultInterval,
);
}
/**
* Create a iterable CarbonPeriod object from current date to a given end date (and optional interval).
*
* @param \DateTimeInterface|Carbon|CarbonImmutable|null $end period end date
* @param int|\DateInterval|string|null $interval period default interval or number of the given $unit
* @param string|null $unit if specified, $interval must be an integer
*/
public function range($end = null, $interval = null, $unit = null): CarbonPeriod
{
return $this->toPeriod($end, $interval, $unit);
}
}

View File

@@ -0,0 +1,937 @@
<?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Carbon\Traits;
use Carbon\Carbon;
use Carbon\CarbonImmutable;
use Carbon\CarbonInterface;
use Carbon\Exceptions\InvalidDateException;
use Carbon\Exceptions\InvalidFormatException;
use Carbon\Exceptions\InvalidTimeZoneException;
use Carbon\Exceptions\OutOfRangeException;
use Carbon\Exceptions\UnitException;
use Carbon\Month;
use Carbon\Translator;
use Carbon\WeekDay;
use Closure;
use DateMalformedStringException;
use DateTimeImmutable;
use DateTimeInterface;
use DateTimeZone;
use Exception;
use ReturnTypeWillChange;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* Trait Creator.
*
* Static creators.
*
* Depends on the following methods:
*
* @method static Carbon|CarbonImmutable getTestNow()
*/
trait Creator
{
use ObjectInitialisation;
use LocalFactory;
/**
* The errors that can occur.
*/
protected static ?array $lastErrors = null;
/**
* Create a new Carbon instance.
*
* Please see the testing aids section (specifically static::setTestNow())
* for more on the possibility of this constructor returning a test instance.
*
* @throws InvalidFormatException
*/
public function __construct(
DateTimeInterface|WeekDay|Month|string|int|float|null $time = null,
DateTimeZone|string|int|null $timezone = null,
) {
$this->initLocalFactory();
if ($time instanceof Month) {
$time = $time->name.' 1';
} elseif ($time instanceof WeekDay) {
$time = $time->name;
} elseif ($time instanceof DateTimeInterface) {
$time = $this->constructTimezoneFromDateTime($time, $timezone)->format('Y-m-d H:i:s.u');
}
if (\is_string($time) && str_starts_with($time, '@')) {
$time = static::createFromTimestampUTC(substr($time, 1))->format('Y-m-d\TH:i:s.uP');
} elseif (is_numeric($time) && (!\is_string($time) || !preg_match('/^\d{1,14}$/', $time))) {
$time = static::createFromTimestampUTC($time)->format('Y-m-d\TH:i:s.uP');
}
// If the class has a test now set, and we are trying to create a now()
// instance then override as required
$isNow = \in_array($time, [null, '', 'now'], true);
$timezone = static::safeCreateDateTimeZone($timezone) ?? null;
if (
($this->clock || (
method_exists(static::class, 'hasTestNow') &&
method_exists(static::class, 'getTestNow') &&
static::hasTestNow()
)) &&
($isNow || static::hasRelativeKeywords($time))
) {
$this->mockConstructorParameters($time, $timezone);
}
try {
parent::__construct($time ?? 'now', $timezone);
} catch (Exception $exception) {
throw new InvalidFormatException($exception->getMessage(), 0, $exception);
}
$this->constructedObjectId = spl_object_hash($this);
self::setLastErrors(parent::getLastErrors());
}
/**
* Get timezone from a datetime instance.
*/
private function constructTimezoneFromDateTime(
DateTimeInterface $date,
DateTimeZone|string|int|null &$timezone,
): DateTimeInterface {
if ($timezone !== null) {
$safeTz = static::safeCreateDateTimeZone($timezone);
if ($safeTz) {
$date = ($date instanceof DateTimeImmutable ? $date : clone $date)->setTimezone($safeTz);
}
return $date;
}
$timezone = $date->getTimezone();
return $date;
}
/**
* Update constructedObjectId on cloned.
*/
public function __clone(): void
{
$this->constructedObjectId = spl_object_hash($this);
}
/**
* Create a Carbon instance from a DateTime one.
*/
public static function instance(DateTimeInterface $date): static
{
if ($date instanceof static) {
return clone $date;
}
$instance = new static($date->format('Y-m-d H:i:s.u'), $date->getTimezone());
if ($date instanceof CarbonInterface) {
$settings = $date->getSettings();
if (!$date->hasLocalTranslator()) {
unset($settings['locale']);
}
$instance->settings($settings);
}
return $instance;
}
/**
* Create a carbon instance from a string.
*
* This is an alias for the constructor that allows better fluent syntax
* as it allows you to do Carbon::parse('Monday next week')->fn() rather
* than (new Carbon('Monday next week'))->fn().
*
* @throws InvalidFormatException
*/
public static function rawParse(
DateTimeInterface|WeekDay|Month|string|int|float|null $time,
DateTimeZone|string|int|null $timezone = null,
): static {
if ($time instanceof DateTimeInterface) {
return static::instance($time);
}
try {
return new static($time, $timezone);
} catch (Exception $exception) {
// @codeCoverageIgnoreStart
try {
$date = @static::now($timezone)->change($time);
} catch (DateMalformedStringException|InvalidFormatException) {
$date = null;
}
// @codeCoverageIgnoreEnd
return $date
?? throw new InvalidFormatException("Could not parse '$time': ".$exception->getMessage(), 0, $exception);
}
}
/**
* Create a carbon instance from a string.
*
* This is an alias for the constructor that allows better fluent syntax
* as it allows you to do Carbon::parse('Monday next week')->fn() rather
* than (new Carbon('Monday next week'))->fn().
*
* @throws InvalidFormatException
*/
public static function parse(
DateTimeInterface|WeekDay|Month|string|int|float|null $time,
DateTimeZone|string|int|null $timezone = null,
): static {
$function = static::$parseFunction;
if (!$function) {
return static::rawParse($time, $timezone);
}
if (\is_string($function) && method_exists(static::class, $function)) {
$function = [static::class, $function];
}
return $function(...\func_get_args());
}
/**
* Create a carbon instance from a localized string (in French, Japanese, Arabic, etc.).
*
* @param string $time date/time string in the given language (may also contain English).
* @param string|null $locale if locale is null or not specified, current global locale will be
* used instead.
* @param DateTimeZone|string|int|null $timezone optional timezone for the new instance.
*
* @throws InvalidFormatException
*/
public static function parseFromLocale(
string $time,
?string $locale = null,
DateTimeZone|string|int|null $timezone = null,
): static {
return static::rawParse(static::translateTimeString($time, $locale, static::DEFAULT_LOCALE), $timezone);
}
/**
* Get a Carbon instance for the current date and time.
*/
public static function now(DateTimeZone|string|int|null $timezone = null): static
{
return new static(null, $timezone);
}
/**
* Create a Carbon instance for today.
*/
public static function today(DateTimeZone|string|int|null $timezone = null): static
{
return static::rawParse('today', $timezone);
}
/**
* Create a Carbon instance for tomorrow.
*/
public static function tomorrow(DateTimeZone|string|int|null $timezone = null): static
{
return static::rawParse('tomorrow', $timezone);
}
/**
* Create a Carbon instance for yesterday.
*/
public static function yesterday(DateTimeZone|string|int|null $timezone = null): static
{
return static::rawParse('yesterday', $timezone);
}
private static function assertBetween($unit, $value, $min, $max): void
{
if (static::isStrictModeEnabled() && ($value < $min || $value > $max)) {
throw new OutOfRangeException($unit, $min, $max, $value);
}
}
private static function createNowInstance($timezone)
{
if (!static::hasTestNow()) {
return static::now($timezone);
}
$now = static::getTestNow();
if ($now instanceof Closure) {
return $now(static::now($timezone));
}
$now = $now->avoidMutation();
return $timezone === null ? $now : $now->setTimezone($timezone);
}
/**
* Create a new Carbon instance from a specific date and time.
*
* If any of $year, $month or $day are set to null their now() values will
* be used.
*
* If $hour is null it will be set to its now() value and the default
* values for $minute and $second will be their now() values.
*
* If $hour is not null then the default values for $minute and $second
* will be 0.
*
* @param DateTimeInterface|string|int|null $year
* @param int|null $month
* @param int|null $day
* @param int|null $hour
* @param int|null $minute
* @param int|null $second
* @param DateTimeZone|string|int|null $timezone
*
* @throws InvalidFormatException
*
* @return static|null
*/
public static function create($year = 0, $month = 1, $day = 1, $hour = 0, $minute = 0, $second = 0, $timezone = null): ?self
{
$month = self::monthToInt($month);
if ((\is_string($year) && !is_numeric($year)) || $year instanceof DateTimeInterface) {
return static::parse($year, $timezone ?? (\is_string($month) || $month instanceof DateTimeZone ? $month : null));
}
$defaults = null;
$getDefault = function ($unit) use ($timezone, &$defaults) {
if ($defaults === null) {
$now = self::createNowInstance($timezone);
$defaults = array_combine([
'year',
'month',
'day',
'hour',
'minute',
'second',
], explode('-', $now->rawFormat('Y-n-j-G-i-s.u')));
}
return $defaults[$unit];
};
$year = $year ?? $getDefault('year');
$month = $month ?? $getDefault('month');
$day = $day ?? $getDefault('day');
$hour = $hour ?? $getDefault('hour');
$minute = $minute ?? $getDefault('minute');
$second = (float) ($second ?? $getDefault('second'));
self::assertBetween('month', $month, 0, 99);
self::assertBetween('day', $day, 0, 99);
self::assertBetween('hour', $hour, 0, 99);
self::assertBetween('minute', $minute, 0, 99);
self::assertBetween('second', $second, 0, 99);
$fixYear = null;
if ($year < 0) {
$fixYear = $year;
$year = 0;
} elseif ($year > 9999) {
$fixYear = $year - 9999;
$year = 9999;
}
$second = ($second < 10 ? '0' : '').number_format($second, 6);
$instance = static::rawCreateFromFormat('!Y-n-j G:i:s.u', sprintf('%s-%s-%s %s:%02s:%02s', $year, $month, $day, $hour, $minute, $second), $timezone);
if ($instance && $fixYear !== null) {
$instance = $instance->addYears($fixYear);
}
return $instance ?? null;
}
/**
* Create a new safe Carbon instance from a specific date and time.
*
* If any of $year, $month or $day are set to null their now() values will
* be used.
*
* If $hour is null it will be set to its now() value and the default
* values for $minute and $second will be their now() values.
*
* If $hour is not null then the default values for $minute and $second
* will be 0.
*
* If one of the set values is not valid, an InvalidDateException
* will be thrown.
*
* @param int|null $year
* @param int|null $month
* @param int|null $day
* @param int|null $hour
* @param int|null $minute
* @param int|null $second
* @param DateTimeZone|string|int|null $timezone
*
* @throws InvalidDateException
*
* @return static|null
*/
public static function createSafe($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $timezone = null): ?self
{
$month = self::monthToInt($month);
$fields = static::getRangesByUnit();
foreach ($fields as $field => $range) {
if ($$field !== null && (!\is_int($$field) || $$field < $range[0] || $$field > $range[1])) {
if (static::isStrictModeEnabled()) {
throw new InvalidDateException($field, $$field);
}
return null;
}
}
$instance = static::create($year, $month, $day, $hour, $minute, $second, $timezone);
foreach (array_reverse($fields) as $field => $range) {
if ($$field !== null && (!\is_int($$field) || $$field !== $instance->$field)) {
if (static::isStrictModeEnabled()) {
throw new InvalidDateException($field, $$field);
}
return null;
}
}
return $instance;
}
/**
* Create a new Carbon instance from a specific date and time using strict validation.
*
* @see create()
*
* @param int|null $year
* @param int|null $month
* @param int|null $day
* @param int|null $hour
* @param int|null $minute
* @param int|null $second
* @param DateTimeZone|string|int|null $timezone
*
* @throws InvalidFormatException
*
* @return static
*/
public static function createStrict(?int $year = 0, ?int $month = 1, ?int $day = 1, ?int $hour = 0, ?int $minute = 0, ?int $second = 0, $timezone = null): static
{
$initialStrictMode = static::isStrictModeEnabled();
static::useStrictMode(true);
try {
$date = static::create($year, $month, $day, $hour, $minute, $second, $timezone);
} finally {
static::useStrictMode($initialStrictMode);
}
return $date;
}
/**
* Create a Carbon instance from just a date. The time portion is set to now.
*
* @param int|null $year
* @param int|null $month
* @param int|null $day
* @param DateTimeZone|string|int|null $timezone
*
* @throws InvalidFormatException
*
* @return static
*/
public static function createFromDate($year = null, $month = null, $day = null, $timezone = null)
{
return static::create($year, $month, $day, null, null, null, $timezone);
}
/**
* Create a Carbon instance from just a date. The time portion is set to midnight.
*
* @param int|null $year
* @param int|null $month
* @param int|null $day
* @param DateTimeZone|string|int|null $timezone
*
* @throws InvalidFormatException
*
* @return static
*/
public static function createMidnightDate($year = null, $month = null, $day = null, $timezone = null)
{
return static::create($year, $month, $day, 0, 0, 0, $timezone);
}
/**
* Create a Carbon instance from just a time. The date portion is set to today.
*
* @param int|null $hour
* @param int|null $minute
* @param int|null $second
* @param DateTimeZone|string|int|null $timezone
*
* @throws InvalidFormatException
*
* @return static
*/
public static function createFromTime($hour = 0, $minute = 0, $second = 0, $timezone = null): static
{
return static::create(null, null, null, $hour, $minute, $second, $timezone);
}
/**
* Create a Carbon instance from a time string. The date portion is set to today.
*
* @throws InvalidFormatException
*/
public static function createFromTimeString(string $time, DateTimeZone|string|int|null $timezone = null): static
{
return static::today($timezone)->setTimeFromTimeString($time);
}
private static function createFromFormatAndTimezone(
string $format,
string $time,
DateTimeZone|string|int|null $originalTimezone,
): ?DateTimeInterface {
if ($originalTimezone === null) {
return parent::createFromFormat($format, $time) ?: null;
}
$timezone = \is_int($originalTimezone) ? self::getOffsetTimezone($originalTimezone) : $originalTimezone;
$timezone = static::safeCreateDateTimeZone($timezone, $originalTimezone);
return parent::createFromFormat($format, $time, $timezone) ?: null;
}
private static function getOffsetTimezone(int $offset): string
{
$minutes = (int) ($offset * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE);
return @timezone_name_from_abbr('', $minutes, 1) ?: throw new InvalidTimeZoneException(
"Invalid offset timezone $offset",
);
}
/**
* Create a Carbon instance from a specific format.
*
* @param string $format Datetime format
* @param string $time
* @param DateTimeZone|string|int|null $timezone
*
* @throws InvalidFormatException
*
* @return static|null
*/
public static function rawCreateFromFormat(string $format, string $time, $timezone = null): ?self
{
// Work-around for https://bugs.php.net/bug.php?id=80141
$format = preg_replace('/(?<!\\\\)((?:\\\\{2})*)c/', '$1Y-m-d\TH:i:sP', $format);
if (preg_match('/(?<!\\\\)(?:\\\\{2})*(a|A)/', $format, $aMatches, PREG_OFFSET_CAPTURE) &&
preg_match('/(?<!\\\\)(?:\\\\{2})*(h|g|H|G)/', $format, $hMatches, PREG_OFFSET_CAPTURE) &&
$aMatches[1][1] < $hMatches[1][1] &&
preg_match('/(am|pm|AM|PM)/', $time)
) {
$format = preg_replace('/^(.*)(?<!\\\\)((?:\\\\{2})*)(a|A)(.*)$/U', '$1$2$4 $3', $format);
$time = preg_replace('/^(.*)(am|pm|AM|PM)(.*)$/U', '$1$3 $2', $time);
}
if ($timezone === false) {
$timezone = null;
}
// First attempt to create an instance, so that error messages are based on the unmodified format.
$date = self::createFromFormatAndTimezone($format, $time, $timezone);
$lastErrors = parent::getLastErrors();
/** @var \Carbon\CarbonImmutable|\Carbon\Carbon|null $mock */
$mock = static::getMockedTestNow($timezone);
if ($mock && $date instanceof DateTimeInterface) {
// Set timezone from mock if custom timezone was neither given directly nor as a part of format.
// First let's skip the part that will be ignored by the parser.
$nonEscaped = '(?<!\\\\)(\\\\{2})*';
$nonIgnored = preg_replace("/^.*{$nonEscaped}!/s", '', $format);
if ($timezone === null && !preg_match("/{$nonEscaped}[eOPT]/", $nonIgnored)) {
$timezone = clone $mock->getTimezone();
}
$mock = $mock->copy();
// Prepend mock datetime only if the format does not contain non escaped unix epoch reset flag.
if (!preg_match("/{$nonEscaped}[!|]/", $format)) {
if (preg_match('/[HhGgisvuB]/', $format)) {
$mock = $mock->setTime(0, 0);
}
$format = static::MOCK_DATETIME_FORMAT.' '.$format;
$time = ($mock instanceof self ? $mock->rawFormat(static::MOCK_DATETIME_FORMAT) : $mock->format(static::MOCK_DATETIME_FORMAT)).' '.$time;
}
// Regenerate date from the modified format to base result on the mocked instance instead of now.
$date = self::createFromFormatAndTimezone($format, $time, $timezone);
}
if ($date instanceof DateTimeInterface) {
$instance = static::instance($date);
$instance::setLastErrors($lastErrors);
return $instance;
}
if (static::isStrictModeEnabled()) {
throw new InvalidFormatException(implode(PHP_EOL, (array) $lastErrors['errors']));
}
return null;
}
/**
* Create a Carbon instance from a specific format.
*
* @param string $format Datetime format
* @param string $time
* @param DateTimeZone|string|int|null $timezone
*
* @throws InvalidFormatException
*
* @return static|null
*/
#[ReturnTypeWillChange]
public static function createFromFormat($format, $time, $timezone = null): ?self
{
$function = static::$createFromFormatFunction;
// format is a single numeric unit
if (\is_int($time) && \in_array(ltrim($format, '!'), ['U', 'Y', 'y', 'X', 'x', 'm', 'n', 'd', 'j', 'w', 'W', 'H', 'h', 'G', 'g', 'i', 's', 'u', 'z', 'v'], true)) {
$time = (string) $time;
}
if (!\is_string($time)) {
@trigger_error(
'createFromFormat() will only accept string or integer for 1-letter format representing a numeric unit int next version',
\E_USER_DEPRECATED,
);
$time = (string) $time;
}
if (!$function) {
return static::rawCreateFromFormat($format, $time, $timezone);
}
if (\is_string($function) && method_exists(static::class, $function)) {
$function = [static::class, $function];
}
return $function(...\func_get_args());
}
/**
* Create a Carbon instance from a specific ISO format (same replacements as ->isoFormat()).
*
* @param string $format Datetime format
* @param string $time
* @param DateTimeZone|string|int|null $timezone optional timezone
* @param string|null $locale locale to be used for LTS, LT, LL, LLL, etc. macro-formats (en by fault, unneeded if no such macro-format in use)
* @param TranslatorInterface|null $translator optional custom translator to use for macro-formats
*
* @throws InvalidFormatException
*
* @return static|null
*/
public static function createFromIsoFormat(
string $format,
string $time,
$timezone = null,
?string $locale = self::DEFAULT_LOCALE,
?TranslatorInterface $translator = null
): ?self {
$format = preg_replace_callback('/(?<!\\\\)(\\\\{2})*(LTS|LT|[Ll]{1,4})/', function ($match) use ($locale, $translator) {
[$code] = $match;
static $formats = null;
if ($formats === null) {
$translator ??= Translator::get($locale);
$formats = [
'LT' => static::getTranslationMessageWith($translator, 'formats.LT', $locale),
'LTS' => static::getTranslationMessageWith($translator, 'formats.LTS', $locale),
'L' => static::getTranslationMessageWith($translator, 'formats.L', $locale),
'LL' => static::getTranslationMessageWith($translator, 'formats.LL', $locale),
'LLL' => static::getTranslationMessageWith($translator, 'formats.LLL', $locale),
'LLLL' => static::getTranslationMessageWith($translator, 'formats.LLLL', $locale),
];
}
return $formats[$code] ?? preg_replace_callback(
'/MMMM|MM|DD|dddd/',
static fn (array $code) => mb_substr($code[0], 1),
$formats[strtoupper($code)] ?? '',
);
}, $format);
$format = preg_replace_callback('/(?<!\\\\)(\\\\{2})*('.CarbonInterface::ISO_FORMAT_REGEXP.'|[A-Za-z])/', function ($match) {
[$code] = $match;
static $replacements = null;
if ($replacements === null) {
$replacements = [
'OD' => 'd',
'OM' => 'M',
'OY' => 'Y',
'OH' => 'G',
'Oh' => 'g',
'Om' => 'i',
'Os' => 's',
'D' => 'd',
'DD' => 'd',
'Do' => 'd',
'd' => '!',
'dd' => '!',
'ddd' => 'D',
'dddd' => 'D',
'DDD' => 'z',
'DDDD' => 'z',
'DDDo' => 'z',
'e' => '!',
'E' => '!',
'H' => 'G',
'HH' => 'H',
'h' => 'g',
'hh' => 'h',
'k' => 'G',
'kk' => 'G',
'hmm' => 'gi',
'hmmss' => 'gis',
'Hmm' => 'Gi',
'Hmmss' => 'Gis',
'm' => 'i',
'mm' => 'i',
'a' => 'a',
'A' => 'a',
's' => 's',
'ss' => 's',
'S' => '*',
'SS' => '*',
'SSS' => '*',
'SSSS' => '*',
'SSSSS' => '*',
'SSSSSS' => 'u',
'SSSSSSS' => 'u*',
'SSSSSSSS' => 'u*',
'SSSSSSSSS' => 'u*',
'M' => 'm',
'MM' => 'm',
'MMM' => 'M',
'MMMM' => 'M',
'Mo' => 'm',
'Q' => '!',
'Qo' => '!',
'G' => '!',
'GG' => '!',
'GGG' => '!',
'GGGG' => '!',
'GGGGG' => '!',
'g' => '!',
'gg' => '!',
'ggg' => '!',
'gggg' => '!',
'ggggg' => '!',
'W' => '!',
'WW' => '!',
'Wo' => '!',
'w' => '!',
'ww' => '!',
'wo' => '!',
'x' => 'U???',
'X' => 'U',
'Y' => 'Y',
'YY' => 'y',
'YYYY' => 'Y',
'YYYYY' => 'Y',
'YYYYYY' => 'Y',
'z' => 'e',
'zz' => 'e',
'Z' => 'e',
'ZZ' => 'e',
];
}
$format = $replacements[$code] ?? '?';
if ($format === '!') {
throw new InvalidFormatException("Format $code not supported for creation.");
}
return $format;
}, $format);
return static::rawCreateFromFormat($format, $time, $timezone);
}
/**
* Create a Carbon instance from a specific format and a string in a given language.
*
* @param string $format Datetime format
* @param string $locale
* @param string $time
* @param DateTimeZone|string|int|null $timezone
*
* @throws InvalidFormatException
*
* @return static|null
*/
public static function createFromLocaleFormat(string $format, string $locale, string $time, $timezone = null): ?self
{
$format = preg_replace_callback(
'/(?:\\\\[a-zA-Z]|[bfkqCEJKQRV]){2,}/',
static function (array $match) use ($locale): string {
$word = str_replace('\\', '', $match[0]);
$translatedWord = static::translateTimeString($word, $locale, static::DEFAULT_LOCALE);
return $word === $translatedWord
? $match[0]
: preg_replace('/[a-zA-Z]/', '\\\\$0', $translatedWord);
},
$format
);
return static::rawCreateFromFormat($format, static::translateTimeString($time, $locale, static::DEFAULT_LOCALE), $timezone);
}
/**
* Create a Carbon instance from a specific ISO format and a string in a given language.
*
* @param string $format Datetime ISO format
* @param string $locale
* @param string $time
* @param DateTimeZone|string|int|null $timezone
*
* @throws InvalidFormatException
*
* @return static|null
*/
public static function createFromLocaleIsoFormat(string $format, string $locale, string $time, $timezone = null): ?self
{
$time = static::translateTimeString($time, $locale, static::DEFAULT_LOCALE, CarbonInterface::TRANSLATE_MONTHS | CarbonInterface::TRANSLATE_DAYS | CarbonInterface::TRANSLATE_MERIDIEM);
return static::createFromIsoFormat($format, $time, $timezone, $locale);
}
/**
* Make a Carbon instance from given variable if possible.
*
* Always return a new instance. Parse only strings and only these likely to be dates (skip intervals
* and recurrences). Throw an exception for invalid format, but otherwise return null.
*
* @param mixed $var
*
* @throws InvalidFormatException
*
* @return static|null
*/
public static function make($var): ?self
{
if ($var instanceof DateTimeInterface) {
return static::instance($var);
}
$date = null;
if (\is_string($var)) {
$var = trim($var);
if (!preg_match('/^P[\dT]/', $var) &&
!preg_match('/^R\d/', $var) &&
preg_match('/[a-z\d]/i', $var)
) {
$date = static::parse($var);
}
}
return $date;
}
/**
* Set last errors.
*
* @param array|bool $lastErrors
*
* @return void
*/
private static function setLastErrors($lastErrors): void
{
if (\is_array($lastErrors) || $lastErrors === false) {
static::$lastErrors = \is_array($lastErrors) ? $lastErrors : [
'warning_count' => 0,
'warnings' => [],
'error_count' => 0,
'errors' => [],
];
}
}
/**
* {@inheritdoc}
*/
public static function getLastErrors(): array|false
{
return static::$lastErrors ?? false;
}
private static function monthToInt(mixed $value, string $unit = 'month'): mixed
{
if ($value instanceof Month) {
if ($unit !== 'month') {
throw new UnitException("Month enum cannot be used to set $unit");
}
return Month::int($value);
}
return $value;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,83 @@
<?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Carbon\Traits;
use Carbon\CarbonInterface;
use Carbon\CarbonInterval;
trait DeprecatedPeriodProperties
{
/**
* Period start in PHP < 8.2.
*
* @var CarbonInterface
*
* @deprecated PHP 8.2 this property is no longer in sync with the actual period start.
*/
public $start;
/**
* Period end in PHP < 8.2.
*
* @var CarbonInterface|null
*
* @deprecated PHP 8.2 this property is no longer in sync with the actual period end.
*/
public $end;
/**
* Period current iterated date in PHP < 8.2.
*
* @var CarbonInterface|null
*
* @deprecated PHP 8.2 this property is no longer in sync with the actual period current iterated date.
*/
public $current;
/**
* Period interval in PHP < 8.2.
*
* @var CarbonInterval|null
*
* @deprecated PHP 8.2 this property is no longer in sync with the actual period interval.
*/
public $interval;
/**
* Period recurrences in PHP < 8.2.
*
* @var int|float|null
*
* @deprecated PHP 8.2 this property is no longer in sync with the actual period recurrences.
*/
public $recurrences;
/**
* Period start included option in PHP < 8.2.
*
* @var bool
*
* @deprecated PHP 8.2 this property is no longer in sync with the actual period start included option.
*/
public $include_start_date;
/**
* Period end included option in PHP < 8.2.
*
* @var bool
*
* @deprecated PHP 8.2 this property is no longer in sync with the actual period end included option.
*/
public $include_end_date;
}

View File

@@ -0,0 +1,866 @@
<?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Carbon\Traits;
use Carbon\Carbon;
use Carbon\CarbonImmutable;
use Carbon\CarbonInterface;
use Carbon\CarbonInterval;
use Carbon\CarbonPeriod;
use Carbon\Exceptions\UnknownUnitException;
use Carbon\Unit;
use Closure;
use DateInterval;
use DateTimeInterface;
/**
* Trait Difference.
*
* Depends on the following methods:
*
* @method bool lessThan($date)
* @method static copy()
* @method static resolveCarbon($date = null)
*/
trait Difference
{
/**
* Get the difference as a DateInterval instance.
* Return relative interval (negative if $absolute flag is not set to true and the given date is before
* current one).
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return DateInterval
*/
public function diffAsDateInterval($date = null, bool $absolute = false): DateInterval
{
$other = $this->resolveCarbon($date);
// Work-around for https://bugs.php.net/bug.php?id=81458
// It was initially introduced for https://bugs.php.net/bug.php?id=80998
// The very specific case of 80998 was fixed in PHP 8.1beta3, but it introduced 81458
// So we still need to keep this for now
if ($other->tz !== $this->tz) {
$other = $other->avoidMutation()->setTimezone($this->tz);
}
return parent::diff($other, $absolute);
}
/**
* Get the difference as a CarbonInterval instance.
* Return relative interval (negative if $absolute flag is not set to true and the given date is before
* current one).
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return CarbonInterval
*/
public function diffAsCarbonInterval($date = null, bool $absolute = false, array $skip = []): CarbonInterval
{
return CarbonInterval::diff($this, $this->resolveCarbon($date), $absolute, $skip)
->setLocalTranslator($this->getLocalTranslator());
}
/**
* @alias diffAsCarbonInterval
*
* Get the difference as a DateInterval instance.
* Return relative interval (negative if $absolute flag is not set to true and the given date is before
* current one).
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return CarbonInterval
*/
public function diff($date = null, bool $absolute = false, array $skip = []): CarbonInterval
{
return $this->diffAsCarbonInterval($date, $absolute, $skip);
}
/**
* @param Unit|string $unit microsecond, millisecond, second, minute,
* hour, day, week, month, quarter, year,
* century, millennium
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
* @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different)
*
* @return float
*/
public function diffInUnit(Unit|string $unit, $date = null, bool $absolute = false, bool $utc = false): float
{
$unit = static::pluralUnit($unit instanceof Unit ? $unit->value : rtrim($unit, 'z'));
$method = 'diffIn'.$unit;
if (!method_exists($this, $method)) {
throw new UnknownUnitException($unit);
}
return $this->$method($date, $absolute, $utc);
}
/**
* Get the difference in years
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
* @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different)
*
* @return float
*/
public function diffInYears($date = null, bool $absolute = false, bool $utc = false): float
{
$start = $this;
$end = $this->resolveCarbon($date);
if ($utc) {
$start = $start->avoidMutation()->utc();
$end = $end->avoidMutation()->utc();
}
$ascending = ($start <= $end);
$sign = $absolute || $ascending ? 1 : -1;
if (!$ascending) {
[$start, $end] = [$end, $start];
}
$yearsDiff = (int) $start->diff($end, $absolute)->format('%r%y');
/** @var Carbon|CarbonImmutable $floorEnd */
$floorEnd = $start->copy()->addYears($yearsDiff);
if ($floorEnd >= $end) {
return $sign * $yearsDiff;
}
/** @var Carbon|CarbonImmutable $startOfYearAfterFloorEnd */
$startOfYearAfterFloorEnd = $floorEnd->copy()->addYear()->startOfYear();
if ($startOfYearAfterFloorEnd > $end) {
return $sign * ($yearsDiff + $floorEnd->diffInDays($end) / $floorEnd->daysInYear);
}
return $sign * ($yearsDiff + $floorEnd->diffInDays($startOfYearAfterFloorEnd) / $floorEnd->daysInYear + $startOfYearAfterFloorEnd->diffInDays($end) / $end->daysInYear);
}
/**
* Get the difference in quarters.
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
* @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different)
*
* @return float
*/
public function diffInQuarters($date = null, bool $absolute = false, bool $utc = false): float
{
return $this->diffInMonths($date, $absolute, $utc) / static::MONTHS_PER_QUARTER;
}
/**
* Get the difference in months.
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
* @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different)
*
* @return float
*/
public function diffInMonths($date = null, bool $absolute = false, bool $utc = false): float
{
$start = $this;
$end = $this->resolveCarbon($date);
$compareUsingUtc = $utc || ($end->timezoneName !== $start->timezoneName);
if ($compareUsingUtc) {
$start = $start->avoidMutation()->utc();
$end = $end->avoidMutation()->utc();
}
[$yearStart, $monthStart, $dayStart] = explode('-', $start->format('Y-m-dHisu'));
[$yearEnd, $monthEnd, $dayEnd] = explode('-', $end->format('Y-m-dHisu'));
$monthsDiff = (((int) $yearEnd) - ((int) $yearStart)) * static::MONTHS_PER_YEAR +
((int) $monthEnd) - ((int) $monthStart);
if ($monthsDiff > 0) {
$monthsDiff -= ($dayStart > $dayEnd ? 1 : 0);
} elseif ($monthsDiff < 0) {
$monthsDiff += ($dayStart < $dayEnd ? 1 : 0);
}
$ascending = ($start <= $end);
$sign = $absolute || $ascending ? 1 : -1;
$monthsDiff = abs($monthsDiff);
if (!$ascending) {
[$start, $end] = [$end, $start];
}
/** @var Carbon|CarbonImmutable $floorEnd */
$floorEnd = $start->avoidMutation()->addMonths($monthsDiff);
if ($floorEnd >= $end) {
return $sign * $monthsDiff;
}
/** @var Carbon|CarbonImmutable $startOfMonthAfterFloorEnd */
$startOfMonthAfterFloorEnd = $floorEnd->avoidMutation()->addMonthNoOverflow()->startOfMonth();
if ($startOfMonthAfterFloorEnd > $end) {
return $sign * ($monthsDiff + $floorEnd->diffInDays($end) / $floorEnd->daysInMonth);
}
return $sign * ($monthsDiff + $floorEnd->diffInDays($startOfMonthAfterFloorEnd) / $floorEnd->daysInMonth + $startOfMonthAfterFloorEnd->diffInDays($end) / $end->daysInMonth);
}
/**
* Get the difference in weeks.
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
* @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different)
*
* @return float
*/
public function diffInWeeks($date = null, bool $absolute = false, bool $utc = false): float
{
return $this->diffInDays($date, $absolute, $utc) / static::DAYS_PER_WEEK;
}
/**
* Get the difference in days.
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
* @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different)
*
* @return float
*/
public function diffInDays($date = null, bool $absolute = false, bool $utc = false): float
{
$date = $this->resolveCarbon($date);
$current = $this;
$compareUsingUtc = $utc || ($date->timezoneName !== $current->timezoneName);
if ($compareUsingUtc) {
$date = $date->avoidMutation()->utc();
$current = $current->avoidMutation()->utc();
}
$interval = $current->diffAsDateInterval($date, $absolute);
if (!$compareUsingUtc) {
$minutes = $interval->i + ($interval->s + $interval->f) / static::SECONDS_PER_MINUTE;
// 24 hours means there is a DST bug
$hours = ($interval->h === 24 && $interval->days !== false ? 0 : $interval->h) + $minutes / static::MINUTES_PER_HOUR;
return $this->getIntervalDayDiff($interval)
+ ($interval->invert ? -$hours : $hours) / static::HOURS_PER_DAY;
}
$hoursDiff = $current->diffInHours($date, $absolute);
if ($interval->y === 0 && $interval->m === 0 && $interval->d === 0) {
return $hoursDiff / static::HOURS_PER_DAY;
}
return $this->getIntervalDayDiff($interval)
+ fmod($hoursDiff, static::HOURS_PER_DAY) / static::HOURS_PER_DAY;
}
/**
* Get the difference in days using a filter closure.
*
* @param Closure $callback
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return int
*/
public function diffInDaysFiltered(Closure $callback, $date = null, bool $absolute = false): int
{
return $this->diffFiltered(CarbonInterval::day(), $callback, $date, $absolute);
}
/**
* Get the difference in hours using a filter closure.
*
* @param Closure $callback
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return int
*/
public function diffInHoursFiltered(Closure $callback, $date = null, bool $absolute = false): int
{
return $this->diffFiltered(CarbonInterval::hour(), $callback, $date, $absolute);
}
/**
* Get the difference by the given interval using a filter closure.
*
* @param CarbonInterval $ci An interval to traverse by
* @param Closure $callback
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return int
*/
public function diffFiltered(CarbonInterval $ci, Closure $callback, $date = null, bool $absolute = false): int
{
$start = $this;
$end = $this->resolveCarbon($date);
$inverse = false;
if ($end < $start) {
$start = $end;
$end = $this;
$inverse = true;
}
$options = CarbonPeriod::EXCLUDE_END_DATE | ($this->isMutable() ? 0 : CarbonPeriod::IMMUTABLE);
$diff = $ci->toPeriod($start, $end, $options)->filter($callback)->count();
return $inverse && !$absolute ? -$diff : $diff;
}
/**
* Get the difference in weekdays.
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return int
*/
public function diffInWeekdays($date = null, bool $absolute = false): int
{
return $this->diffInDaysFiltered(
static fn (CarbonInterface $date) => $date->isWeekday(),
$this->resolveCarbon($date)->avoidMutation()->modify($this->format('H:i:s.u')),
$absolute,
);
}
/**
* Get the difference in weekend days using a filter.
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return int
*/
public function diffInWeekendDays($date = null, bool $absolute = false): int
{
return $this->diffInDaysFiltered(
static fn (CarbonInterface $date) => $date->isWeekend(),
$this->resolveCarbon($date)->avoidMutation()->modify($this->format('H:i:s.u')),
$absolute,
);
}
/**
* Get the difference in hours.
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return float
*/
public function diffInHours($date = null, bool $absolute = false): float
{
return $this->diffInMinutes($date, $absolute) / static::MINUTES_PER_HOUR;
}
/**
* Get the difference in minutes.
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return float
*/
public function diffInMinutes($date = null, bool $absolute = false): float
{
return $this->diffInSeconds($date, $absolute) / static::SECONDS_PER_MINUTE;
}
/**
* Get the difference in seconds.
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return float
*/
public function diffInSeconds($date = null, bool $absolute = false): float
{
return $this->diffInMilliseconds($date, $absolute) / static::MILLISECONDS_PER_SECOND;
}
/**
* Get the difference in microseconds.
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return float
*/
public function diffInMicroseconds($date = null, bool $absolute = false): float
{
/** @var CarbonInterface $date */
$date = $this->resolveCarbon($date);
$value = ($date->timestamp - $this->timestamp) * static::MICROSECONDS_PER_SECOND +
$date->micro - $this->micro;
return $absolute ? abs($value) : $value;
}
/**
* Get the difference in milliseconds.
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return float
*/
public function diffInMilliseconds($date = null, bool $absolute = false): float
{
return $this->diffInMicroseconds($date, $absolute) / static::MICROSECONDS_PER_MILLISECOND;
}
/**
* The number of seconds since midnight.
*
* @return float
*/
public function secondsSinceMidnight(): float
{
return $this->diffInSeconds($this->copy()->startOfDay(), true);
}
/**
* The number of seconds until 23:59:59.
*
* @return float
*/
public function secondsUntilEndOfDay(): float
{
return $this->diffInSeconds($this->copy()->endOfDay(), true);
}
/**
* Get the difference in a human readable format in the current locale from current instance to an other
* instance given (or now if null given).
*
* @example
* ```
* echo Carbon::tomorrow()->diffForHumans() . "\n";
* echo Carbon::tomorrow()->diffForHumans(['parts' => 2]) . "\n";
* echo Carbon::tomorrow()->diffForHumans(['parts' => 3, 'join' => true]) . "\n";
* echo Carbon::tomorrow()->diffForHumans(Carbon::yesterday()) . "\n";
* echo Carbon::tomorrow()->diffForHumans(Carbon::yesterday(), ['short' => true]) . "\n";
* ```
*
* @param Carbon|DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below;
* if null passed, now will be used as comparison reference;
* if any other type, it will be converted to date and used as reference.
* @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains:
* ⦿ 'syntax' entry (see below)
* ⦿ 'short' entry (see below)
* ⦿ 'parts' entry (see below)
* ⦿ 'options' entry (see below)
* ⦿ 'skip' entry, list of units to skip (array of strings or a single string,
* ` it can be the unit name (singular or plural) or its shortcut
* ` (y, m, w, d, h, min, s, ms, µs).
* ⦿ 'aUnit' entry, prefer "an hour" over "1 hour" if true
* ⦿ 'altNumbers' entry, use alternative numbers if available
* ` (from the current language if true is passed, from the given language(s)
* ` if array or string is passed)
* ⦿ 'join' entry determines how to join multiple parts of the string
* ` - if $join is a string, it's used as a joiner glue
* ` - if $join is a callable/closure, it get the list of string and should return a string
* ` - if $join is an array, the first item will be the default glue, and the second item
* ` will be used instead of the glue for the last item
* ` - if $join is true, it will be guessed from the locale ('list' translation file entry)
* ` - if $join is missing, a space will be used as glue
* ⦿ 'other' entry (see above)
* ⦿ 'minimumUnit' entry determines the smallest unit of time to display can be long or
* ` short form of the units, e.g. 'hour' or 'h' (default value: s)
* ⦿ 'locale' language in which the diff should be output (has no effect if 'translator' key is set)
* ⦿ 'translator' a custom translator to use to translator the output.
* if int passed, it adds modifiers:
* Possible values:
* - CarbonInterface::DIFF_ABSOLUTE no modifiers
* - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier
* - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier
* Default value: CarbonInterface::DIFF_ABSOLUTE
* @param bool $short displays short format of time units
* @param int $parts maximum number of parts to display (default value: 1: single unit)
* @param int $options human diff options
*/
public function diffForHumans($other = null, $syntax = null, $short = false, $parts = 1, $options = null): string
{
/* @var CarbonInterface $this */
if (\is_array($other)) {
$other['syntax'] = \array_key_exists('syntax', $other) ? $other['syntax'] : $syntax;
$syntax = $other;
$other = $syntax['other'] ?? null;
}
$intSyntax = &$syntax;
if (\is_array($syntax)) {
$syntax['syntax'] = $syntax['syntax'] ?? null;
$intSyntax = &$syntax['syntax'];
}
$intSyntax = (int) ($intSyntax ?? static::DIFF_RELATIVE_AUTO);
$intSyntax = $intSyntax === static::DIFF_RELATIVE_AUTO && $other === null ? static::DIFF_RELATIVE_TO_NOW : $intSyntax;
$parts = min(7, max(1, (int) $parts));
$skip = \is_array($syntax) ? ($syntax['skip'] ?? []) : [];
$options ??= $this->localHumanDiffOptions ?? $this->transmitFactory(
static fn () => static::getHumanDiffOptions(),
);
return $this->diff($other, skip: (array) $skip)->forHumans($syntax, (bool) $short, $parts, $options);
}
/**
* @alias diffForHumans
*
* Get the difference in a human readable format in the current locale from current instance to an other
* instance given (or now if null given).
*
* @param Carbon|\DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below;
* if null passed, now will be used as comparison reference;
* if any other type, it will be converted to date and used as reference.
* @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains:
* - 'syntax' entry (see below)
* - 'short' entry (see below)
* - 'parts' entry (see below)
* - 'options' entry (see below)
* - 'join' entry determines how to join multiple parts of the string
* ` - if $join is a string, it's used as a joiner glue
* ` - if $join is a callable/closure, it get the list of string and should return a string
* ` - if $join is an array, the first item will be the default glue, and the second item
* ` will be used instead of the glue for the last item
* ` - if $join is true, it will be guessed from the locale ('list' translation file entry)
* ` - if $join is missing, a space will be used as glue
* - 'other' entry (see above)
* if int passed, it add modifiers:
* Possible values:
* - CarbonInterface::DIFF_ABSOLUTE no modifiers
* - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier
* - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier
* Default value: CarbonInterface::DIFF_ABSOLUTE
* @param bool $short displays short format of time units
* @param int $parts maximum number of parts to display (default value: 1: single unit)
* @param int $options human diff options
*
* @return string
*/
public function from($other = null, $syntax = null, $short = false, $parts = 1, $options = null)
{
return $this->diffForHumans($other, $syntax, $short, $parts, $options);
}
/**
* @alias diffForHumans
*
* Get the difference in a human readable format in the current locale from current instance to an other
* instance given (or now if null given).
*/
public function since($other = null, $syntax = null, $short = false, $parts = 1, $options = null)
{
return $this->diffForHumans($other, $syntax, $short, $parts, $options);
}
/**
* Get the difference in a human readable format in the current locale from an other
* instance given (or now if null given) to current instance.
*
* When comparing a value in the past to default now:
* 1 hour from now
* 5 months from now
*
* When comparing a value in the future to default now:
* 1 hour ago
* 5 months ago
*
* When comparing a value in the past to another value:
* 1 hour after
* 5 months after
*
* When comparing a value in the future to another value:
* 1 hour before
* 5 months before
*
* @param Carbon|\DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below;
* if null passed, now will be used as comparison reference;
* if any other type, it will be converted to date and used as reference.
* @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains:
* - 'syntax' entry (see below)
* - 'short' entry (see below)
* - 'parts' entry (see below)
* - 'options' entry (see below)
* - 'join' entry determines how to join multiple parts of the string
* ` - if $join is a string, it's used as a joiner glue
* ` - if $join is a callable/closure, it get the list of string and should return a string
* ` - if $join is an array, the first item will be the default glue, and the second item
* ` will be used instead of the glue for the last item
* ` - if $join is true, it will be guessed from the locale ('list' translation file entry)
* ` - if $join is missing, a space will be used as glue
* - 'other' entry (see above)
* if int passed, it add modifiers:
* Possible values:
* - CarbonInterface::DIFF_ABSOLUTE no modifiers
* - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier
* - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier
* Default value: CarbonInterface::DIFF_ABSOLUTE
* @param bool $short displays short format of time units
* @param int $parts maximum number of parts to display (default value: 1: single unit)
* @param int $options human diff options
*
* @return string
*/
public function to($other = null, $syntax = null, $short = false, $parts = 1, $options = null)
{
if (!$syntax && !$other) {
$syntax = CarbonInterface::DIFF_RELATIVE_TO_NOW;
}
return $this->resolveCarbon($other)->diffForHumans($this, $syntax, $short, $parts, $options);
}
/**
* @alias to
*
* Get the difference in a human readable format in the current locale from an other
* instance given (or now if null given) to current instance.
*
* @param Carbon|\DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below;
* if null passed, now will be used as comparison reference;
* if any other type, it will be converted to date and used as reference.
* @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains:
* - 'syntax' entry (see below)
* - 'short' entry (see below)
* - 'parts' entry (see below)
* - 'options' entry (see below)
* - 'join' entry determines how to join multiple parts of the string
* ` - if $join is a string, it's used as a joiner glue
* ` - if $join is a callable/closure, it get the list of string and should return a string
* ` - if $join is an array, the first item will be the default glue, and the second item
* ` will be used instead of the glue for the last item
* ` - if $join is true, it will be guessed from the locale ('list' translation file entry)
* ` - if $join is missing, a space will be used as glue
* - 'other' entry (see above)
* if int passed, it add modifiers:
* Possible values:
* - CarbonInterface::DIFF_ABSOLUTE no modifiers
* - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier
* - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier
* Default value: CarbonInterface::DIFF_ABSOLUTE
* @param bool $short displays short format of time units
* @param int $parts maximum number of parts to display (default value: 1: single unit)
* @param int $options human diff options
*
* @return string
*/
public function until($other = null, $syntax = null, $short = false, $parts = 1, $options = null)
{
return $this->to($other, $syntax, $short, $parts, $options);
}
/**
* Get the difference in a human readable format in the current locale from current
* instance to now.
*
* @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains:
* - 'syntax' entry (see below)
* - 'short' entry (see below)
* - 'parts' entry (see below)
* - 'options' entry (see below)
* - 'join' entry determines how to join multiple parts of the string
* ` - if $join is a string, it's used as a joiner glue
* ` - if $join is a callable/closure, it get the list of string and should return a string
* ` - if $join is an array, the first item will be the default glue, and the second item
* ` will be used instead of the glue for the last item
* ` - if $join is true, it will be guessed from the locale ('list' translation file entry)
* ` - if $join is missing, a space will be used as glue
* if int passed, it add modifiers:
* Possible values:
* - CarbonInterface::DIFF_ABSOLUTE no modifiers
* - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier
* - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier
* Default value: CarbonInterface::DIFF_ABSOLUTE
* @param bool $short displays short format of time units
* @param int $parts maximum number of parts to display (default value: 1: single unit)
* @param int $options human diff options
*
* @return string
*/
public function fromNow($syntax = null, $short = false, $parts = 1, $options = null)
{
$other = null;
if ($syntax instanceof DateTimeInterface) {
[$other, $syntax, $short, $parts, $options] = array_pad(\func_get_args(), 5, null);
}
return $this->from($other, $syntax, $short, $parts, $options);
}
/**
* Get the difference in a human readable format in the current locale from an other
* instance given to now
*
* @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains:
* - 'syntax' entry (see below)
* - 'short' entry (see below)
* - 'parts' entry (see below)
* - 'options' entry (see below)
* - 'join' entry determines how to join multiple parts of the string
* ` - if $join is a string, it's used as a joiner glue
* ` - if $join is a callable/closure, it get the list of string and should return a string
* ` - if $join is an array, the first item will be the default glue, and the second item
* ` will be used instead of the glue for the last item
* ` - if $join is true, it will be guessed from the locale ('list' translation file entry)
* ` - if $join is missing, a space will be used as glue
* if int passed, it add modifiers:
* Possible values:
* - CarbonInterface::DIFF_ABSOLUTE no modifiers
* - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier
* - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier
* Default value: CarbonInterface::DIFF_ABSOLUTE
* @param bool $short displays short format of time units
* @param int $parts maximum number of parts to display (default value: 1: single part)
* @param int $options human diff options
*
* @return string
*/
public function toNow($syntax = null, $short = false, $parts = 1, $options = null)
{
return $this->to(null, $syntax, $short, $parts, $options);
}
/**
* Get the difference in a human readable format in the current locale from an other
* instance given to now
*
* @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains:
* - 'syntax' entry (see below)
* - 'short' entry (see below)
* - 'parts' entry (see below)
* - 'options' entry (see below)
* - 'join' entry determines how to join multiple parts of the string
* ` - if $join is a string, it's used as a joiner glue
* ` - if $join is a callable/closure, it get the list of string and should return a string
* ` - if $join is an array, the first item will be the default glue, and the second item
* ` will be used instead of the glue for the last item
* ` - if $join is true, it will be guessed from the locale ('list' translation file entry)
* ` - if $join is missing, a space will be used as glue
* if int passed, it add modifiers:
* Possible values:
* - CarbonInterface::DIFF_ABSOLUTE no modifiers
* - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier
* - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier
* Default value: CarbonInterface::DIFF_ABSOLUTE
* @param bool $short displays short format of time units
* @param int $parts maximum number of parts to display (default value: 1: single part)
* @param int $options human diff options
*
* @return string
*/
public function ago($syntax = null, $short = false, $parts = 1, $options = null)
{
$other = null;
if ($syntax instanceof DateTimeInterface) {
[$other, $syntax, $short, $parts, $options] = array_pad(\func_get_args(), 5, null);
}
return $this->from($other, $syntax, $short, $parts, $options);
}
/**
* Get the difference in a human-readable format in the current locale from current instance to another
* instance given (or now if null given).
*
* @return string
*/
public function timespan($other = null, $timezone = null): string
{
if (\is_string($other)) {
$other = $this->transmitFactory(static fn () => static::parse($other, $timezone));
}
return $this->diffForHumans($other, [
'join' => ', ',
'syntax' => CarbonInterface::DIFF_ABSOLUTE,
'parts' => INF,
]);
}
/**
* Returns either day of week + time (e.g. "Last Friday at 3:30 PM") if reference time is within 7 days,
* or a calendar date (e.g. "10/29/2017") otherwise.
*
* Language, date and time formats will change according to the current locale.
*
* @param Carbon|\DateTimeInterface|string|null $referenceTime
* @param array $formats
*
* @return string
*/
public function calendar($referenceTime = null, array $formats = [])
{
/** @var CarbonInterface $current */
$current = $this->avoidMutation()->startOfDay();
/** @var CarbonInterface $other */
$other = $this->resolveCarbon($referenceTime)->avoidMutation()->setTimezone($this->getTimezone())->startOfDay();
$diff = $other->diffInDays($current, false);
$format = $diff <= -static::DAYS_PER_WEEK ? 'sameElse' : (
$diff < -1 ? 'lastWeek' : (
$diff < 0 ? 'lastDay' : (
$diff < 1 ? 'sameDay' : (
$diff < 2 ? 'nextDay' : (
$diff < static::DAYS_PER_WEEK ? 'nextWeek' : 'sameElse'
)
)
)
)
);
$format = array_merge($this->getCalendarFormats(), $formats)[$format];
if ($format instanceof Closure) {
$format = $format($current, $other) ?? '';
}
return $this->isoFormat((string) $format);
}
private function getIntervalDayDiff(DateInterval $interval): int
{
$daysDiff = (int) $interval->format('%a');
$sign = $interval->format('%r') === '-' ? -1 : 1;
return $daysDiff * $sign;
}
}

View File

@@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Carbon\Traits;
use Carbon\CarbonInterval;
use Carbon\Exceptions\InvalidIntervalException;
use DateInterval;
/**
* Trait to call rounding methods to interval or the interval of a period.
*/
trait IntervalRounding
{
protected function callRoundMethod(string $method, array $parameters): ?static
{
$action = substr($method, 0, 4);
if ($action !== 'ceil') {
$action = substr($method, 0, 5);
}
if (\in_array($action, ['round', 'floor', 'ceil'])) {
return $this->{$action.'Unit'}(substr($method, \strlen($action)), ...$parameters);
}
return null;
}
protected function roundWith(DateInterval|string|float|int $precision, callable|string $function): ?static
{
$unit = 'second';
if ($precision instanceof DateInterval) {
$precision = CarbonInterval::instance($precision)->forHumans(['locale' => 'en']);
}
if (\is_string($precision) && preg_match('/^\s*(?<precision>\d+)?\s*(?<unit>\w+)(?<other>\W.*)?$/', $precision, $match)) {
if (trim($match['other'] ?? '') !== '') {
throw new InvalidIntervalException('Rounding is only possible with single unit intervals.');
}
$precision = (int) ($match['precision'] ?: 1);
$unit = $match['unit'];
}
return $this->roundUnit($unit, $precision, $function);
}
}

View File

@@ -0,0 +1,94 @@
<?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Carbon\Traits;
use Carbon\Callback;
use Carbon\Carbon;
use Carbon\CarbonImmutable;
use Carbon\CarbonInterface;
use Closure;
use DateTimeImmutable;
use DateTimeInterface;
trait IntervalStep
{
/**
* Step to apply instead of a fixed interval to get the new date.
*
* @var Closure|null
*/
protected $step;
/**
* Get the dynamic step in use.
*
* @return Closure
*/
public function getStep(): ?Closure
{
return $this->step;
}
/**
* Set a step to apply instead of a fixed interval to get the new date.
*
* Or pass null to switch to fixed interval.
*
* @param Closure|null $step
*/
public function setStep(?Closure $step): void
{
$this->step = $step;
}
/**
* Take a date and apply either the step if set, or the current interval else.
*
* The interval/step is applied negatively (typically subtraction instead of addition) if $negated is true.
*
* @param DateTimeInterface $dateTime
* @param bool $negated
*
* @return CarbonInterface
*/
public function convertDate(DateTimeInterface $dateTime, bool $negated = false): CarbonInterface
{
/** @var CarbonInterface $carbonDate */
$carbonDate = $dateTime instanceof CarbonInterface ? $dateTime : $this->resolveCarbon($dateTime);
if ($this->step) {
$carbonDate = Callback::parameter($this->step, $carbonDate->avoidMutation());
return $carbonDate->setDateTimeFrom(($this->step)($carbonDate, $negated));
}
if ($negated) {
return $carbonDate->rawSub($this);
}
return $carbonDate->rawAdd($this);
}
/**
* Convert DateTimeImmutable instance to CarbonImmutable instance and DateTime instance to Carbon instance.
*/
private function resolveCarbon(DateTimeInterface $dateTime): Carbon|CarbonImmutable
{
if ($dateTime instanceof DateTimeImmutable) {
return CarbonImmutable::instance($dateTime);
}
return Carbon::instance($dateTime);
}
}

View File

@@ -0,0 +1,67 @@
<?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Carbon\Traits;
use Carbon\Factory;
use Carbon\FactoryImmutable;
use Carbon\WrapperClock;
use Closure;
/**
* Remember the factory that was the current at the creation of the object.
*/
trait LocalFactory
{
/**
* The clock that generated the current instance (or FactoryImmutable::getDefaultInstance() if none)
*/
private ?WrapperClock $clock = null;
public function getClock(): ?WrapperClock
{
return $this->clock;
}
private function initLocalFactory(): void
{
$this->clock = FactoryImmutable::getCurrentClock();
}
/**
* Trigger the given action using the local factory of the object, so it will be transmitted
* to any object also using this trait and calling initLocalFactory() in its constructor.
*
* @template T
*
* @param Closure(): T $action
*
* @return T
*/
private function transmitFactory(Closure $action): mixed
{
$previousClock = FactoryImmutable::getCurrentClock();
FactoryImmutable::setCurrentClock($this->clock);
try {
return $action();
} finally {
FactoryImmutable::setCurrentClock($previousClock);
}
}
private function getFactory(): Factory
{
return $this->getClock()?->getFactory() ?? FactoryImmutable::getDefaultInstance();
}
}

View File

@@ -0,0 +1,728 @@
<?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Carbon\Traits;
use Carbon\CarbonInterface;
use Carbon\Exceptions\InvalidTypeException;
use Carbon\Exceptions\NotLocaleAwareException;
use Carbon\Language;
use Carbon\Translator;
use Carbon\TranslatorStrongTypeInterface;
use Closure;
use Symfony\Component\Translation\TranslatorBagInterface;
use Symfony\Contracts\Translation\LocaleAwareInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* Trait Localization.
*
* Embed default and locale translators and translation base methods.
*/
trait Localization
{
use StaticLocalization;
/**
* Specific translator of the current instance.
*/
protected ?TranslatorInterface $localTranslator = null;
/**
* Return true if the current instance has its own translator.
*/
public function hasLocalTranslator(): bool
{
return isset($this->localTranslator);
}
/**
* Get the translator of the current instance or the default if none set.
*/
public function getLocalTranslator(): TranslatorInterface
{
return $this->localTranslator ?? $this->transmitFactory(static fn () => static::getTranslator());
}
/**
* Set the translator for the current instance.
*/
public function setLocalTranslator(TranslatorInterface $translator): self
{
$this->localTranslator = $translator;
return $this;
}
/**
* Returns raw translation message for a given key.
*
* @param TranslatorInterface|null $translator the translator to use
* @param string $key key to find
* @param string|null $locale current locale used if null
* @param string|null $default default value if translation returns the key
*
* @return string|Closure|null
*/
public static function getTranslationMessageWith($translator, string $key, ?string $locale = null, ?string $default = null)
{
if (!($translator instanceof TranslatorBagInterface && $translator instanceof TranslatorInterface)) {
throw new InvalidTypeException(
'Translator does not implement '.TranslatorInterface::class.' and '.TranslatorBagInterface::class.'. '.
(\is_object($translator) ? \get_class($translator) : \gettype($translator)).' has been given.',
);
}
if (!$locale && $translator instanceof LocaleAwareInterface) {
$locale = $translator->getLocale();
}
$result = self::getFromCatalogue($translator, $translator->getCatalogue($locale), $key);
return $result === $key ? $default : $result;
}
/**
* Returns raw translation message for a given key.
*
* @param string $key key to find
* @param string|null $locale current locale used if null
* @param string|null $default default value if translation returns the key
* @param TranslatorInterface $translator an optional translator to use
*
* @return string
*/
public function getTranslationMessage(string $key, ?string $locale = null, ?string $default = null, $translator = null)
{
return static::getTranslationMessageWith($translator ?? $this->getLocalTranslator(), $key, $locale, $default);
}
/**
* Translate using translation string or callback available.
*
* @param TranslatorInterface $translator an optional translator to use
* @param string $key key to find
* @param array $parameters replacement parameters
* @param int|float|null $number number if plural
*
* @return string
*/
public static function translateWith(TranslatorInterface $translator, string $key, array $parameters = [], $number = null): string
{
$message = static::getTranslationMessageWith($translator, $key, null, $key);
if ($message instanceof Closure) {
return (string) $message(...array_values($parameters));
}
if ($number !== null) {
$parameters['%count%'] = $number;
}
if (isset($parameters['%count%'])) {
$parameters[':count'] = $parameters['%count%'];
}
return (string) $translator->trans($key, $parameters);
}
/**
* Translate using translation string or callback available.
*
* @param string $key key to find
* @param array $parameters replacement parameters
* @param string|int|float|null $number number if plural
* @param TranslatorInterface|null $translator an optional translator to use
* @param bool $altNumbers pass true to use alternative numbers
*
* @return string
*/
public function translate(
string $key,
array $parameters = [],
string|int|float|null $number = null,
?TranslatorInterface $translator = null,
bool $altNumbers = false,
): string {
$translation = static::translateWith($translator ?? $this->getLocalTranslator(), $key, $parameters, $number);
if ($number !== null && $altNumbers) {
return str_replace((string) $number, $this->translateNumber((int) $number), $translation);
}
return $translation;
}
/**
* Returns the alternative number for a given integer if available in the current locale.
*
* @param int $number
*
* @return string
*/
public function translateNumber(int $number): string
{
$translateKey = "alt_numbers.$number";
$symbol = $this->translate($translateKey);
if ($symbol !== $translateKey) {
return $symbol;
}
if ($number > 99 && $this->translate('alt_numbers.99') !== 'alt_numbers.99') {
$start = '';
foreach ([10000, 1000, 100] as $exp) {
$key = "alt_numbers_pow.$exp";
if ($number >= $exp && $number < $exp * 10 && ($pow = $this->translate($key)) !== $key) {
$unit = floor($number / $exp);
$number -= $unit * $exp;
$start .= ($unit > 1 ? $this->translate("alt_numbers.$unit") : '').$pow;
}
}
$result = '';
while ($number) {
$chunk = $number % 100;
$result = $this->translate("alt_numbers.$chunk").$result;
$number = floor($number / 100);
}
return "$start$result";
}
if ($number > 9 && $this->translate('alt_numbers.9') !== 'alt_numbers.9') {
$result = '';
while ($number) {
$chunk = $number % 10;
$result = $this->translate("alt_numbers.$chunk").$result;
$number = floor($number / 10);
}
return $result;
}
return (string) $number;
}
/**
* Translate a time string from a locale to an other.
*
* @param string $timeString date/time/duration string to translate (may also contain English)
* @param string|null $from input locale of the $timeString parameter (`Carbon::getLocale()` by default)
* @param string|null $to output locale of the result returned (`"en"` by default)
* @param int $mode specify what to translate with options:
* - CarbonInterface::TRANSLATE_ALL (default)
* - CarbonInterface::TRANSLATE_MONTHS
* - CarbonInterface::TRANSLATE_DAYS
* - CarbonInterface::TRANSLATE_UNITS
* - CarbonInterface::TRANSLATE_MERIDIEM
* You can use pipe to group: CarbonInterface::TRANSLATE_MONTHS | CarbonInterface::TRANSLATE_DAYS
*
* @return string
*/
public static function translateTimeString(
string $timeString,
?string $from = null,
?string $to = null,
int $mode = CarbonInterface::TRANSLATE_ALL,
): string {
// Fallback source and destination locales
$from = $from ?: static::getLocale();
$to = $to ?: CarbonInterface::DEFAULT_LOCALE;
if ($from === $to) {
return $timeString;
}
// Standardize apostrophe
$timeString = strtr($timeString, ['' => "'"]);
$fromTranslations = [];
$toTranslations = [];
foreach (['from', 'to'] as $key) {
$language = $$key;
$translator = Translator::get($language);
$translations = $translator->getMessages();
if (!isset($translations[$language])) {
return $timeString;
}
$translationKey = $key.'Translations';
$messages = $translations[$language];
$months = $messages['months'] ?? [];
$weekdays = $messages['weekdays'] ?? [];
$meridiem = $messages['meridiem'] ?? ['AM', 'PM'];
if (isset($messages['ordinal_words'])) {
$timeString = self::replaceOrdinalWords(
$timeString,
$key === 'from' ? array_flip($messages['ordinal_words']) : $messages['ordinal_words']
);
}
if ($key === 'from') {
foreach (['months', 'weekdays'] as $variable) {
$list = $messages[$variable.'_standalone'] ?? null;
if ($list) {
foreach ($$variable as $index => &$name) {
$name .= '|'.$messages[$variable.'_standalone'][$index];
}
}
}
}
$$translationKey = array_merge(
$mode & CarbonInterface::TRANSLATE_MONTHS ? static::getTranslationArray($months, static::MONTHS_PER_YEAR, $timeString) : [],
$mode & CarbonInterface::TRANSLATE_MONTHS ? static::getTranslationArray($messages['months_short'] ?? [], static::MONTHS_PER_YEAR, $timeString) : [],
$mode & CarbonInterface::TRANSLATE_DAYS ? static::getTranslationArray($weekdays, static::DAYS_PER_WEEK, $timeString) : [],
$mode & CarbonInterface::TRANSLATE_DAYS ? static::getTranslationArray($messages['weekdays_short'] ?? [], static::DAYS_PER_WEEK, $timeString) : [],
$mode & CarbonInterface::TRANSLATE_DIFF ? static::translateWordsByKeys([
'diff_now',
'diff_today',
'diff_yesterday',
'diff_tomorrow',
'diff_before_yesterday',
'diff_after_tomorrow',
], $messages, $key) : [],
$mode & CarbonInterface::TRANSLATE_UNITS ? static::translateWordsByKeys([
'year',
'month',
'week',
'day',
'hour',
'minute',
'second',
], $messages, $key) : [],
$mode & CarbonInterface::TRANSLATE_MERIDIEM ? array_map(function ($hour) use ($meridiem) {
if (\is_array($meridiem)) {
return $meridiem[$hour < static::HOURS_PER_DAY / 2 ? 0 : 1];
}
return $meridiem($hour, 0, false);
}, range(0, 23)) : [],
);
}
return substr(preg_replace_callback('/(?<=[\d\s+.\/,_-])('.implode('|', $fromTranslations).')(?=[\d\s+.\/,_-])/iu', function ($match) use ($fromTranslations, $toTranslations) {
[$chunk] = $match;
foreach ($fromTranslations as $index => $word) {
if (preg_match("/^$word\$/iu", $chunk)) {
return $toTranslations[$index] ?? '';
}
}
return $chunk; // @codeCoverageIgnore
}, " $timeString "), 1, -1);
}
/**
* Translate a time string from the current locale (`$date->locale()`) to an other.
*
* @param string $timeString time string to translate
* @param string|null $to output locale of the result returned ("en" by default)
*
* @return string
*/
public function translateTimeStringTo(string $timeString, ?string $to = null): string
{
return static::translateTimeString($timeString, $this->getTranslatorLocale(), $to);
}
/**
* Get/set the locale for the current instance.
*
* @param string|null $locale
* @param string ...$fallbackLocales
*
* @return $this|string
*/
public function locale(?string $locale = null, string ...$fallbackLocales): static|string
{
if ($locale === null) {
return $this->getTranslatorLocale();
}
if (!$this->localTranslator || $this->getTranslatorLocale($this->localTranslator) !== $locale) {
$translator = Translator::get($locale);
if (!empty($fallbackLocales)) {
$translator->setFallbackLocales($fallbackLocales);
foreach ($fallbackLocales as $fallbackLocale) {
$messages = Translator::get($fallbackLocale)->getMessages();
if (isset($messages[$fallbackLocale])) {
$translator->setMessages($fallbackLocale, $messages[$fallbackLocale]);
}
}
}
$this->localTranslator = $translator;
}
return $this;
}
/**
* Get the current translator locale.
*
* @return string
*/
public static function getLocale(): string
{
return static::getLocaleAwareTranslator()->getLocale();
}
/**
* Set the current translator locale and indicate if the source locale file exists.
* Pass 'auto' as locale to use the closest language to the current LC_TIME locale.
*
* @param string $locale locale ex. en
*/
public static function setLocale(string $locale): void
{
static::getLocaleAwareTranslator()->setLocale($locale);
}
/**
* Set the fallback locale.
*
* @see https://symfony.com/doc/current/components/translation.html#fallback-locales
*
* @param string $locale
*/
public static function setFallbackLocale(string $locale): void
{
$translator = static::getTranslator();
if (method_exists($translator, 'setFallbackLocales')) {
$translator->setFallbackLocales([$locale]);
if ($translator instanceof Translator) {
$preferredLocale = $translator->getLocale();
$translator->setMessages($preferredLocale, array_replace_recursive(
$translator->getMessages()[$locale] ?? [],
Translator::get($locale)->getMessages()[$locale] ?? [],
$translator->getMessages($preferredLocale),
));
}
}
}
/**
* Get the fallback locale.
*
* @see https://symfony.com/doc/current/components/translation.html#fallback-locales
*/
public static function getFallbackLocale(): ?string
{
$translator = static::getTranslator();
if (method_exists($translator, 'getFallbackLocales')) {
return $translator->getFallbackLocales()[0] ?? null;
}
return null;
}
/**
* Set the current locale to the given, execute the passed function, reset the locale to previous one,
* then return the result of the closure (or null if the closure was void).
*
* @param string $locale locale ex. en
* @param callable $func
*
* @return mixed
*/
public static function executeWithLocale(string $locale, callable $func): mixed
{
$currentLocale = static::getLocale();
static::setLocale($locale);
$newLocale = static::getLocale();
$result = $func(
$newLocale === 'en' && strtolower(substr((string) $locale, 0, 2)) !== 'en'
? false
: $newLocale,
static::getTranslator(),
);
static::setLocale($currentLocale);
return $result;
}
/**
* Returns true if the given locale is internally supported and has short-units support.
* Support is considered enabled if either year, day or hour has a short variant translated.
*
* @param string $locale locale ex. en
*
* @return bool
*/
public static function localeHasShortUnits(string $locale): bool
{
return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) {
return ($newLocale && (($y = static::translateWith($translator, 'y')) !== 'y' && $y !== static::translateWith($translator, 'year'))) || (
($y = static::translateWith($translator, 'd')) !== 'd' &&
$y !== static::translateWith($translator, 'day')
) || (
($y = static::translateWith($translator, 'h')) !== 'h' &&
$y !== static::translateWith($translator, 'hour')
);
});
}
/**
* Returns true if the given locale is internally supported and has diff syntax support (ago, from now, before, after).
* Support is considered enabled if the 4 sentences are translated in the given locale.
*
* @param string $locale locale ex. en
*
* @return bool
*/
public static function localeHasDiffSyntax(string $locale): bool
{
return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) {
if (!$newLocale) {
return false;
}
foreach (['ago', 'from_now', 'before', 'after'] as $key) {
if ($translator instanceof TranslatorBagInterface &&
self::getFromCatalogue($translator, $translator->getCatalogue($newLocale), $key) instanceof Closure
) {
continue;
}
if ($translator->trans($key) === $key) {
return false;
}
}
return true;
});
}
/**
* Returns true if the given locale is internally supported and has words for 1-day diff (just now, yesterday, tomorrow).
* Support is considered enabled if the 3 words are translated in the given locale.
*
* @param string $locale locale ex. en
*
* @return bool
*/
public static function localeHasDiffOneDayWords(string $locale): bool
{
return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) {
return $newLocale &&
$translator->trans('diff_now') !== 'diff_now' &&
$translator->trans('diff_yesterday') !== 'diff_yesterday' &&
$translator->trans('diff_tomorrow') !== 'diff_tomorrow';
});
}
/**
* Returns true if the given locale is internally supported and has words for 2-days diff (before yesterday, after tomorrow).
* Support is considered enabled if the 2 words are translated in the given locale.
*
* @param string $locale locale ex. en
*
* @return bool
*/
public static function localeHasDiffTwoDayWords(string $locale): bool
{
return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) {
return $newLocale &&
$translator->trans('diff_before_yesterday') !== 'diff_before_yesterday' &&
$translator->trans('diff_after_tomorrow') !== 'diff_after_tomorrow';
});
}
/**
* Returns true if the given locale is internally supported and has period syntax support (X times, every X, from X, to X).
* Support is considered enabled if the 4 sentences are translated in the given locale.
*
* @param string $locale locale ex. en
*
* @return bool
*/
public static function localeHasPeriodSyntax($locale)
{
return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) {
return $newLocale &&
$translator->trans('period_recurrences') !== 'period_recurrences' &&
$translator->trans('period_interval') !== 'period_interval' &&
$translator->trans('period_start_date') !== 'period_start_date' &&
$translator->trans('period_end_date') !== 'period_end_date';
});
}
/**
* Returns the list of internally available locales and already loaded custom locales.
* (It will ignore custom translator dynamic loading.)
*
* @return array
*/
public static function getAvailableLocales()
{
$translator = static::getLocaleAwareTranslator();
return $translator instanceof Translator
? $translator->getAvailableLocales()
: [$translator->getLocale()];
}
/**
* Returns list of Language object for each available locale. This object allow you to get the ISO name, native
* name, region and variant of the locale.
*
* @return Language[]
*/
public static function getAvailableLocalesInfo()
{
$languages = [];
foreach (static::getAvailableLocales() as $id) {
$languages[$id] = new Language($id);
}
return $languages;
}
/**
* Get the locale of a given translator.
*
* If null or omitted, current local translator is used.
* If no local translator is in use, current global translator is used.
*/
protected function getTranslatorLocale($translator = null): ?string
{
if (\func_num_args() === 0) {
$translator = $this->getLocalTranslator();
}
$translator = static::getLocaleAwareTranslator($translator);
return $translator?->getLocale();
}
/**
* Throw an error if passed object is not LocaleAwareInterface.
*
* @param LocaleAwareInterface|null $translator
*
* @return LocaleAwareInterface|null
*/
protected static function getLocaleAwareTranslator($translator = null)
{
if (\func_num_args() === 0) {
$translator = static::getTranslator();
}
if ($translator && !($translator instanceof LocaleAwareInterface || method_exists($translator, 'getLocale'))) {
throw new NotLocaleAwareException($translator); // @codeCoverageIgnore
}
return $translator;
}
/**
* @param mixed $translator
* @param \Symfony\Component\Translation\MessageCatalogueInterface $catalogue
*
* @return mixed
*/
private static function getFromCatalogue($translator, $catalogue, string $id, string $domain = 'messages')
{
return $translator instanceof TranslatorStrongTypeInterface
? $translator->getFromCatalogue($catalogue, $id, $domain)
: $catalogue->get($id, $domain); // @codeCoverageIgnore
}
/**
* Return the word cleaned from its translation codes.
*
* @param string $word
*
* @return string
*/
private static function cleanWordFromTranslationString($word)
{
$word = str_replace([':count', '%count', ':time'], '', $word);
$word = strtr($word, ['' => "'"]);
$word = preg_replace('/({\d+(,(\d+|Inf))?}|[\[\]]\d+(,(\d+|Inf))?[\[\]])/', '', $word);
return trim($word);
}
/**
* Translate a list of words.
*
* @param string[] $keys keys to translate.
* @param string[] $messages messages bag handling translations.
* @param string $key 'to' (to get the translation) or 'from' (to get the detection RegExp pattern).
*
* @return string[]
*/
private static function translateWordsByKeys($keys, $messages, $key): array
{
return array_map(function ($wordKey) use ($messages, $key) {
$message = $key === 'from' && isset($messages[$wordKey.'_regexp'])
? $messages[$wordKey.'_regexp']
: ($messages[$wordKey] ?? null);
if (!$message) {
return '>>DO NOT REPLACE<<';
}
$parts = explode('|', $message);
return $key === 'to'
? self::cleanWordFromTranslationString(end($parts))
: '(?:'.implode('|', array_map([static::class, 'cleanWordFromTranslationString'], $parts)).')';
}, $keys);
}
/**
* Get an array of translations based on the current date.
*
* @param callable $translation
* @param int $length
* @param string $timeString
*
* @return string[]
*/
private static function getTranslationArray($translation, $length, $timeString): array
{
$filler = '>>DO NOT REPLACE<<';
if (\is_array($translation)) {
return array_pad($translation, $length, $filler);
}
$list = [];
$date = static::now();
for ($i = 0; $i < $length; $i++) {
$list[] = $translation($date, $timeString, $i) ?? $filler;
}
return $list;
}
private static function replaceOrdinalWords(string $timeString, array $ordinalWords): string
{
return preg_replace_callback('/(?<![a-z])[a-z]+(?![a-z])/i', function (array $match) use ($ordinalWords) {
return $ordinalWords[mb_strtolower($match[0])] ?? $match[0];
}, $timeString);
}
}

View File

@@ -0,0 +1,109 @@
<?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Carbon\Traits;
use Carbon\FactoryImmutable;
/**
* Trait Macros.
*
* Allows users to register macros within the Carbon class.
*/
trait Macro
{
use Mixin;
/**
* Register a custom macro.
*
* Pass null macro to remove it.
*
* @example
* ```
* $userSettings = [
* 'locale' => 'pt',
* 'timezone' => 'America/Sao_Paulo',
* ];
* Carbon::macro('userFormat', function () use ($userSettings) {
* return $this->copy()->locale($userSettings['locale'])->tz($userSettings['timezone'])->calendar();
* });
* echo Carbon::yesterday()->hours(11)->userFormat();
* ```
*/
public static function macro(string $name, ?callable $macro): void
{
FactoryImmutable::getDefaultInstance()->macro($name, $macro);
}
/**
* Remove all macros and generic macros.
*/
public static function resetMacros(): void
{
FactoryImmutable::getDefaultInstance()->resetMacros();
}
/**
* Register a custom macro.
*
* @param callable $macro
* @param int $priority marco with higher priority is tried first
*
* @return void
*/
public static function genericMacro(callable $macro, int $priority = 0): void
{
FactoryImmutable::getDefaultInstance()->genericMacro($macro, $priority);
}
/**
* Checks if macro is registered globally.
*
* @param string $name
*
* @return bool
*/
public static function hasMacro(string $name): bool
{
return FactoryImmutable::getInstance()->hasMacro($name);
}
/**
* Get the raw callable macro registered globally for a given name.
*/
public static function getMacro(string $name): ?callable
{
return FactoryImmutable::getInstance()->getMacro($name);
}
/**
* Checks if macro is registered globally or locally.
*/
public function hasLocalMacro(string $name): bool
{
return ($this->localMacros && isset($this->localMacros[$name])) || $this->transmitFactory(
static fn () => static::hasMacro($name),
);
}
/**
* Get the raw callable macro registered globally or locally for a given name.
*/
public function getLocalMacro(string $name): ?callable
{
return ($this->localMacros ?? [])[$name] ?? $this->transmitFactory(
static fn () => static::getMacro($name),
);
}
}

View File

@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Carbon\Traits;
/**
* Trait MagicParameter.
*
* Allows to retrieve parameter in magic calls by index or name.
*/
trait MagicParameter
{
private function getMagicParameter(array $parameters, int $index, string $key, $default)
{
if (\array_key_exists($index, $parameters)) {
return $parameters[$index];
}
if (\array_key_exists($key, $parameters)) {
return $parameters[$key];
}
return $default;
}
}

View File

@@ -0,0 +1,208 @@
<?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Carbon\Traits;
use Carbon\CarbonInterface;
use Carbon\CarbonInterval;
use Carbon\CarbonPeriod;
use Closure;
use Generator;
use ReflectionClass;
use ReflectionException;
use ReflectionMethod;
use Throwable;
/**
* Trait Mixin.
*
* Allows mixing in entire classes with multiple macros.
*/
trait Mixin
{
/**
* Stack of macro instance contexts.
*/
protected static array $macroContextStack = [];
/**
* Mix another object into the class.
*
* @example
* ```
* Carbon::mixin(new class {
* public function addMoon() {
* return function () {
* return $this->addDays(30);
* };
* }
* public function subMoon() {
* return function () {
* return $this->subDays(30);
* };
* }
* });
* $fullMoon = Carbon::create('2018-12-22');
* $nextFullMoon = $fullMoon->addMoon();
* $blackMoon = Carbon::create('2019-01-06');
* $previousBlackMoon = $blackMoon->subMoon();
* echo "$nextFullMoon\n";
* echo "$previousBlackMoon\n";
* ```
*
* @throws ReflectionException
*/
public static function mixin(object|string $mixin): void
{
\is_string($mixin) && trait_exists($mixin)
? self::loadMixinTrait($mixin)
: self::loadMixinClass($mixin);
}
/**
* @throws ReflectionException
*/
private static function loadMixinClass(object|string $mixin): void
{
$methods = (new ReflectionClass($mixin))->getMethods(
ReflectionMethod::IS_PUBLIC | ReflectionMethod::IS_PROTECTED,
);
foreach ($methods as $method) {
if ($method->isConstructor() || $method->isDestructor()) {
continue;
}
$macro = $method->invoke($mixin);
if (\is_callable($macro)) {
static::macro($method->name, $macro);
}
}
}
private static function loadMixinTrait(string $trait): void
{
$context = eval(self::getAnonymousClassCodeForTrait($trait));
$className = \get_class($context);
$baseClass = static::class;
foreach (self::getMixableMethods($context) as $name) {
$closureBase = Closure::fromCallable([$context, $name]);
static::macro($name, function (...$parameters) use ($closureBase, $className, $baseClass) {
$downContext = isset($this) ? ($this) : new $baseClass();
$context = isset($this) ? $this->cast($className) : new $className();
try {
// @ is required to handle error if not converted into exceptions
$closure = @$closureBase->bindTo($context);
} catch (Throwable) { // @codeCoverageIgnore
$closure = $closureBase; // @codeCoverageIgnore
}
// in case of errors not converted into exceptions
$closure = $closure ?: $closureBase;
$result = $closure(...$parameters);
if (!($result instanceof $className)) {
return $result;
}
if ($downContext instanceof CarbonInterface && $result instanceof CarbonInterface) {
if ($context !== $result) {
$downContext = $downContext->copy();
}
return $downContext
->setTimezone($result->getTimezone())
->modify($result->format('Y-m-d H:i:s.u'))
->settings($result->getSettings());
}
if ($downContext instanceof CarbonInterval && $result instanceof CarbonInterval) {
if ($context !== $result) {
$downContext = $downContext->copy();
}
$downContext->copyProperties($result);
self::copyStep($downContext, $result);
self::copyNegativeUnits($downContext, $result);
return $downContext->settings($result->getSettings());
}
if ($downContext instanceof CarbonPeriod && $result instanceof CarbonPeriod) {
if ($context !== $result) {
$downContext = $downContext->copy();
}
return $downContext
->setDates($result->getStartDate(), $result->getEndDate())
->setRecurrences($result->getRecurrences())
->setOptions($result->getOptions())
->settings($result->getSettings());
}
return $result;
});
}
}
private static function getAnonymousClassCodeForTrait(string $trait): string
{
return 'return new class() extends '.static::class.' {use '.$trait.';};';
}
private static function getMixableMethods(self $context): Generator
{
foreach (get_class_methods($context) as $name) {
if (method_exists(static::class, $name)) {
continue;
}
yield $name;
}
}
/**
* Stack a Carbon context from inside calls of self::this() and execute a given action.
*/
protected static function bindMacroContext(?self $context, callable $callable): mixed
{
static::$macroContextStack[] = $context;
try {
return $callable();
} finally {
array_pop(static::$macroContextStack);
}
}
/**
* Return the current context from inside a macro callee or a null if static.
*/
protected static function context(): ?static
{
return end(static::$macroContextStack) ?: null;
}
/**
* Return the current context from inside a macro callee or a new one if static.
*/
protected static function this(): static
{
return end(static::$macroContextStack) ?: new static();
}
}

View File

@@ -0,0 +1,476 @@
<?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Carbon\Traits;
use Carbon\CarbonInterface;
use Carbon\Exceptions\InvalidFormatException;
use ReturnTypeWillChange;
/**
* Trait Modifiers.
*
* Returns dates relative to current date using modifier short-hand.
*/
trait Modifiers
{
/**
* Midday/noon hour.
*
* @var int
*/
protected static $midDayAt = 12;
/**
* get midday/noon hour
*
* @return int
*/
public static function getMidDayAt()
{
return static::$midDayAt;
}
/**
* @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
* You should rather consider mid-day is always 12pm, then if you need to test if it's an other
* hour, test it explicitly:
* $date->format('G') == 13
* or to set explicitly to a given hour:
* $date->setTime(13, 0, 0, 0)
*
* Set midday/noon hour
*
* @param int $hour midday hour
*
* @return void
*/
public static function setMidDayAt($hour)
{
static::$midDayAt = $hour;
}
/**
* Modify to midday, default to self::$midDayAt
*
* @return static
*/
public function midDay()
{
return $this->setTime(static::$midDayAt, 0, 0, 0);
}
/**
* Modify to the next occurrence of a given modifier such as a day of
* the week. If no modifier is provided, modify to the next occurrence
* of the current day of the week. Use the supplied constants
* to indicate the desired dayOfWeek, ex. static::MONDAY.
*
* @param string|int|null $modifier
*
* @return static
*/
public function next($modifier = null)
{
if ($modifier === null) {
$modifier = $this->dayOfWeek;
}
return $this->change(
'next '.(\is_string($modifier) ? $modifier : static::$days[$modifier]),
);
}
/**
* Go forward or backward to the next week- or weekend-day.
*
* @param bool $weekday
* @param bool $forward
*
* @return static
*/
private function nextOrPreviousDay($weekday = true, $forward = true)
{
/** @var CarbonInterface $date */
$date = $this;
$step = $forward ? 1 : -1;
do {
$date = $date->addDays($step);
} while ($weekday ? $date->isWeekend() : $date->isWeekday());
return $date;
}
/**
* Go forward to the next weekday.
*
* @return static
*/
public function nextWeekday()
{
return $this->nextOrPreviousDay();
}
/**
* Go backward to the previous weekday.
*
* @return static
*/
public function previousWeekday()
{
return $this->nextOrPreviousDay(true, false);
}
/**
* Go forward to the next weekend day.
*
* @return static
*/
public function nextWeekendDay()
{
return $this->nextOrPreviousDay(false);
}
/**
* Go backward to the previous weekend day.
*
* @return static
*/
public function previousWeekendDay()
{
return $this->nextOrPreviousDay(false, false);
}
/**
* Modify to the previous occurrence of a given modifier such as a day of
* the week. If no dayOfWeek is provided, modify to the previous occurrence
* of the current day of the week. Use the supplied constants
* to indicate the desired dayOfWeek, ex. static::MONDAY.
*
* @param string|int|null $modifier
*
* @return static
*/
public function previous($modifier = null)
{
if ($modifier === null) {
$modifier = $this->dayOfWeek;
}
return $this->change(
'last '.(\is_string($modifier) ? $modifier : static::$days[$modifier]),
);
}
/**
* Modify to the first occurrence of a given day of the week
* in the current month. If no dayOfWeek is provided, modify to the
* first day of the current month. Use the supplied constants
* to indicate the desired dayOfWeek, ex. static::MONDAY.
*
* @param int|null $dayOfWeek
*
* @return static
*/
public function firstOfMonth($dayOfWeek = null)
{
$date = $this->startOfDay();
if ($dayOfWeek === null) {
return $date->day(1);
}
return $date->modify('first '.static::$days[$dayOfWeek].' of '.$date->rawFormat('F').' '.$date->year);
}
/**
* Modify to the last occurrence of a given day of the week
* in the current month. If no dayOfWeek is provided, modify to the
* last day of the current month. Use the supplied constants
* to indicate the desired dayOfWeek, ex. static::MONDAY.
*
* @param int|null $dayOfWeek
*
* @return static
*/
public function lastOfMonth($dayOfWeek = null)
{
$date = $this->startOfDay();
if ($dayOfWeek === null) {
return $date->day($date->daysInMonth);
}
return $date->modify('last '.static::$days[$dayOfWeek].' of '.$date->rawFormat('F').' '.$date->year);
}
/**
* Modify to the given occurrence of a given day of the week
* in the current month. If the calculated occurrence is outside the scope
* of the current month, then return false and no modifications are made.
* Use the supplied constants to indicate the desired dayOfWeek, ex. static::MONDAY.
*
* @param int $nth
* @param int $dayOfWeek
*
* @return mixed
*/
public function nthOfMonth($nth, $dayOfWeek)
{
$date = $this->avoidMutation()->firstOfMonth();
$check = $date->rawFormat('Y-m');
$date = $date->modify('+'.$nth.' '.static::$days[$dayOfWeek]);
return $date->rawFormat('Y-m') === $check ? $this->modify((string) $date) : false;
}
/**
* Modify to the first occurrence of a given day of the week
* in the current quarter. If no dayOfWeek is provided, modify to the
* first day of the current quarter. Use the supplied constants
* to indicate the desired dayOfWeek, ex. static::MONDAY.
*
* @param int|null $dayOfWeek day of the week default null
*
* @return static
*/
public function firstOfQuarter($dayOfWeek = null)
{
return $this->setDate($this->year, $this->quarter * static::MONTHS_PER_QUARTER - 2, 1)->firstOfMonth($dayOfWeek);
}
/**
* Modify to the last occurrence of a given day of the week
* in the current quarter. If no dayOfWeek is provided, modify to the
* last day of the current quarter. Use the supplied constants
* to indicate the desired dayOfWeek, ex. static::MONDAY.
*
* @param int|null $dayOfWeek day of the week default null
*
* @return static
*/
public function lastOfQuarter($dayOfWeek = null)
{
return $this->setDate($this->year, $this->quarter * static::MONTHS_PER_QUARTER, 1)->lastOfMonth($dayOfWeek);
}
/**
* Modify to the given occurrence of a given day of the week
* in the current quarter. If the calculated occurrence is outside the scope
* of the current quarter, then return false and no modifications are made.
* Use the supplied constants to indicate the desired dayOfWeek, ex. static::MONDAY.
*
* @param int $nth
* @param int $dayOfWeek
*
* @return mixed
*/
public function nthOfQuarter($nth, $dayOfWeek)
{
$date = $this->avoidMutation()->day(1)->month($this->quarter * static::MONTHS_PER_QUARTER);
$lastMonth = $date->month;
$year = $date->year;
$date = $date->firstOfQuarter()->modify('+'.$nth.' '.static::$days[$dayOfWeek]);
return ($lastMonth < $date->month || $year !== $date->year) ? false : $this->modify((string) $date);
}
/**
* Modify to the first occurrence of a given day of the week
* in the current year. If no dayOfWeek is provided, modify to the
* first day of the current year. Use the supplied constants
* to indicate the desired dayOfWeek, ex. static::MONDAY.
*
* @param int|null $dayOfWeek day of the week default null
*
* @return static
*/
public function firstOfYear($dayOfWeek = null)
{
return $this->month(1)->firstOfMonth($dayOfWeek);
}
/**
* Modify to the last occurrence of a given day of the week
* in the current year. If no dayOfWeek is provided, modify to the
* last day of the current year. Use the supplied constants
* to indicate the desired dayOfWeek, ex. static::MONDAY.
*
* @param int|null $dayOfWeek day of the week default null
*
* @return static
*/
public function lastOfYear($dayOfWeek = null)
{
return $this->month(static::MONTHS_PER_YEAR)->lastOfMonth($dayOfWeek);
}
/**
* Modify to the given occurrence of a given day of the week
* in the current year. If the calculated occurrence is outside the scope
* of the current year, then return false and no modifications are made.
* Use the supplied constants to indicate the desired dayOfWeek, ex. static::MONDAY.
*
* @param int $nth
* @param int $dayOfWeek
*
* @return mixed
*/
public function nthOfYear($nth, $dayOfWeek)
{
$date = $this->avoidMutation()->firstOfYear()->modify('+'.$nth.' '.static::$days[$dayOfWeek]);
return $this->year === $date->year ? $this->modify((string) $date) : false;
}
/**
* Modify the current instance to the average of a given instance (default now) and the current instance
* (second-precision).
*
* @param \Carbon\Carbon|\DateTimeInterface|null $date
*
* @return static
*/
public function average($date = null)
{
return $this->addRealMicroseconds((int) ($this->diffInMicroseconds($this->resolveCarbon($date), false) / 2));
}
/**
* Get the closest date from the instance (second-precision).
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date1
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date2
*
* @return static
*/
public function closest($date1, $date2)
{
return $this->diffInMicroseconds($date1, true) < $this->diffInMicroseconds($date2, true) ? $date1 : $date2;
}
/**
* Get the farthest date from the instance (second-precision).
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date1
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date2
*
* @return static
*/
public function farthest($date1, $date2)
{
return $this->diffInMicroseconds($date1, true) > $this->diffInMicroseconds($date2, true) ? $date1 : $date2;
}
/**
* Get the minimum instance between a given instance (default now) and the current instance.
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date
*
* @return static
*/
public function min($date = null)
{
$date = $this->resolveCarbon($date);
return $this->lt($date) ? $this : $date;
}
/**
* Get the minimum instance between a given instance (default now) and the current instance.
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date
*
* @see min()
*
* @return static
*/
public function minimum($date = null)
{
return $this->min($date);
}
/**
* Get the maximum instance between a given instance (default now) and the current instance.
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date
*
* @return static
*/
public function max($date = null)
{
$date = $this->resolveCarbon($date);
return $this->gt($date) ? $this : $date;
}
/**
* Get the maximum instance between a given instance (default now) and the current instance.
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date
*
* @see max()
*
* @return static
*/
public function maximum($date = null)
{
return $this->max($date);
}
/**
* Calls \DateTime::modify if mutable or \DateTimeImmutable::modify else.
*
* @see https://php.net/manual/en/datetime.modify.php
*
* @return static
*/
#[ReturnTypeWillChange]
public function modify($modify)
{
return parent::modify((string) $modify)
?: throw new InvalidFormatException('Could not modify with: '.var_export($modify, true));
}
/**
* Similar to native modify() method of DateTime but can handle more grammars.
*
* @example
* ```
* echo Carbon::now()->change('next 2pm');
* ```
*
* @link https://php.net/manual/en/datetime.modify.php
*
* @param string $modifier
*
* @return static
*/
public function change($modifier)
{
return $this->modify(preg_replace_callback('/^(next|previous|last)\s+(\d{1,2}(h|am|pm|:\d{1,2}(:\d{1,2})?))$/i', function ($match) {
$match[2] = str_replace('h', ':00', $match[2]);
$test = $this->avoidMutation()->modify($match[2]);
$method = $match[1] === 'next' ? 'lt' : 'gt';
$match[1] = $test->$method($this) ? $match[1].' day' : 'today';
return $match[1].' '.$match[2];
}, strtr(trim($modifier), [
' at ' => ' ',
'just now' => 'now',
'after tomorrow' => 'tomorrow +1 day',
'before yesterday' => 'yesterday -1 day',
])));
}
}

View File

@@ -0,0 +1,69 @@
<?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Carbon\Traits;
use Carbon\Carbon;
use Carbon\CarbonImmutable;
/**
* Trait Mutability.
*
* Utils to know if the current object is mutable or immutable and convert it.
*/
trait Mutability
{
use Cast;
/**
* Returns true if the current class/instance is mutable.
*/
public static function isMutable(): bool
{
return false;
}
/**
* Returns true if the current class/instance is immutable.
*/
public static function isImmutable(): bool
{
return !static::isMutable();
}
/**
* Return a mutable copy of the instance.
*
* @return Carbon
*/
public function toMutable()
{
/** @var Carbon $date */
$date = $this->cast(Carbon::class);
return $date;
}
/**
* Return a immutable copy of the instance.
*
* @return CarbonImmutable
*/
public function toImmutable()
{
/** @var CarbonImmutable $date */
$date = $this->cast(CarbonImmutable::class);
return $date;
}
}

View File

@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Carbon\Traits;
trait ObjectInitialisation
{
/**
* True when parent::__construct has been called.
*
* @var string
*/
protected $constructedObjectId;
}

View File

@@ -0,0 +1,213 @@
<?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Carbon\Traits;
use Carbon\CarbonInterface;
use DateTimeInterface;
use Throwable;
/**
* Trait Options.
*
* Embed base methods to change settings of Carbon classes.
*
* Depends on the following methods:
*
* @method static shiftTimezone($timezone) Set the timezone
*/
trait Options
{
use StaticOptions;
use Localization;
/**
* Indicates if months should be calculated with overflow.
* Specific setting.
*/
protected ?bool $localMonthsOverflow = null;
/**
* Indicates if years should be calculated with overflow.
* Specific setting.
*/
protected ?bool $localYearsOverflow = null;
/**
* Indicates if the strict mode is in use.
* Specific setting.
*/
protected ?bool $localStrictModeEnabled = null;
/**
* Options for diffForHumans and forHumans methods.
*/
protected ?int $localHumanDiffOptions = null;
/**
* Format to use on string cast.
*
* @var string|callable|null
*/
protected $localToStringFormat = null;
/**
* Format to use on JSON serialization.
*
* @var string|callable|null
*/
protected $localSerializer = null;
/**
* Instance-specific macros.
*/
protected ?array $localMacros = null;
/**
* Instance-specific generic macros.
*/
protected ?array $localGenericMacros = null;
/**
* Function to call instead of format.
*
* @var string|callable|null
*/
protected $localFormatFunction = null;
/**
* Set specific options.
* - strictMode: true|false|null
* - monthOverflow: true|false|null
* - yearOverflow: true|false|null
* - humanDiffOptions: int|null
* - toStringFormat: string|Closure|null
* - toJsonFormat: string|Closure|null
* - locale: string|null
* - timezone: \DateTimeZone|string|int|null
* - macros: array|null
* - genericMacros: array|null
*
* @param array $settings
*
* @return $this|static
*/
public function settings(array $settings): static
{
$this->localStrictModeEnabled = $settings['strictMode'] ?? null;
$this->localMonthsOverflow = $settings['monthOverflow'] ?? null;
$this->localYearsOverflow = $settings['yearOverflow'] ?? null;
$this->localHumanDiffOptions = $settings['humanDiffOptions'] ?? null;
$this->localToStringFormat = $settings['toStringFormat'] ?? null;
$this->localSerializer = $settings['toJsonFormat'] ?? null;
$this->localMacros = $settings['macros'] ?? null;
$this->localGenericMacros = $settings['genericMacros'] ?? null;
$this->localFormatFunction = $settings['formatFunction'] ?? null;
if (isset($settings['locale'])) {
$locales = $settings['locale'];
if (!\is_array($locales)) {
$locales = [$locales];
}
$this->locale(...$locales);
} elseif (isset($settings['translator']) && property_exists($this, 'localTranslator')) {
$this->localTranslator = $settings['translator'];
}
if (isset($settings['innerTimezone'])) {
return $this->setTimezone($settings['innerTimezone']);
}
if (isset($settings['timezone'])) {
return $this->shiftTimezone($settings['timezone']);
}
return $this;
}
/**
* Returns current local settings.
*/
public function getSettings(): array
{
$settings = [];
$map = [
'localStrictModeEnabled' => 'strictMode',
'localMonthsOverflow' => 'monthOverflow',
'localYearsOverflow' => 'yearOverflow',
'localHumanDiffOptions' => 'humanDiffOptions',
'localToStringFormat' => 'toStringFormat',
'localSerializer' => 'toJsonFormat',
'localMacros' => 'macros',
'localGenericMacros' => 'genericMacros',
'locale' => 'locale',
'tzName' => 'timezone',
'localFormatFunction' => 'formatFunction',
];
foreach ($map as $property => $key) {
$value = $this->$property ?? null;
if ($value !== null && ($key !== 'locale' || $value !== 'en' || $this->localTranslator)) {
$settings[$key] = $value;
}
}
return $settings;
}
/**
* Show truthy properties on var_dump().
*/
public function __debugInfo(): array
{
$infos = array_filter(get_object_vars($this), static function ($var) {
return $var;
});
foreach (['dumpProperties', 'constructedObjectId', 'constructed', 'originalInput'] as $property) {
if (isset($infos[$property])) {
unset($infos[$property]);
}
}
$this->addExtraDebugInfos($infos);
if (\array_key_exists('carbonRecurrences', $infos)) {
$infos['recurrences'] = $infos['carbonRecurrences'];
unset($infos['carbonRecurrences']);
}
return $infos;
}
protected function isLocalStrictModeEnabled(): bool
{
return $this->localStrictModeEnabled
?? $this->transmitFactory(static fn () => static::isStrictModeEnabled());
}
protected function addExtraDebugInfos(array &$infos): void
{
if ($this instanceof DateTimeInterface) {
try {
$infos['date'] ??= $this->format(CarbonInterface::MOCK_DATETIME_FORMAT);
$infos['timezone'] ??= $this->tzName ?? $this->timezoneSetting ?? $this->timezone ?? null;
} catch (Throwable) {
// noop
}
}
}
}

View File

@@ -0,0 +1,226 @@
<?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Carbon\Traits;
use Carbon\CarbonInterface;
use Carbon\Exceptions\UnknownUnitException;
use Carbon\WeekDay;
use DateInterval;
/**
* Trait Rounding.
*
* Round, ceil, floor units.
*
* Depends on the following methods:
*
* @method CarbonInterface copy()
* @method CarbonInterface startOfWeek(int $weekStartsAt = null)
*/
trait Rounding
{
use IntervalRounding;
/**
* Round the current instance at the given unit with given precision if specified and the given function.
*/
public function roundUnit(
string $unit,
DateInterval|string|float|int $precision = 1,
callable|string $function = 'round',
): static {
$metaUnits = [
// @call roundUnit
'millennium' => [static::YEARS_PER_MILLENNIUM, 'year'],
// @call roundUnit
'century' => [static::YEARS_PER_CENTURY, 'year'],
// @call roundUnit
'decade' => [static::YEARS_PER_DECADE, 'year'],
// @call roundUnit
'quarter' => [static::MONTHS_PER_QUARTER, 'month'],
// @call roundUnit
'millisecond' => [1000, 'microsecond'],
];
$normalizedUnit = static::singularUnit($unit);
$ranges = array_merge(static::getRangesByUnit($this->daysInMonth), [
// @call roundUnit
'microsecond' => [0, 999999],
]);
$factor = 1;
if ($normalizedUnit === 'week') {
$normalizedUnit = 'day';
$precision *= static::DAYS_PER_WEEK;
}
if (isset($metaUnits[$normalizedUnit])) {
[$factor, $normalizedUnit] = $metaUnits[$normalizedUnit];
}
$precision *= $factor;
if (!isset($ranges[$normalizedUnit])) {
throw new UnknownUnitException($unit);
}
$found = false;
$fraction = 0;
$arguments = null;
$initialValue = null;
$factor = $this->year < 0 ? -1 : 1;
$changes = [];
$minimumInc = null;
foreach ($ranges as $unit => [$minimum, $maximum]) {
if ($normalizedUnit === $unit) {
$arguments = [$this->$unit, $minimum];
$initialValue = $this->$unit;
$fraction = $precision - floor($precision);
$found = true;
continue;
}
if ($found) {
$delta = $maximum + 1 - $minimum;
$factor /= $delta;
$fraction *= $delta;
$inc = ($this->$unit - $minimum) * $factor;
if ($inc !== 0.0) {
$minimumInc = $minimumInc ?? ($arguments[0] / pow(2, 52));
// If value is still the same when adding a non-zero increment/decrement,
// it means precision got lost in the addition
if (abs($inc) < $minimumInc) {
$inc = $minimumInc * ($inc < 0 ? -1 : 1);
}
// If greater than $precision, assume precision loss caused an overflow
if ($function !== 'floor' || abs($arguments[0] + $inc - $initialValue) >= $precision) {
$arguments[0] += $inc;
}
}
$changes[$unit] = round(
$minimum + ($fraction ? $fraction * $function(($this->$unit - $minimum) / $fraction) : 0),
);
// Cannot use modulo as it lose double precision
while ($changes[$unit] >= $delta) {
$changes[$unit] -= $delta;
}
$fraction -= floor($fraction);
}
}
[$value, $minimum] = $arguments;
$normalizedValue = floor($function(($value - $minimum) / $precision) * $precision + $minimum);
/** @var CarbonInterface $result */
$result = $this;
foreach ($changes as $unit => $value) {
$result = $result->$unit($value);
}
return $result->$normalizedUnit($normalizedValue);
}
/**
* Truncate the current instance at the given unit with given precision if specified.
*/
public function floorUnit(string $unit, DateInterval|string|float|int $precision = 1): static
{
return $this->roundUnit($unit, $precision, 'floor');
}
/**
* Ceil the current instance at the given unit with given precision if specified.
*/
public function ceilUnit(string $unit, DateInterval|string|float|int $precision = 1): static
{
return $this->roundUnit($unit, $precision, 'ceil');
}
/**
* Round the current instance second with given precision if specified.
*/
public function round(DateInterval|string|float|int $precision = 1, callable|string $function = 'round'): static
{
return $this->roundWith($precision, $function);
}
/**
* Round the current instance second with given precision if specified.
*/
public function floor(DateInterval|string|float|int $precision = 1): static
{
return $this->round($precision, 'floor');
}
/**
* Ceil the current instance second with given precision if specified.
*/
public function ceil(DateInterval|string|float|int $precision = 1): static
{
return $this->round($precision, 'ceil');
}
/**
* Round the current instance week.
*
* @param WeekDay|int|null $weekStartsAt optional start allow you to specify the day of week to use to start the week
*/
public function roundWeek(WeekDay|int|null $weekStartsAt = null): static
{
return $this->closest(
$this->avoidMutation()->floorWeek($weekStartsAt),
$this->avoidMutation()->ceilWeek($weekStartsAt),
);
}
/**
* Truncate the current instance week.
*
* @param WeekDay|int|null $weekStartsAt optional start allow you to specify the day of week to use to start the week
*/
public function floorWeek(WeekDay|int|null $weekStartsAt = null): static
{
return $this->startOfWeek($weekStartsAt);
}
/**
* Ceil the current instance week.
*
* @param WeekDay|int|null $weekStartsAt optional start allow you to specify the day of week to use to start the week
*/
public function ceilWeek(WeekDay|int|null $weekStartsAt = null): static
{
if ($this->isMutable()) {
$startOfWeek = $this->avoidMutation()->startOfWeek($weekStartsAt);
return $startOfWeek != $this ?
$this->startOfWeek($weekStartsAt)->addWeek() :
$this;
}
$startOfWeek = $this->startOfWeek($weekStartsAt);
return $startOfWeek != $this ?
$startOfWeek->addWeek() :
$this->avoidMutation();
}
}

View File

@@ -0,0 +1,318 @@
<?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Carbon\Traits;
use Carbon\Exceptions\InvalidFormatException;
use Carbon\FactoryImmutable;
use DateTimeZone;
use ReturnTypeWillChange;
use Throwable;
/**
* Trait Serialization.
*
* Serialization and JSON stuff.
*
* Depends on the following properties:
*
* @property int $year
* @property int $month
* @property int $daysInMonth
* @property int $quarter
*
* Depends on the following methods:
*
* @method string|static locale(string $locale = null, string ...$fallbackLocales)
* @method string toJSON()
*/
trait Serialization
{
use ObjectInitialisation;
/**
* List of key to use for dump/serialization.
*
* @var string[]
*/
protected array $dumpProperties = ['date', 'timezone_type', 'timezone'];
/**
* Locale to dump comes here before serialization.
*
* @var string|null
*/
protected $dumpLocale;
/**
* Embed date properties to dump in a dedicated variables so it won't overlap native
* DateTime ones.
*
* @var array|null
*/
protected $dumpDateProperties;
/**
* Return a serialized string of the instance.
*/
public function serialize(): string
{
return serialize($this);
}
/**
* Create an instance from a serialized string.
*
* @param string $value
*
* @throws InvalidFormatException
*
* @return static
*/
public static function fromSerialized($value): static
{
$instance = @unserialize((string) $value);
if (!$instance instanceof static) {
throw new InvalidFormatException("Invalid serialized value: $value");
}
return $instance;
}
/**
* The __set_state handler.
*
* @param string|array $dump
*
* @return static
*/
#[ReturnTypeWillChange]
public static function __set_state($dump): static
{
if (\is_string($dump)) {
return static::parse($dump);
}
/** @var \DateTimeInterface $date */
$date = get_parent_class(static::class) && method_exists(parent::class, '__set_state')
? parent::__set_state((array) $dump)
: (object) $dump;
return static::instance($date);
}
/**
* Returns the list of properties to dump on serialize() called on.
*
* Only used by PHP < 7.4.
*
* @return array
*/
public function __sleep()
{
$properties = $this->getSleepProperties();
if ($this->localTranslator ?? null) {
$properties[] = 'dumpLocale';
$this->dumpLocale = $this->locale ?? null;
}
return $properties;
}
/**
* Returns the values to dump on serialize() called on.
*
* Only used by PHP >= 7.4.
*
* @return array
*/
public function __serialize(): array
{
// @codeCoverageIgnoreStart
if (isset($this->timezone_type, $this->timezone, $this->date)) {
return [
'date' => $this->date,
'timezone_type' => $this->timezone_type,
'timezone' => $this->dumpTimezone($this->timezone),
];
}
// @codeCoverageIgnoreEnd
$timezone = $this->getTimezone();
$export = [
'date' => $this->format('Y-m-d H:i:s.u'),
'timezone_type' => $timezone->getType(),
'timezone' => $timezone->getName(),
];
// @codeCoverageIgnoreStart
if (\extension_loaded('msgpack') && isset($this->constructedObjectId)) {
$timezone = $this->timezone ?? null;
$export['dumpDateProperties'] = [
'date' => $this->format('Y-m-d H:i:s.u'),
'timezone' => $this->dumpTimezone($timezone),
];
}
// @codeCoverageIgnoreEnd
if ($this->localTranslator ?? null) {
$export['dumpLocale'] = $this->locale ?? null;
}
return $export;
}
/**
* Set locale if specified on unserialize() called.
*
* Only used by PHP < 7.4.
*/
public function __wakeup(): void
{
if (parent::class && method_exists(parent::class, '__wakeup')) {
// @codeCoverageIgnoreStart
try {
parent::__wakeup();
} catch (Throwable $exception) {
try {
// FatalError occurs when calling msgpack_unpack() in PHP 7.4 or later.
['date' => $date, 'timezone' => $timezone] = $this->dumpDateProperties;
parent::__construct($date, $timezone);
} catch (Throwable) {
throw $exception;
}
}
// @codeCoverageIgnoreEnd
}
$this->constructedObjectId = spl_object_hash($this);
if (isset($this->dumpLocale)) {
$this->locale($this->dumpLocale);
$this->dumpLocale = null;
}
$this->cleanupDumpProperties();
}
/**
* Set locale if specified on unserialize() called.
*
* Only used by PHP >= 7.4.
*/
public function __unserialize(array $data): void
{
// @codeCoverageIgnoreStart
try {
$this->__construct($data['date'] ?? null, $data['timezone'] ?? null);
} catch (Throwable $exception) {
if (!isset($data['dumpDateProperties']['date'], $data['dumpDateProperties']['timezone'])) {
throw $exception;
}
try {
// FatalError occurs when calling msgpack_unpack() in PHP 7.4 or later.
['date' => $date, 'timezone' => $timezone] = $data['dumpDateProperties'];
$this->__construct($date, $timezone);
} catch (Throwable) {
throw $exception;
}
}
// @codeCoverageIgnoreEnd
if (isset($data['dumpLocale'])) {
$this->locale($data['dumpLocale']);
}
}
/**
* Prepare the object for JSON serialization.
*/
public function jsonSerialize(): mixed
{
$serializer = $this->localSerializer
?? $this->getFactory()->getSettings()['toJsonFormat']
?? null;
if ($serializer) {
return \is_string($serializer)
? $this->rawFormat($serializer)
: $serializer($this);
}
return $this->toJSON();
}
/**
* @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
* You should rather transform Carbon object before the serialization.
*
* JSON serialize all Carbon instances using the given callback.
*/
public static function serializeUsing(string|callable|null $format): void
{
FactoryImmutable::getDefaultInstance()->serializeUsing($format);
}
/**
* Cleanup properties attached to the public scope of DateTime when a dump of the date is requested.
* foreach ($date as $_) {}
* serializer($date)
* var_export($date)
* get_object_vars($date)
*/
public function cleanupDumpProperties(): self
{
// @codeCoverageIgnoreStart
if (PHP_VERSION < 8.2) {
foreach ($this->dumpProperties as $property) {
if (isset($this->$property)) {
unset($this->$property);
}
}
}
// @codeCoverageIgnoreEnd
return $this;
}
private function getSleepProperties(): array
{
$properties = $this->dumpProperties;
// @codeCoverageIgnoreStart
if (!\extension_loaded('msgpack')) {
return $properties;
}
if (isset($this->constructedObjectId)) {
$timezone = $this->timezone ?? null;
$this->dumpDateProperties = [
'date' => $this->format('Y-m-d H:i:s.u'),
'timezone' => $this->dumpTimezone($timezone),
];
$properties[] = 'dumpDateProperties';
}
return $properties;
// @codeCoverageIgnoreEnd
}
private function dumpTimezone(mixed $timezone): mixed
{
return $timezone instanceof DateTimeZone ? $timezone->getName() : $timezone;
}
}

View File

@@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Carbon\Traits;
use Carbon\FactoryImmutable;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* Static config for localization.
*/
trait StaticLocalization
{
/**
* @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
* You should rather use the ->settings() method.
* @see settings
*/
public static function setHumanDiffOptions(int $humanDiffOptions): void
{
FactoryImmutable::getDefaultInstance()->setHumanDiffOptions($humanDiffOptions);
}
/**
* @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
* You should rather use the ->settings() method.
* @see settings
*/
public static function enableHumanDiffOption(int $humanDiffOption): void
{
FactoryImmutable::getDefaultInstance()->enableHumanDiffOption($humanDiffOption);
}
/**
* @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
* You should rather use the ->settings() method.
* @see settings
*/
public static function disableHumanDiffOption(int $humanDiffOption): void
{
FactoryImmutable::getDefaultInstance()->disableHumanDiffOption($humanDiffOption);
}
/**
* Return default humanDiff() options (merged flags as integer).
*/
public static function getHumanDiffOptions(): int
{
return FactoryImmutable::getInstance()->getHumanDiffOptions();
}
/**
* Set the default translator instance to use.
*
* @param TranslatorInterface $translator
*
* @return void
*/
public static function setTranslator(TranslatorInterface $translator): void
{
FactoryImmutable::getDefaultInstance()->setTranslator($translator);
}
/**
* Initialize the default translator instance if necessary.
*/
public static function getTranslator(): TranslatorInterface
{
return FactoryImmutable::getInstance()->getTranslator();
}
}

View File

@@ -0,0 +1,164 @@
<?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Carbon\Traits;
use Carbon\FactoryImmutable;
/**
* Options related to a static variable.
*/
trait StaticOptions
{
///////////////////////////////////////////////////////////////////
///////////// Behavior customization for sub-classes //////////////
///////////////////////////////////////////////////////////////////
/**
* Function to call instead of format.
*
* @var string|callable|null
*/
protected static $formatFunction;
/**
* Function to call instead of createFromFormat.
*
* @var string|callable|null
*/
protected static $createFromFormatFunction;
/**
* Function to call instead of parse.
*
* @var string|callable|null
*/
protected static $parseFunction;
///////////////////////////////////////////////////////////////////
///////////// Use default factory for static options //////////////
///////////////////////////////////////////////////////////////////
/**
* @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
* You should rather use the ->settings() method.
* @see settings
*
* Enable the strict mode (or disable with passing false).
*
* @param bool $strictModeEnabled
*/
public static function useStrictMode(bool $strictModeEnabled = true): void
{
FactoryImmutable::getDefaultInstance()->useStrictMode($strictModeEnabled);
}
/**
* Returns true if the strict mode is globally in use, false else.
* (It can be overridden in specific instances.)
*
* @return bool
*/
public static function isStrictModeEnabled(): bool
{
return FactoryImmutable::getInstance()->isStrictModeEnabled();
}
/**
* @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
* You should rather use the ->settings() method.
* Or you can use method variants: addMonthsWithOverflow/addMonthsNoOverflow, same variants
* are available for quarters, years, decade, centuries, millennia (singular and plural forms).
* @see settings
*
* Indicates if months should be calculated with overflow.
*
* @param bool $monthsOverflow
*
* @return void
*/
public static function useMonthsOverflow(bool $monthsOverflow = true): void
{
FactoryImmutable::getDefaultInstance()->useMonthsOverflow($monthsOverflow);
}
/**
* @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
* You should rather use the ->settings() method.
* Or you can use method variants: addMonthsWithOverflow/addMonthsNoOverflow, same variants
* are available for quarters, years, decade, centuries, millennia (singular and plural forms).
* @see settings
*
* Reset the month overflow behavior.
*
* @return void
*/
public static function resetMonthsOverflow(): void
{
FactoryImmutable::getDefaultInstance()->resetMonthsOverflow();
}
/**
* Get the month overflow global behavior (can be overridden in specific instances).
*
* @return bool
*/
public static function shouldOverflowMonths(): bool
{
return FactoryImmutable::getInstance()->shouldOverflowMonths();
}
/**
* @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
* You should rather use the ->settings() method.
* Or you can use method variants: addYearsWithOverflow/addYearsNoOverflow, same variants
* are available for quarters, years, decade, centuries, millennia (singular and plural forms).
* @see settings
*
* Indicates if years should be calculated with overflow.
*
* @param bool $yearsOverflow
*
* @return void
*/
public static function useYearsOverflow(bool $yearsOverflow = true): void
{
FactoryImmutable::getDefaultInstance()->useYearsOverflow($yearsOverflow);
}
/**
* @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
* You should rather use the ->settings() method.
* Or you can use method variants: addYearsWithOverflow/addYearsNoOverflow, same variants
* are available for quarters, years, decade, centuries, millennia (singular and plural forms).
* @see settings
*
* Reset the month overflow behavior.
*
* @return void
*/
public static function resetYearsOverflow(): void
{
FactoryImmutable::getDefaultInstance()->resetYearsOverflow();
}
/**
* Get the month overflow global behavior (can be overridden in specific instances).
*
* @return bool
*/
public static function shouldOverflowYears(): bool
{
return FactoryImmutable::getInstance()->shouldOverflowYears();
}
}

View File

@@ -0,0 +1,185 @@
<?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Carbon\Traits;
use Carbon\CarbonInterface;
use Carbon\CarbonTimeZone;
use Carbon\Factory;
use Carbon\FactoryImmutable;
use Closure;
use DateTimeImmutable;
use DateTimeInterface;
use DateTimeZone;
trait Test
{
///////////////////////////////////////////////////////////////////
///////////////////////// TESTING AIDS ////////////////////////////
///////////////////////////////////////////////////////////////////
/**
* Set a Carbon instance (real or mock) to be returned when a "now"
* instance is created. The provided instance will be returned
* specifically under the following conditions:
* - A call to the static now() method, ex. Carbon::now()
* - When a null (or blank string) is passed to the constructor or parse(), ex. new Carbon(null)
* - When the string "now" is passed to the constructor or parse(), ex. new Carbon('now')
* - When a string containing the desired time is passed to Carbon::parse().
*
* Note the timezone parameter was left out of the examples above and
* has no affect as the mock value will be returned regardless of its value.
*
* Only the moment is mocked with setTestNow(), the timezone will still be the one passed
* as parameter of date_default_timezone_get() as a fallback (see setTestNowAndTimezone()).
*
* To clear the test instance call this method using the default
* parameter of null.
*
* /!\ Use this method for unit tests only.
*
* @param DateTimeInterface|Closure|static|string|false|null $testNow real or mock Carbon instance
*/
public static function setTestNow(mixed $testNow = null): void
{
FactoryImmutable::getDefaultInstance()->setTestNow($testNow);
}
/**
* Set a Carbon instance (real or mock) to be returned when a "now"
* instance is created. The provided instance will be returned
* specifically under the following conditions:
* - A call to the static now() method, ex. Carbon::now()
* - When a null (or blank string) is passed to the constructor or parse(), ex. new Carbon(null)
* - When the string "now" is passed to the constructor or parse(), ex. new Carbon('now')
* - When a string containing the desired time is passed to Carbon::parse().
*
* It will also align default timezone (e.g. call date_default_timezone_set()) with
* the second argument or if null, with the timezone of the given date object.
*
* To clear the test instance call this method using the default
* parameter of null.
*
* /!\ Use this method for unit tests only.
*
* @param DateTimeInterface|Closure|static|string|false|null $testNow real or mock Carbon instance
*/
public static function setTestNowAndTimezone($testNow = null, $timezone = null): void
{
FactoryImmutable::getDefaultInstance()->setTestNowAndTimezone($testNow, $timezone);
}
/**
* Temporarily sets a static date to be used within the callback.
* Using setTestNow to set the date, executing the callback, then
* clearing the test instance.
*
* /!\ Use this method for unit tests only.
*
* @template T
*
* @param DateTimeInterface|Closure|static|string|false|null $testNow real or mock Carbon instance
* @param Closure(): T $callback
*
* @return T
*/
public static function withTestNow(mixed $testNow, callable $callback): mixed
{
return FactoryImmutable::getDefaultInstance()->withTestNow($testNow, $callback);
}
/**
* Get the Carbon instance (real or mock) to be returned when a "now"
* instance is created.
*
* @return Closure|CarbonInterface|null the current instance used for testing
*/
public static function getTestNow(): Closure|CarbonInterface|null
{
return FactoryImmutable::getInstance()->getTestNow();
}
/**
* Determine if there is a valid test instance set. A valid test instance
* is anything that is not null.
*
* @return bool true if there is a test instance, otherwise false
*/
public static function hasTestNow(): bool
{
return FactoryImmutable::getInstance()->hasTestNow();
}
/**
* Get the mocked date passed in setTestNow() and if it's a Closure, execute it.
*/
protected static function getMockedTestNow(DateTimeZone|string|int|null $timezone): ?CarbonInterface
{
$testNow = FactoryImmutable::getInstance()->handleTestNowClosure(static::getTestNow(), $timezone);
if ($testNow === null) {
return null;
}
$testNow = $testNow->avoidMutation();
return $timezone ? $testNow->setTimezone($timezone) : $testNow;
}
private function mockConstructorParameters(&$time, ?CarbonTimeZone $timezone): void
{
$clock = $this->clock?->unwrap();
$now = $clock instanceof Factory
? $clock->getTestNow()
: $this->nowFromClock($timezone);
$testInstance = $now ?? self::getMockedTestNowClone($timezone);
if (!$testInstance) {
return;
}
if ($testInstance instanceof DateTimeInterface) {
$testInstance = $testInstance->setTimezone($timezone ?? date_default_timezone_get());
}
if (static::hasRelativeKeywords($time)) {
$testInstance = $testInstance->modify($time);
}
$factory = $this->getClock()?->unwrap();
if (!($factory instanceof Factory)) {
$factory = FactoryImmutable::getInstance();
}
$testInstance = $factory->handleTestNowClosure($testInstance, $timezone);
$time = $testInstance instanceof self
? $testInstance->rawFormat(static::MOCK_DATETIME_FORMAT)
: $testInstance->format(static::MOCK_DATETIME_FORMAT);
}
private function getMockedTestNowClone($timezone): CarbonInterface|self|null
{
$mock = static::getMockedTestNow($timezone);
return $mock ? clone $mock : null;
}
private function nowFromClock(?CarbonTimeZone $timezone): ?DateTimeImmutable
{
$now = $this->clock?->now();
return $now && $timezone ? $now->setTimezone($timezone) : null;
}
}

View File

@@ -0,0 +1,191 @@
<?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Carbon\Traits;
use DateTimeZone;
/**
* Trait Timestamp.
*/
trait Timestamp
{
/**
* Create a Carbon instance from a timestamp and set the timezone (UTC by default).
*
* Timestamp input can be given as int, float or a string containing one or more numbers.
*/
public static function createFromTimestamp(
float|int|string $timestamp,
DateTimeZone|string|int|null $timezone = null,
): static {
$date = static::createFromTimestampUTC($timestamp);
return $timezone === null ? $date : $date->setTimezone($timezone);
}
/**
* Create a Carbon instance from a timestamp keeping the timezone to UTC.
*
* Timestamp input can be given as int, float or a string containing one or more numbers.
*/
public static function createFromTimestampUTC(float|int|string $timestamp): static
{
[$integer, $decimal] = self::getIntegerAndDecimalParts($timestamp);
$delta = floor($decimal / static::MICROSECONDS_PER_SECOND);
$integer += $delta;
$decimal -= $delta * static::MICROSECONDS_PER_SECOND;
$decimal = str_pad((string) $decimal, 6, '0', STR_PAD_LEFT);
return static::rawCreateFromFormat('U u', "$integer $decimal");
}
/**
* Create a Carbon instance from a timestamp in milliseconds.
*
* Timestamp input can be given as int, float or a string containing one or more numbers.
*
* @param float|int|string $timestamp
*
* @return static
*/
public static function createFromTimestampMsUTC($timestamp): static
{
[$milliseconds, $microseconds] = self::getIntegerAndDecimalParts($timestamp, 3);
$sign = $milliseconds < 0 || ($milliseconds === 0.0 && $microseconds < 0) ? -1 : 1;
$milliseconds = abs($milliseconds);
$microseconds = $sign * abs($microseconds) + static::MICROSECONDS_PER_MILLISECOND * ($milliseconds % static::MILLISECONDS_PER_SECOND);
$seconds = $sign * floor($milliseconds / static::MILLISECONDS_PER_SECOND);
$delta = floor($microseconds / static::MICROSECONDS_PER_SECOND);
$seconds = (int) ($seconds + $delta);
$microseconds -= $delta * static::MICROSECONDS_PER_SECOND;
$microseconds = str_pad((string) (int) $microseconds, 6, '0', STR_PAD_LEFT);
return static::rawCreateFromFormat('U u', "$seconds $microseconds");
}
/**
* Create a Carbon instance from a timestamp in milliseconds.
*
* Timestamp input can be given as int, float or a string containing one or more numbers.
*/
public static function createFromTimestampMs(
float|int|string $timestamp,
DateTimeZone|string|int|null $timezone = null,
): static {
$date = static::createFromTimestampMsUTC($timestamp);
return $timezone === null ? $date : $date->setTimezone($timezone);
}
/**
* Set the instance's timestamp.
*
* Timestamp input can be given as int, float or a string containing one or more numbers.
*/
public function timestamp(float|int|string $timestamp): static
{
return $this->setTimestamp($timestamp);
}
/**
* Returns a timestamp rounded with the given precision (6 by default).
*
* @example getPreciseTimestamp() 1532087464437474 (microsecond maximum precision)
* @example getPreciseTimestamp(6) 1532087464437474
* @example getPreciseTimestamp(5) 153208746443747 (1/100000 second precision)
* @example getPreciseTimestamp(4) 15320874644375 (1/10000 second precision)
* @example getPreciseTimestamp(3) 1532087464437 (millisecond precision)
* @example getPreciseTimestamp(2) 153208746444 (1/100 second precision)
* @example getPreciseTimestamp(1) 15320874644 (1/10 second precision)
* @example getPreciseTimestamp(0) 1532087464 (second precision)
* @example getPreciseTimestamp(-1) 153208746 (10 second precision)
* @example getPreciseTimestamp(-2) 15320875 (100 second precision)
*
* @param int $precision
*
* @return float
*/
public function getPreciseTimestamp($precision = 6): float
{
return round(((float) $this->rawFormat('Uu')) / pow(10, 6 - $precision));
}
/**
* Returns the milliseconds timestamps used amongst other by Date javascript objects.
*
* @return float
*/
public function valueOf(): float
{
return $this->getPreciseTimestamp(3);
}
/**
* Returns the timestamp with millisecond precision.
*
* @return int
*/
public function getTimestampMs(): int
{
return (int) $this->getPreciseTimestamp(3);
}
/**
* @alias getTimestamp
*
* Returns the UNIX timestamp for the current date.
*
* @return int
*/
public function unix(): int
{
return $this->getTimestamp();
}
/**
* Return an array with integer part digits and decimals digits split from one or more positive numbers
* (such as timestamps) as string with the given number of decimals (6 by default).
*
* By splitting integer and decimal, this method obtain a better precision than
* number_format when the input is a string.
*
* @param float|int|string $numbers one or more numbers
* @param int $decimals number of decimals precision (6 by default)
*
* @return array 0-index is integer part, 1-index is decimal part digits
*/
private static function getIntegerAndDecimalParts($numbers, $decimals = 6): array
{
if (\is_int($numbers) || \is_float($numbers)) {
$numbers = number_format($numbers, $decimals, '.', '');
}
$sign = str_starts_with($numbers, '-') ? -1 : 1;
$integer = 0;
$decimal = 0;
foreach (preg_split('`[^\d.]+`', $numbers) as $chunk) {
[$integerPart, $decimalPart] = explode('.', "$chunk.");
$integer += (int) $integerPart;
$decimal += (float) ("0.$decimalPart");
}
$overflow = floor($decimal);
$integer += $overflow;
$decimal -= $overflow;
return [$sign * $integer, $decimal === 0.0 ? 0.0 : $sign * round($decimal * pow(10, $decimals))];
}
}

View File

@@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Carbon\Traits;
use Carbon\FactoryImmutable;
use Closure;
/**
* Trait ToStringFormat.
*
* Handle global format customization for string cast of the object.
*/
trait ToStringFormat
{
/**
* Reset the format used to the default when type juggling a Carbon instance to a string
*
* @return void
*/
public static function resetToStringFormat(): void
{
FactoryImmutable::getDefaultInstance()->resetToStringFormat();
}
/**
* @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
* You should rather let Carbon object being cast to string with DEFAULT_TO_STRING_FORMAT, and
* use other method or custom format passed to format() method if you need to dump another string
* format.
*
* Set the default format used when type juggling a Carbon instance to a string.
*
* @param string|Closure|null $format
*
* @return void
*/
public static function setToStringFormat(string|Closure|null $format): void
{
FactoryImmutable::getDefaultInstance()->setToStringFormat($format);
}
}

View File

@@ -0,0 +1,469 @@
<?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Carbon\Traits;
use Carbon\CarbonConverterInterface;
use Carbon\CarbonInterface;
use Carbon\CarbonInterval;
use Carbon\Exceptions\InvalidFormatException;
use Carbon\Exceptions\InvalidIntervalException;
use Carbon\Exceptions\UnitException;
use Carbon\Exceptions\UnsupportedUnitException;
use Carbon\Unit;
use Closure;
use DateInterval;
use DateMalformedStringException;
use ReturnTypeWillChange;
/**
* Trait Units.
*
* Add, subtract and set units.
*/
trait Units
{
/**
* @deprecated Prefer to use add addUTCUnit() which more accurately defines what it's doing.
*
* Add seconds to the instance using timestamp. Positive $value travels
* forward while negative $value travels into the past.
*
* @param string $unit
* @param int|float|null $value
*
* @return static
*/
public function addRealUnit(string $unit, $value = 1): static
{
return $this->addUTCUnit($unit, $value);
}
/**
* Add seconds to the instance using timestamp. Positive $value travels
* forward while negative $value travels into the past.
*
* @param string $unit
* @param int|float|null $value
*
* @return static
*/
public function addUTCUnit(string $unit, $value = 1): static
{
$value ??= 0;
switch ($unit) {
// @call addUTCUnit
case 'micro':
// @call addUTCUnit
case 'microsecond':
/* @var CarbonInterface $this */
$diff = $this->microsecond + $value;
$time = $this->getTimestamp();
$seconds = (int) floor($diff / static::MICROSECONDS_PER_SECOND);
$time += $seconds;
$diff -= $seconds * static::MICROSECONDS_PER_SECOND;
$microtime = str_pad((string) $diff, 6, '0', STR_PAD_LEFT);
$timezone = $this->tz;
return $this->tz('UTC')->modify("@$time.$microtime")->setTimezone($timezone);
// @call addUTCUnit
case 'milli':
// @call addUTCUnit
case 'millisecond':
return $this->addUTCUnit('microsecond', $value * static::MICROSECONDS_PER_MILLISECOND);
// @call addUTCUnit
case 'second':
break;
// @call addUTCUnit
case 'minute':
$value *= static::SECONDS_PER_MINUTE;
break;
// @call addUTCUnit
case 'hour':
$value *= static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE;
break;
// @call addUTCUnit
case 'day':
$value *= static::HOURS_PER_DAY * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE;
break;
// @call addUTCUnit
case 'week':
$value *= static::DAYS_PER_WEEK * static::HOURS_PER_DAY * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE;
break;
// @call addUTCUnit
case 'month':
$value *= 30 * static::HOURS_PER_DAY * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE;
break;
// @call addUTCUnit
case 'quarter':
$value *= static::MONTHS_PER_QUARTER * 30 * static::HOURS_PER_DAY * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE;
break;
// @call addUTCUnit
case 'year':
$value *= 365 * static::HOURS_PER_DAY * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE;
break;
// @call addUTCUnit
case 'decade':
$value *= static::YEARS_PER_DECADE * 365 * static::HOURS_PER_DAY * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE;
break;
// @call addUTCUnit
case 'century':
$value *= static::YEARS_PER_CENTURY * 365 * static::HOURS_PER_DAY * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE;
break;
// @call addUTCUnit
case 'millennium':
$value *= static::YEARS_PER_MILLENNIUM * 365 * static::HOURS_PER_DAY * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE;
break;
default:
if ($this->isLocalStrictModeEnabled()) {
throw new UnitException("Invalid unit for real timestamp add/sub: '$unit'");
}
return $this;
}
$seconds = (int) $value;
$microseconds = (int) round(
(abs($value) - abs($seconds)) * ($value < 0 ? -1 : 1) * static::MICROSECONDS_PER_SECOND,
);
$date = $this->setTimestamp($this->getTimestamp() + $seconds);
return $microseconds ? $date->addUTCUnit('microsecond', $microseconds) : $date;
}
/**
* @deprecated Prefer to use add subUTCUnit() which more accurately defines what it's doing.
*
* Subtract seconds to the instance using timestamp. Positive $value travels
* into the past while negative $value travels forward.
*
* @param string $unit
* @param int $value
*
* @return static
*/
public function subRealUnit($unit, $value = 1): static
{
return $this->addUTCUnit($unit, -$value);
}
/**
* Subtract seconds to the instance using timestamp. Positive $value travels
* into the past while negative $value travels forward.
*
* @param string $unit
* @param int $value
*
* @return static
*/
public function subUTCUnit($unit, $value = 1): static
{
return $this->addUTCUnit($unit, -$value);
}
/**
* Returns true if a property can be changed via setter.
*
* @param string $unit
*
* @return bool
*/
public static function isModifiableUnit($unit): bool
{
static $modifiableUnits = [
// @call addUnit
'millennium',
// @call addUnit
'century',
// @call addUnit
'decade',
// @call addUnit
'quarter',
// @call addUnit
'week',
// @call addUnit
'weekday',
];
return \in_array($unit, $modifiableUnits, true) || \in_array($unit, static::$units, true);
}
/**
* Call native PHP DateTime/DateTimeImmutable add() method.
*
* @param DateInterval $interval
*
* @return static
*/
public function rawAdd(DateInterval $interval): static
{
return parent::add($interval);
}
/**
* Add given units or interval to the current instance.
*
* @example $date->add('hour', 3)
* @example $date->add(15, 'days')
* @example $date->add(CarbonInterval::days(4))
*
* @param Unit|string|DateInterval|Closure|CarbonConverterInterface $unit
* @param int|float $value
* @param bool|null $overflow
*
* @return static
*/
#[ReturnTypeWillChange]
public function add($unit, $value = 1, ?bool $overflow = null): static
{
$unit = Unit::toNameIfUnit($unit);
$value = Unit::toNameIfUnit($value);
if (\is_string($unit) && \func_num_args() === 1) {
$unit = CarbonInterval::make($unit, [], true);
}
if ($unit instanceof CarbonConverterInterface) {
$unit = Closure::fromCallable([$unit, 'convertDate']);
}
if ($unit instanceof Closure) {
$result = $this->resolveCarbon($unit($this, false));
if ($this !== $result && $this->isMutable()) {
return $this->setDateTimeFrom($result);
}
return $result;
}
if ($unit instanceof DateInterval) {
return parent::add($unit);
}
if (is_numeric($unit)) {
[$value, $unit] = [$unit, $value];
}
return $this->addUnit((string) $unit, $value, $overflow);
}
/**
* Add given units to the current instance.
*/
public function addUnit(Unit|string $unit, $value = 1, ?bool $overflow = null): static
{
$unit = Unit::toName($unit);
$originalArgs = \func_get_args();
$date = $this;
if (!is_numeric($value) || !(float) $value) {
return $date->isMutable() ? $date : $date->copy();
}
$unit = self::singularUnit($unit);
$metaUnits = [
'millennium' => [static::YEARS_PER_MILLENNIUM, 'year'],
'century' => [static::YEARS_PER_CENTURY, 'year'],
'decade' => [static::YEARS_PER_DECADE, 'year'],
'quarter' => [static::MONTHS_PER_QUARTER, 'month'],
];
if (isset($metaUnits[$unit])) {
[$factor, $unit] = $metaUnits[$unit];
$value *= $factor;
}
if ($unit === 'weekday') {
$weekendDays = $this->transmitFactory(static fn () => static::getWeekendDays());
if ($weekendDays !== [static::SATURDAY, static::SUNDAY]) {
$absoluteValue = abs($value);
$sign = $value / max(1, $absoluteValue);
$weekDaysCount = static::DAYS_PER_WEEK - min(static::DAYS_PER_WEEK - 1, \count(array_unique($weekendDays)));
$weeks = floor($absoluteValue / $weekDaysCount);
for ($diff = $absoluteValue % $weekDaysCount; $diff; $diff--) {
/** @var static $date */
$date = $date->addDays($sign);
while (\in_array($date->dayOfWeek, $weekendDays, true)) {
$date = $date->addDays($sign);
}
}
$value = $weeks * $sign;
$unit = 'week';
}
$timeString = $date->toTimeString();
} elseif ($canOverflow = (\in_array($unit, [
'month',
'year',
]) && ($overflow === false || (
$overflow === null &&
($ucUnit = ucfirst($unit).'s') &&
!($this->{'local'.$ucUnit.'Overflow'} ?? static::{'shouldOverflow'.$ucUnit}())
)))) {
$day = $date->day;
}
if ($unit === 'milli' || $unit === 'millisecond') {
$unit = 'microsecond';
$value *= static::MICROSECONDS_PER_MILLISECOND;
}
$previousException = null;
try {
$date = self::rawAddUnit($date, $unit, $value);
if (isset($timeString)) {
$date = $date?->setTimeFromTimeString($timeString);
} elseif (isset($canOverflow, $day) && $canOverflow && $day !== $date?->day) {
$date = $date?->modify('last day of previous month');
}
} catch (DateMalformedStringException|InvalidFormatException|UnsupportedUnitException $exception) {
$date = null;
$previousException = $exception;
}
return $date ?? throw new UnitException(
'Unable to add unit '.var_export($originalArgs, true),
previous: $previousException,
);
}
/**
* Subtract given units to the current instance.
*/
public function subUnit(Unit|string $unit, $value = 1, ?bool $overflow = null): static
{
return $this->addUnit($unit, -$value, $overflow);
}
/**
* Call native PHP DateTime/DateTimeImmutable sub() method.
*/
public function rawSub(DateInterval $interval): static
{
return parent::sub($interval);
}
/**
* Subtract given units or interval to the current instance.
*
* @example $date->sub('hour', 3)
* @example $date->sub(15, 'days')
* @example $date->sub(CarbonInterval::days(4))
*
* @param Unit|string|DateInterval|Closure|CarbonConverterInterface $unit
* @param int|float $value
* @param bool|null $overflow
*
* @return static
*/
#[ReturnTypeWillChange]
public function sub($unit, $value = 1, ?bool $overflow = null): static
{
if (\is_string($unit) && \func_num_args() === 1) {
$unit = CarbonInterval::make($unit, [], true);
}
if ($unit instanceof CarbonConverterInterface) {
$unit = Closure::fromCallable([$unit, 'convertDate']);
}
if ($unit instanceof Closure) {
$result = $this->resolveCarbon($unit($this, true));
if ($this !== $result && $this->isMutable()) {
return $this->setDateTimeFrom($result);
}
return $result;
}
if ($unit instanceof DateInterval) {
return parent::sub($unit);
}
if (is_numeric($unit)) {
[$value, $unit] = [$unit, $value];
}
return $this->addUnit((string) $unit, -(float) $value, $overflow);
}
/**
* Subtract given units or interval to the current instance.
*
* @see sub()
*
* @param string|DateInterval $unit
* @param int|float $value
* @param bool|null $overflow
*
* @return static
*/
public function subtract($unit, $value = 1, ?bool $overflow = null): static
{
if (\is_string($unit) && \func_num_args() === 1) {
$unit = CarbonInterval::make($unit, [], true);
}
return $this->sub($unit, $value, $overflow);
}
private static function rawAddUnit(self $date, string $unit, int|float $value): ?static
{
try {
return $date->rawAdd(
CarbonInterval::fromString(abs($value)." $unit")->invert($value < 0),
);
} catch (InvalidIntervalException $exception) {
try {
return $date->modify("$value $unit");
} catch (InvalidFormatException) {
throw new UnsupportedUnitException($unit, previous: $exception);
}
}
}
}

View File

@@ -0,0 +1,224 @@
<?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Carbon\Traits;
use Carbon\CarbonInterface;
use Carbon\CarbonInterval;
/**
* Trait Week.
*
* week and ISO week number, year and count in year.
*
* Depends on the following properties:
*
* @property int $daysInYear
* @property int $dayOfWeek
* @property int $dayOfYear
* @property int $year
*
* Depends on the following methods:
*
* @method CarbonInterface addWeeks(int $weeks = 1)
* @method CarbonInterface copy()
* @method CarbonInterface dayOfYear(int $dayOfYear)
* @method string getTranslationMessage(string $key, ?string $locale = null, ?string $default = null, $translator = null)
* @method CarbonInterface next(int|string $modifier = null)
* @method CarbonInterface startOfWeek(int $day = null)
* @method CarbonInterface subWeeks(int $weeks = 1)
* @method CarbonInterface year(int $year = null)
*/
trait Week
{
/**
* Set/get the week number of year using given first day of week and first
* day of year included in the first week. Or use ISO format if no settings
* given.
*
* @param int|null $year if null, act as a getter, if not null, set the year and return current instance.
* @param int|null $dayOfWeek first date of week from 0 (Sunday) to 6 (Saturday)
* @param int|null $dayOfYear first day of year included in the week #1
*
* @return int|static
*/
public function isoWeekYear($year = null, $dayOfWeek = null, $dayOfYear = null)
{
return $this->weekYear(
$year,
$dayOfWeek ?? static::MONDAY,
$dayOfYear ?? static::THURSDAY,
);
}
/**
* Set/get the week number of year using given first day of week and first
* day of year included in the first week. Or use US format if no settings
* given (Sunday / Jan 6).
*
* @param int|null $year if null, act as a getter, if not null, set the year and return current instance.
* @param int|null $dayOfWeek first date of week from 0 (Sunday) to 6 (Saturday)
* @param int|null $dayOfYear first day of year included in the week #1
*
* @return int|static
*/
public function weekYear($year = null, $dayOfWeek = null, $dayOfYear = null)
{
$dayOfWeek = $dayOfWeek ?? $this->getTranslationMessage('first_day_of_week') ?? static::SUNDAY;
$dayOfYear = $dayOfYear ?? $this->getTranslationMessage('day_of_first_week_of_year') ?? 1;
if ($year !== null) {
$year = (int) round($year);
if ($this->weekYear(null, $dayOfWeek, $dayOfYear) === $year) {
return $this->avoidMutation();
}
$week = $this->week(null, $dayOfWeek, $dayOfYear);
$day = $this->dayOfWeek;
$date = $this->year($year);
$date = match ($date->weekYear(null, $dayOfWeek, $dayOfYear) - $year) {
CarbonInterval::POSITIVE => $date->subWeeks(static::WEEKS_PER_YEAR / 2),
CarbonInterval::NEGATIVE => $date->addWeeks(static::WEEKS_PER_YEAR / 2),
default => $date,
};
$date = $date
->addWeeks($week - $date->week(null, $dayOfWeek, $dayOfYear))
->startOfWeek($dayOfWeek);
if ($date->dayOfWeek === $day) {
return $date;
}
return $date->next($day);
}
$year = $this->year;
$day = $this->dayOfYear;
$date = $this->avoidMutation()->dayOfYear($dayOfYear)->startOfWeek($dayOfWeek);
if ($date->year === $year && $day < $date->dayOfYear) {
return $year - 1;
}
$date = $this->avoidMutation()->addYear()->dayOfYear($dayOfYear)->startOfWeek($dayOfWeek);
if ($date->year === $year && $day >= $date->dayOfYear) {
return $year + 1;
}
return $year;
}
/**
* Get the number of weeks of the current week-year using given first day of week and first
* day of year included in the first week. Or use ISO format if no settings
* given.
*
* @param int|null $dayOfWeek first date of week from 0 (Sunday) to 6 (Saturday)
* @param int|null $dayOfYear first day of year included in the week #1
*
* @return int
*/
public function isoWeeksInYear($dayOfWeek = null, $dayOfYear = null)
{
return $this->weeksInYear(
$dayOfWeek ?? static::MONDAY,
$dayOfYear ?? static::THURSDAY,
);
}
/**
* Get the number of weeks of the current week-year using given first day of week and first
* day of year included in the first week. Or use US format if no settings
* given (Sunday / Jan 6).
*
* @param int|null $dayOfWeek first date of week from 0 (Sunday) to 6 (Saturday)
* @param int|null $dayOfYear first day of year included in the week #1
*
* @return int
*/
public function weeksInYear($dayOfWeek = null, $dayOfYear = null)
{
$dayOfWeek = $dayOfWeek ?? $this->getTranslationMessage('first_day_of_week') ?? static::SUNDAY;
$dayOfYear = $dayOfYear ?? $this->getTranslationMessage('day_of_first_week_of_year') ?? 1;
$year = $this->year;
$start = $this->avoidMutation()->dayOfYear($dayOfYear)->startOfWeek($dayOfWeek);
$startDay = $start->dayOfYear;
if ($start->year !== $year) {
$startDay -= $start->daysInYear;
}
$end = $this->avoidMutation()->addYear()->dayOfYear($dayOfYear)->startOfWeek($dayOfWeek);
$endDay = $end->dayOfYear;
if ($end->year !== $year) {
$endDay += $this->daysInYear;
}
return (int) round(($endDay - $startDay) / static::DAYS_PER_WEEK);
}
/**
* Get/set the week number using given first day of week and first
* day of year included in the first week. Or use US format if no settings
* given (Sunday / Jan 6).
*
* @param int|null $week
* @param int|null $dayOfWeek
* @param int|null $dayOfYear
*
* @return int|static
*/
public function week($week = null, $dayOfWeek = null, $dayOfYear = null)
{
$date = $this;
$dayOfWeek = $dayOfWeek ?? $this->getTranslationMessage('first_day_of_week') ?? 0;
$dayOfYear = $dayOfYear ?? $this->getTranslationMessage('day_of_first_week_of_year') ?? 1;
if ($week !== null) {
return $date->addWeeks(round($week) - $this->week(null, $dayOfWeek, $dayOfYear));
}
$start = $date->avoidMutation()->shiftTimezone('UTC')->dayOfYear($dayOfYear)->startOfWeek($dayOfWeek);
$end = $date->avoidMutation()->shiftTimezone('UTC')->startOfWeek($dayOfWeek);
if ($start > $end) {
$start = $start->subWeeks(static::WEEKS_PER_YEAR / 2)->dayOfYear($dayOfYear)->startOfWeek($dayOfWeek);
}
$week = (int) ($start->diffInDays($end) / static::DAYS_PER_WEEK + 1);
return $week > $end->weeksInYear($dayOfWeek, $dayOfYear) ? 1 : $week;
}
/**
* Get/set the week number using given first day of week and first
* day of year included in the first week. Or use ISO format if no settings
* given.
*
* @param int|null $week
* @param int|null $dayOfWeek
* @param int|null $dayOfYear
*
* @return int|static
*/
public function isoWeek($week = null, $dayOfWeek = null, $dayOfYear = null)
{
return $this->week(
$week,
$dayOfWeek ?? static::MONDAY,
$dayOfYear ?? static::THURSDAY,
);
}
}