Upgrade framework

This commit is contained in:
2023-11-14 16:54:35 +01:00
parent 1648a5cd42
commit 4fcf6fffcc
10548 changed files with 693138 additions and 466698 deletions

View File

@@ -0,0 +1,443 @@
<?php
/**
* 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;
/**
* 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 int $weekStartsAt optional start allow you to specify the day of week to use to start the week
*
* @return static
*/
public function startOfWeek($weekStartsAt = null)
{
return $this->subDays((7 + $this->dayOfWeek - ($weekStartsAt ?? $this->firstWeekDay)) % 7)->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 int $weekEndsAt optional start allow you to specify the day of week to use to end the week
*
* @return static
*/
public function endOfWeek($weekEndsAt = null)
{
return $this->addDays((7 - $this->dayOfWeek + ($weekEndsAt ?? $this->lastWeekDay)) % 7)->endOfDay();
}
/**
* Modify to start of current hour, minutes and seconds become 0
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->startOfHour();
* ```
*
* @return static
*/
public function startOfHour()
{
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();
* ```
*
* @return static
*/
public function endOfHour()
{
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();
* ```
*
* @return static
*/
public function startOfMinute()
{
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();
* ```
*
* @return static
*/
public function endOfMinute()
{
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');
* ```
*
* @return static
*/
public function startOfSecond()
{
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');
* ```
*
* @return static
*/
public function endOfSecond()
{
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);
* ```
*
* @param string $unit
* @param array<int, mixed> $params
*
* @return static
*/
public function startOf($unit, ...$params)
{
$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);
* ```
*
* @param string $unit
* @param array<int, mixed> $params
*
* @return static
*/
public function endOf($unit, ...$params)
{
$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,43 @@
<?php
/**
* 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.
*
* @param string $className The $className::instance() method will be called to cast the current object.
*
* @return DateTimeInterface
*/
public function cast(string $className)
{
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);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,636 @@
<?php
/**
* 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\UnitException;
use Closure;
use DateTime;
use DateTimeImmutable;
use ReturnTypeWillChange;
/**
* 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
*
* @param string $format
*
* @return string
*/
#[ReturnTypeWillChange]
public function format($format)
{
$function = $this->localFormatFunction ?: 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
*
* @param string $format
*
* @return string
*/
public function rawFormat($format)
{
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
* ```
*
* @return string
*/
public function __toString()
{
$format = $this->localToStringFormat ?? static::$toStringFormat;
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();
* ```
*
* @return string
*/
public function toDateString()
{
return $this->rawFormat('Y-m-d');
}
/**
* Format the instance as a readable date
*
* @example
* ```
* echo Carbon::now()->toFormattedDateString();
* ```
*
* @return string
*/
public function toFormattedDateString()
{
return $this->rawFormat('M j, Y');
}
/**
* Format the instance with the day, and a readable date
*
* @example
* ```
* echo Carbon::now()->toFormattedDayDateString();
* ```
*
* @return string
*/
public function toFormattedDayDateString(): string
{
return $this->rawFormat('D, M j, Y');
}
/**
* Format the instance as time
*
* @example
* ```
* echo Carbon::now()->toTimeString();
* ```
*
* @param string $unitPrecision
*
* @return string
*/
public function toTimeString($unitPrecision = 'second')
{
return $this->rawFormat(static::getTimeFormatByPrecision($unitPrecision));
}
/**
* Format the instance as date and time
*
* @example
* ```
* echo Carbon::now()->toDateTimeString();
* ```
*
* @param string $unitPrecision
*
* @return string
*/
public function toDateTimeString($unitPrecision = 'second')
{
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"
*
* @return string
*/
public static function getTimeFormatByPrecision($unitPrecision)
{
switch (static::singularUnit($unitPrecision)) {
case 'minute':
return 'H:i';
case 'second':
return 'H:i:s';
case 'm':
case 'millisecond':
return 'H:i:s.v';
case 'µ':
case 'microsecond':
return 'H:i:s.u';
}
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
* ```
*
* @param string $unitPrecision
*
* @return string
*/
public function toDateTimeLocalString($unitPrecision = 'second')
{
return $this->rawFormat('Y-m-d\T'.static::getTimeFormatByPrecision($unitPrecision));
}
/**
* Format the instance with day, date and time
*
* @example
* ```
* echo Carbon::now()->toDayDateTimeString();
* ```
*
* @return string
*/
public function toDayDateTimeString()
{
return $this->rawFormat('D, M j, Y g:i A');
}
/**
* Format the instance as ATOM
*
* @example
* ```
* echo Carbon::now()->toAtomString();
* ```
*
* @return string
*/
public function toAtomString()
{
return $this->rawFormat(DateTime::ATOM);
}
/**
* Format the instance as COOKIE
*
* @example
* ```
* echo Carbon::now()->toCookieString();
* ```
*
* @return string
*/
public function toCookieString()
{
return $this->rawFormat(DateTime::COOKIE);
}
/**
* Format the instance as ISO8601
*
* @example
* ```
* echo Carbon::now()->toIso8601String();
* ```
*
* @return string
*/
public function toIso8601String()
{
return $this->toAtomString();
}
/**
* Format the instance as RFC822
*
* @example
* ```
* echo Carbon::now()->toRfc822String();
* ```
*
* @return string
*/
public function toRfc822String()
{
return $this->rawFormat(DateTime::RFC822);
}
/**
* Convert the instance to UTC and return as Zulu ISO8601
*
* @example
* ```
* echo Carbon::now()->toIso8601ZuluString();
* ```
*
* @param string $unitPrecision
*
* @return string
*/
public function toIso8601ZuluString($unitPrecision = 'second')
{
return $this->avoidMutation()
->utc()
->rawFormat('Y-m-d\T'.static::getTimeFormatByPrecision($unitPrecision).'\Z');
}
/**
* Format the instance as RFC850
*
* @example
* ```
* echo Carbon::now()->toRfc850String();
* ```
*
* @return string
*/
public function toRfc850String()
{
return $this->rawFormat(DateTime::RFC850);
}
/**
* Format the instance as RFC1036
*
* @example
* ```
* echo Carbon::now()->toRfc1036String();
* ```
*
* @return string
*/
public function toRfc1036String()
{
return $this->rawFormat(DateTime::RFC1036);
}
/**
* Format the instance as RFC1123
*
* @example
* ```
* echo Carbon::now()->toRfc1123String();
* ```
*
* @return string
*/
public function toRfc1123String()
{
return $this->rawFormat(DateTime::RFC1123);
}
/**
* Format the instance as RFC2822
*
* @example
* ```
* echo Carbon::now()->toRfc2822String();
* ```
*
* @return string
*/
public function toRfc2822String()
{
return $this->rawFormat(DateTime::RFC2822);
}
/**
* Format the instance as RFC3339
*
* @param bool $extended
*
* @example
* ```
* echo Carbon::now()->toRfc3339String() . "\n";
* echo Carbon::now()->toRfc3339String(true) . "\n";
* ```
*
* @return string
*/
public function toRfc3339String($extended = false)
{
$format = DateTime::RFC3339;
if ($extended) {
$format = DateTime::RFC3339_EXTENDED;
}
return $this->rawFormat($format);
}
/**
* Format the instance as RSS
*
* @example
* ```
* echo Carbon::now()->toRssString();
* ```
*
* @return string
*/
public function toRssString()
{
return $this->rawFormat(DateTime::RSS);
}
/**
* Format the instance as W3C
*
* @example
* ```
* echo Carbon::now()->toW3cString();
* ```
*
* @return string
*/
public function toW3cString()
{
return $this->rawFormat(DateTime::W3C);
}
/**
* Format the instance as RFC7231
*
* @example
* ```
* echo Carbon::now()->toRfc7231String();
* ```
*
* @return string
*/
public function toRfc7231String()
{
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());
* ```
*
* @return array
*/
public function toArray()
{
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());
* ```
*
* @return object
*/
public function toObject()
{
return (object) $this->toArray();
}
/**
* Returns english human readable complete date string.
*
* @example
* ```
* echo Carbon::now()->toString();
* ```
*
* @return string
*/
public function toString()
{
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.
*
* @return null|string
*/
public function toISOString($keepOffset = false)
{
if (!$this->isValid()) {
return null;
}
$yearFormat = $this->year < 0 || $this->year > 9999 ? 'YYYYYY' : 'YYYY';
$tzFormat = $keepOffset ? 'Z' : '[Z]';
$date = $keepOffset ? $this : $this->avoidMutation()->utc();
return $date->isoFormat("$yearFormat-MM-DD[T]HH:mm:ss.SSSSSS$tzFormat");
}
/**
* Return the ISO-8601 string (ex: 1977-04-22T06:00:00Z) with UTC timezone.
*
* @example
* ```
* echo Carbon::now('America/Toronto')->toJSON();
* ```
*
* @return null|string
*/
public function toJSON()
{
return $this->toISOString();
}
/**
* Return native DateTime PHP object matching the current instance.
*
* @example
* ```
* var_dump(Carbon::now()->toDateTime());
* ```
*
* @return DateTime
*/
public function toDateTime()
{
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());
* ```
*
* @return DateTimeImmutable
*/
public function toDateTimeImmutable()
{
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());
* ```
*
* @return DateTime
*/
public function toDate()
{
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
*
* @return CarbonPeriod
*/
public function toPeriod($end = null, $interval = null, $unit = null)
{
if ($unit) {
$interval = CarbonInterval::make("$interval ".static::pluralUnit($unit));
}
$period = (new CarbonPeriod())->setDateClass(static::class)->setStartDate($this);
if ($interval) {
$period->setDateInterval($interval);
}
if (\is_int($end) || (\is_string($end) && ctype_digit($end))) {
$period->setRecurrences($end);
} elseif ($end) {
$period->setEndDate($end);
}
return $period;
}
/**
* 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
*
* @return CarbonPeriod
*/
public function range($end = null, $interval = null, $unit = null)
{
return $this->toPeriod($end, $interval, $unit);
}
}

View File

@@ -0,0 +1,950 @@
<?php
/**
* 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\OutOfRangeException;
use Carbon\Translator;
use Closure;
use DateTimeInterface;
use DateTimeZone;
use Exception;
use ReturnTypeWillChange;
/**
* Trait Creator.
*
* Static creators.
*
* Depends on the following methods:
*
* @method static Carbon|CarbonImmutable getTestNow()
*/
trait Creator
{
use ObjectInitialisation;
/**
* The errors that can occur.
*
* @var array
*/
protected static $lastErrors;
/**
* 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.
*
* @param DateTimeInterface|string|null $time
* @param DateTimeZone|string|null $tz
*
* @throws InvalidFormatException
*/
public function __construct($time = null, $tz = null)
{
if ($time instanceof DateTimeInterface) {
$time = $this->constructTimezoneFromDateTime($time, $tz)->format('Y-m-d H:i:s.u');
}
if (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 = empty($time) || $time === 'now';
if (method_exists(static::class, 'hasTestNow') &&
method_exists(static::class, 'getTestNow') &&
static::hasTestNow() &&
($isNow || static::hasRelativeKeywords($time))
) {
static::mockConstructorParameters($time, $tz);
}
// Work-around for PHP bug https://bugs.php.net/bug.php?id=67127
if (!str_contains((string) .1, '.')) {
$locale = setlocale(LC_NUMERIC, '0'); // @codeCoverageIgnore
setlocale(LC_NUMERIC, 'C'); // @codeCoverageIgnore
}
try {
parent::__construct($time ?: 'now', static::safeCreateDateTimeZone($tz) ?: null);
} catch (Exception $exception) {
throw new InvalidFormatException($exception->getMessage(), 0, $exception);
}
$this->constructedObjectId = spl_object_hash($this);
if (isset($locale)) {
setlocale(LC_NUMERIC, $locale); // @codeCoverageIgnore
}
self::setLastErrors(parent::getLastErrors());
}
/**
* Get timezone from a datetime instance.
*
* @param DateTimeInterface $date
* @param DateTimeZone|string|null $tz
*
* @return DateTimeInterface
*/
private function constructTimezoneFromDateTime(DateTimeInterface $date, &$tz)
{
if ($tz !== null) {
$safeTz = static::safeCreateDateTimeZone($tz);
if ($safeTz) {
return $date->setTimezone($safeTz);
}
return $date;
}
$tz = $date->getTimezone();
return $date;
}
/**
* Update constructedObjectId on cloned.
*/
public function __clone()
{
$this->constructedObjectId = spl_object_hash($this);
}
/**
* Create a Carbon instance from a DateTime one.
*
* @param DateTimeInterface $date
*
* @return static
*/
public static function instance($date)
{
if ($date instanceof static) {
return clone $date;
}
static::expectDateTime($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().
*
* @param string|DateTimeInterface|null $time
* @param DateTimeZone|string|null $tz
*
* @throws InvalidFormatException
*
* @return static
*/
public static function rawParse($time = null, $tz = null)
{
if ($time instanceof DateTimeInterface) {
return static::instance($time);
}
try {
return new static($time, $tz);
} catch (Exception $exception) {
$date = @static::now($tz)->change($time);
if (!$date) {
throw new InvalidFormatException("Could not parse '$time': ".$exception->getMessage(), 0, $exception);
}
return $date;
}
}
/**
* 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().
*
* @param string|DateTimeInterface|null $time
* @param DateTimeZone|string|null $tz
*
* @throws InvalidFormatException
*
* @return static
*/
public static function parse($time = null, $tz = null)
{
$function = static::$parseFunction;
if (!$function) {
return static::rawParse($time, $tz);
}
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|null $tz optional timezone for the new instance.
*
* @throws InvalidFormatException
*
* @return static
*/
public static function parseFromLocale($time, $locale = null, $tz = null)
{
return static::rawParse(static::translateTimeString($time, $locale, 'en'), $tz);
}
/**
* Get a Carbon instance for the current date and time.
*
* @param DateTimeZone|string|null $tz
*
* @return static
*/
public static function now($tz = null)
{
return new static(null, $tz);
}
/**
* Create a Carbon instance for today.
*
* @param DateTimeZone|string|null $tz
*
* @return static
*/
public static function today($tz = null)
{
return static::rawParse('today', $tz);
}
/**
* Create a Carbon instance for tomorrow.
*
* @param DateTimeZone|string|null $tz
*
* @return static
*/
public static function tomorrow($tz = null)
{
return static::rawParse('tomorrow', $tz);
}
/**
* Create a Carbon instance for yesterday.
*
* @param DateTimeZone|string|null $tz
*
* @return static
*/
public static function yesterday($tz = null)
{
return static::rawParse('yesterday', $tz);
}
/**
* Create a Carbon instance for the greatest supported date.
*
* @return static
*/
public static function maxValue()
{
if (self::$PHPIntSize === 4) {
// 32 bit
return static::createFromTimestamp(PHP_INT_MAX); // @codeCoverageIgnore
}
// 64 bit
return static::create(9999, 12, 31, 23, 59, 59);
}
/**
* Create a Carbon instance for the lowest supported date.
*
* @return static
*/
public static function minValue()
{
if (self::$PHPIntSize === 4) {
// 32 bit
return static::createFromTimestamp(~PHP_INT_MAX); // @codeCoverageIgnore
}
// 64 bit
return static::create(1, 1, 1, 0, 0, 0);
}
private static function assertBetween($unit, $value, $min, $max)
{
if (static::isStrictModeEnabled() && ($value < $min || $value > $max)) {
throw new OutOfRangeException($unit, $min, $max, $value);
}
}
private static function createNowInstance($tz)
{
if (!static::hasTestNow()) {
return static::now($tz);
}
$now = static::getTestNow();
if ($now instanceof Closure) {
return $now(static::now($tz));
}
return $now->avoidMutation()->tz($tz);
}
/**
* 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 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|null $tz
*
* @throws InvalidFormatException
*
* @return static|false
*/
public static function create($year = 0, $month = 1, $day = 1, $hour = 0, $minute = 0, $second = 0, $tz = null)
{
if ((\is_string($year) && !is_numeric($year)) || $year instanceof DateTimeInterface) {
return static::parse($year, $tz ?: (\is_string($month) || $month instanceof DateTimeZone ? $month : null));
}
$defaults = null;
$getDefault = function ($unit) use ($tz, &$defaults) {
if ($defaults === null) {
$now = self::createNowInstance($tz);
$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), $tz);
if ($fixYear !== null) {
$instance = $instance->addYears($fixYear);
}
return $instance;
}
/**
* 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|null $tz
*
* @throws InvalidDateException
*
* @return static|false
*/
public static function createSafe($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $tz = null)
{
$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 false;
}
}
$instance = static::create($year, $month, $day, $hour, $minute, $second, $tz);
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 false;
}
}
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|null $tz
*
* @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, $tz = null): self
{
$initialStrictMode = static::isStrictModeEnabled();
static::useStrictMode(true);
try {
$date = static::create($year, $month, $day, $hour, $minute, $second, $tz);
} 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|null $tz
*
* @throws InvalidFormatException
*
* @return static
*/
public static function createFromDate($year = null, $month = null, $day = null, $tz = null)
{
return static::create($year, $month, $day, null, null, null, $tz);
}
/**
* 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|null $tz
*
* @throws InvalidFormatException
*
* @return static
*/
public static function createMidnightDate($year = null, $month = null, $day = null, $tz = null)
{
return static::create($year, $month, $day, 0, 0, 0, $tz);
}
/**
* 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|null $tz
*
* @throws InvalidFormatException
*
* @return static
*/
public static function createFromTime($hour = 0, $minute = 0, $second = 0, $tz = null)
{
return static::create(null, null, null, $hour, $minute, $second, $tz);
}
/**
* Create a Carbon instance from a time string. The date portion is set to today.
*
* @param string $time
* @param DateTimeZone|string|null $tz
*
* @throws InvalidFormatException
*
* @return static
*/
public static function createFromTimeString($time, $tz = null)
{
return static::today($tz)->setTimeFromTimeString($time);
}
/**
* @param string $format Datetime format
* @param string $time
* @param DateTimeZone|string|false|null $originalTz
*
* @return DateTimeInterface|false
*/
private static function createFromFormatAndTimezone($format, $time, $originalTz)
{
// Work-around for https://bugs.php.net/bug.php?id=75577
// @codeCoverageIgnoreStart
if (version_compare(PHP_VERSION, '7.3.0-dev', '<')) {
$format = str_replace('.v', '.u', $format);
}
// @codeCoverageIgnoreEnd
if ($originalTz === null) {
return parent::createFromFormat($format, (string) $time);
}
$tz = \is_int($originalTz)
? @timezone_name_from_abbr('', (int) ($originalTz * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE), 1)
: $originalTz;
$tz = static::safeCreateDateTimeZone($tz, $originalTz);
if ($tz === false) {
return false;
}
return parent::createFromFormat($format, (string) $time, $tz);
}
/**
* Create a Carbon instance from a specific format.
*
* @param string $format Datetime format
* @param string $time
* @param DateTimeZone|string|false|null $tz
*
* @throws InvalidFormatException
*
* @return static|false
*/
public static function rawCreateFromFormat($format, $time, $tz = null)
{
// 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);
}
// First attempt to create an instance, so that error messages are based on the unmodified format.
$date = self::createFromFormatAndTimezone($format, $time, $tz);
$lastErrors = parent::getLastErrors();
/** @var \Carbon\CarbonImmutable|\Carbon\Carbon|null $mock */
$mock = static::getMockedTestNow($tz);
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 ($tz === null && !preg_match("/{$nonEscaped}[eOPT]/", $nonIgnored)) {
$tz = clone $mock->getTimezone();
}
// Set microseconds to zero to match behavior of DateTime::createFromFormat()
// See https://bugs.php.net/bug.php?id=74332
$mock = $mock->copy()->microsecond(0);
// Prepend mock datetime only if the format does not contain non escaped unix epoch reset flag.
if (!preg_match("/{$nonEscaped}[!|]/", $format)) {
$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, $tz);
}
if ($date instanceof DateTimeInterface) {
$instance = static::instance($date);
$instance::setLastErrors($lastErrors);
return $instance;
}
if (static::isStrictModeEnabled()) {
throw new InvalidFormatException(implode(PHP_EOL, $lastErrors['errors']));
}
return false;
}
/**
* Create a Carbon instance from a specific format.
*
* @param string $format Datetime format
* @param string $time
* @param DateTimeZone|string|false|null $tz
*
* @throws InvalidFormatException
*
* @return static|false
*/
#[ReturnTypeWillChange]
public static function createFromFormat($format, $time, $tz = null)
{
$function = static::$createFromFormatFunction;
if (!$function) {
return static::rawCreateFromFormat($format, $time, $tz);
}
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|false|null $tz 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 \Symfony\Component\Translation\TranslatorInterface $translator optional custom translator to use for macro-formats
*
* @throws InvalidFormatException
*
* @return static|false
*/
public static function createFromIsoFormat($format, $time, $tz = null, $locale = 'en', $translator = null)
{
$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 ?: Translator::get($locale);
$formats = [
'LT' => static::getTranslationMessageWith($translator, 'formats.LT', $locale, 'h:mm A'),
'LTS' => static::getTranslationMessageWith($translator, 'formats.LTS', $locale, 'h:mm:ss A'),
'L' => static::getTranslationMessageWith($translator, 'formats.L', $locale, 'MM/DD/YYYY'),
'LL' => static::getTranslationMessageWith($translator, 'formats.LL', $locale, 'MMMM D, YYYY'),
'LLL' => static::getTranslationMessageWith($translator, 'formats.LLL', $locale, 'MMMM D, YYYY h:mm A'),
'LLLL' => static::getTranslationMessageWith($translator, 'formats.LLLL', $locale, 'dddd, MMMM D, YYYY h:mm A'),
];
}
return $formats[$code] ?? preg_replace_callback(
'/MMMM|MM|DD|dddd/',
function ($code) {
return 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, $tz);
}
/**
* 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|false|null $tz
*
* @throws InvalidFormatException
*
* @return static|false
*/
public static function createFromLocaleFormat($format, $locale, $time, $tz = null)
{
return static::rawCreateFromFormat($format, static::translateTimeString($time, $locale, 'en'), $tz);
}
/**
* 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|false|null $tz
*
* @throws InvalidFormatException
*
* @return static|false
*/
public static function createFromLocaleIsoFormat($format, $locale, $time, $tz = null)
{
$time = static::translateTimeString($time, $locale, 'en', CarbonInterface::TRANSLATE_MONTHS | CarbonInterface::TRANSLATE_DAYS | CarbonInterface::TRANSLATE_MERIDIEM);
return static::createFromIsoFormat($format, $time, $tz, $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)
{
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)
{
if (\is_array($lastErrors) || $lastErrors === false) {
static::$lastErrors = \is_array($lastErrors) ? $lastErrors : [
'warning_count' => 0,
'warnings' => [],
'error_count' => 0,
'errors' => [],
];
}
}
/**
* {@inheritdoc}
*
* @return array
*/
#[ReturnTypeWillChange]
public static function getLastErrors()
{
return static::$lastErrors;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,61 @@
<?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 DeprecatedProperties
{
/**
* the day of week in current locale LC_TIME
*
* @var string
*
* @deprecated It uses OS language package and strftime() which is deprecated since PHP 8.1.
* Use ->isoFormat('MMM') instead.
* Deprecated since 2.55.0
*/
public $localeDayOfWeek;
/**
* the abbreviated day of week in current locale LC_TIME
*
* @var string
*
* @deprecated It uses OS language package and strftime() which is deprecated since PHP 8.1.
* Use ->isoFormat('dddd') instead.
* Deprecated since 2.55.0
*/
public $shortLocaleDayOfWeek;
/**
* the month in current locale LC_TIME
*
* @var string
*
* @deprecated It uses OS language package and strftime() which is deprecated since PHP 8.1.
* Use ->isoFormat('ddd') instead.
* Deprecated since 2.55.0
*/
public $localeMonth;
/**
* the abbreviated month in current locale LC_TIME
*
* @var string
*
* @deprecated It uses OS language package and strftime() which is deprecated since PHP 8.1.
* Use ->isoFormat('MMMM') instead.
* Deprecated since 2.55.0
*/
public $shortLocaleMonth;
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,57 @@
<?php
/**
* 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)
{
$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($precision, $function)
{
$unit = 'second';
if ($precision instanceof DateInterval) {
$precision = (string) CarbonInterval::instance($precision);
}
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,93 @@
<?php
/**
* 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 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) {
return $carbonDate->setDateTimeFrom(($this->step)($carbonDate->avoidMutation(), $negated));
}
if ($negated) {
return $carbonDate->rawSub($this);
}
return $carbonDate->rawAdd($this);
}
/**
* Convert DateTimeImmutable instance to CarbonImmutable instance and DateTime instance to Carbon instance.
*
* @param DateTimeInterface $dateTime
*
* @return Carbon|CarbonImmutable
*/
private function resolveCarbon(DateTimeInterface $dateTime)
{
if ($dateTime instanceof DateTimeImmutable) {
return CarbonImmutable::instance($dateTime);
}
return Carbon::instance($dateTime);
}
}

View File

@@ -0,0 +1,838 @@
<?php
/**
* 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\Component\Translation\TranslatorInterface;
use Symfony\Contracts\Translation\LocaleAwareInterface;
use Symfony\Contracts\Translation\TranslatorInterface as ContractsTranslatorInterface;
if (interface_exists('Symfony\\Contracts\\Translation\\TranslatorInterface') &&
!interface_exists('Symfony\\Component\\Translation\\TranslatorInterface')
) {
class_alias(
'Symfony\\Contracts\\Translation\\TranslatorInterface',
'Symfony\\Component\\Translation\\TranslatorInterface'
);
}
/**
* Trait Localization.
*
* Embed default and locale translators and translation base methods.
*/
trait Localization
{
/**
* Default translator.
*
* @var \Symfony\Component\Translation\TranslatorInterface
*/
protected static $translator;
/**
* Specific translator of the current instance.
*
* @var \Symfony\Component\Translation\TranslatorInterface
*/
protected $localTranslator;
/**
* Options for diffForHumans().
*
* @var int
*/
protected static $humanDiffOptions = CarbonInterface::NO_ZERO_DIFF;
/**
* @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
* You should rather use the ->settings() method.
* @see settings
*
* @param int $humanDiffOptions
*/
public static function setHumanDiffOptions($humanDiffOptions)
{
static::$humanDiffOptions = $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
*
* @param int $humanDiffOption
*/
public static function enableHumanDiffOption($humanDiffOption)
{
static::$humanDiffOptions = static::getHumanDiffOptions() | $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
*
* @param int $humanDiffOption
*/
public static function disableHumanDiffOption($humanDiffOption)
{
static::$humanDiffOptions = static::getHumanDiffOptions() & ~$humanDiffOption;
}
/**
* Return default humanDiff() options (merged flags as integer).
*
* @return int
*/
public static function getHumanDiffOptions()
{
return static::$humanDiffOptions;
}
/**
* Get the default translator instance in use.
*
* @return \Symfony\Component\Translation\TranslatorInterface
*/
public static function getTranslator()
{
return static::translator();
}
/**
* Set the default translator instance to use.
*
* @param \Symfony\Component\Translation\TranslatorInterface $translator
*
* @return void
*/
public static function setTranslator(TranslatorInterface $translator)
{
static::$translator = $translator;
}
/**
* Return true if the current instance has its own translator.
*
* @return bool
*/
public function hasLocalTranslator()
{
return isset($this->localTranslator);
}
/**
* Get the translator of the current instance or the default if none set.
*
* @return \Symfony\Component\Translation\TranslatorInterface
*/
public function getLocalTranslator()
{
return $this->localTranslator ?: static::translator();
}
/**
* Set the translator for the current instance.
*
* @param \Symfony\Component\Translation\TranslatorInterface $translator
*
* @return $this
*/
public function setLocalTranslator(TranslatorInterface $translator)
{
$this->localTranslator = $translator;
return $this;
}
/**
* Returns raw translation message for a given key.
*
* @param \Symfony\Component\Translation\TranslatorInterface $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
*/
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 \Symfony\Component\Translation\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 \Symfony\Component\Translation\TranslatorInterface $translator
* @param string $key
* @param array $parameters
* @param null $number
*
* @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%'];
}
// @codeCoverageIgnoreStart
$choice = $translator instanceof ContractsTranslatorInterface
? $translator->trans($key, $parameters)
: $translator->transChoice($key, $number, $parameters);
// @codeCoverageIgnoreEnd
return (string) $choice;
}
/**
* Translate using translation string or callback available.
*
* @param string $key
* @param array $parameters
* @param string|int|float|null $number
* @param \Symfony\Component\Translation\TranslatorInterface|null $translator
* @param bool $altNumbers
*
* @return string
*/
public function translate(string $key, array $parameters = [], $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($number, $this->translateNumber($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($timeString, $from = null, $to = null, $mode = CarbonInterface::TRANSLATE_ALL)
{
// Fallback source and destination locales
$from = $from ?: static::getLocale();
$to = $to ?: 'en';
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, 12, $timeString) : [],
$mode & CarbonInterface::TRANSLATE_MONTHS ? static::getTranslationArray($messages['months_short'] ?? [], 12, $timeString) : [],
$mode & CarbonInterface::TRANSLATE_DAYS ? static::getTranslationArray($weekdays, 7, $timeString) : [],
$mode & CarbonInterface::TRANSLATE_DAYS ? static::getTranslationArray($messages['weekdays_short'] ?? [], 7, $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 < 12 ? 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($timeString, $to = null)
{
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, ...$fallbackLocales)
{
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()
{
return static::getLocaleAwareTranslator()->getLocale();
}
/**
* Set the current translator locale and indicate if the source locale file exists.
* Pass 'auto' as locale to use closest language from the current LC_TIME locale.
*
* @param string $locale locale ex. en
*
* @return bool
*/
public static function setLocale($locale)
{
return static::getLocaleAwareTranslator()->setLocale($locale) !== false;
}
/**
* Set the fallback locale.
*
* @see https://symfony.com/doc/current/components/translation.html#fallback-locales
*
* @param string $locale
*/
public static function setFallbackLocale($locale)
{
$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
*
* @return string|null
*/
public static function getFallbackLocale()
{
$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($locale, $func)
{
$currentLocale = static::getLocale();
$result = $func(static::setLocale($locale) ? static::getLocale() : false, static::translator());
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($locale)
{
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($locale)
{
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($locale)
{
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($locale)
{
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;
}
/**
* Initialize the default translator instance if necessary.
*
* @return \Symfony\Component\Translation\TranslatorInterface
*/
protected static function translator()
{
if (static::$translator === null) {
static::$translator = Translator::get();
}
return static::$translator;
}
/**
* 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.
*
* @param null $translator
*
* @return string|null
*/
protected function getTranslatorLocale($translator = null): ?string
{
if (\func_num_args() === 0) {
$translator = $this->getLocalTranslator();
}
$translator = static::getLocaleAwareTranslator($translator);
return $translator ? $translator->getLocale() : null;
}
/**
* 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::translator();
}
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) // @codeCoverageIgnore
: $catalogue->get($id, $domain);
}
/**
* 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,136 @@
<?php
/**
* 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 Macros.
*
* Allows users to register macros within the Carbon class.
*/
trait Macro
{
use Mixin;
/**
* The registered macros.
*
* @var array
*/
protected static $globalMacros = [];
/**
* The registered generic macros.
*
* @var array
*/
protected static $globalGenericMacros = [];
/**
* Register a custom macro.
*
* @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();
* ```
*
* @param string $name
* @param object|callable $macro
*
* @return void
*/
public static function macro($name, $macro)
{
static::$globalMacros[$name] = $macro;
}
/**
* Remove all macros and generic macros.
*/
public static function resetMacros()
{
static::$globalMacros = [];
static::$globalGenericMacros = [];
}
/**
* Register a custom macro.
*
* @param object|callable $macro
* @param int $priority marco with higher priority is tried first
*
* @return void
*/
public static function genericMacro($macro, $priority = 0)
{
if (!isset(static::$globalGenericMacros[$priority])) {
static::$globalGenericMacros[$priority] = [];
krsort(static::$globalGenericMacros, SORT_NUMERIC);
}
static::$globalGenericMacros[$priority][] = $macro;
}
/**
* Checks if macro is registered globally.
*
* @param string $name
*
* @return bool
*/
public static function hasMacro($name)
{
return isset(static::$globalMacros[$name]);
}
/**
* Get the raw callable macro registered globally for a given name.
*
* @param string $name
*
* @return callable|null
*/
public static function getMacro($name)
{
return static::$globalMacros[$name] ?? null;
}
/**
* Checks if macro is registered globally or locally.
*
* @param string $name
*
* @return bool
*/
public function hasLocalMacro($name)
{
return ($this->localMacros && isset($this->localMacros[$name])) || static::hasMacro($name);
}
/**
* Get the raw callable macro registered globally or locally for a given name.
*
* @param string $name
*
* @return callable|null
*/
public function getLocalMacro($name)
{
return ($this->localMacros ?? [])[$name] ?? static::getMacro($name);
}
}

View File

@@ -0,0 +1,33 @@
<?php
/**
* 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,191 @@
<?php
/**
* 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 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.
*
* @var array
*/
protected static $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";
* ```
*
* @param object|string $mixin
*
* @throws ReflectionException
*
* @return void
*/
public static function mixin($mixin)
{
\is_string($mixin) && trait_exists($mixin)
? self::loadMixinTrait($mixin)
: self::loadMixinClass($mixin);
}
/**
* @param object|string $mixin
*
* @throws ReflectionException
*/
private static function loadMixinClass($mixin)
{
$methods = (new ReflectionClass($mixin))->getMethods(
ReflectionMethod::IS_PUBLIC | ReflectionMethod::IS_PROTECTED
);
foreach ($methods as $method) {
if ($method->isConstructor() || $method->isDestructor()) {
continue;
}
$method->setAccessible(true);
static::macro($method->name, $method->invoke($mixin));
}
}
/**
* @param string $trait
*/
private static function loadMixinTrait($trait)
{
$context = eval(self::getAnonymousClassCodeForTrait($trait));
$className = \get_class($context);
foreach (self::getMixableMethods($context) as $name) {
$closureBase = Closure::fromCallable([$context, $name]);
static::macro($name, function () use ($closureBase, $className) {
/** @phpstan-ignore-next-line */
$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 $throwable) { // @codeCoverageIgnore
$closure = $closureBase; // @codeCoverageIgnore
}
// in case of errors not converted into exceptions
$closure = $closure ?: $closureBase;
return $closure(...\func_get_args());
});
}
}
private static function getAnonymousClassCodeForTrait(string $trait)
{
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.
*
* @param static|null $context
* @param callable $callable
*
* @throws Throwable
*
* @return mixed
*/
protected static function bindMacroContext($context, callable $callable)
{
static::$macroContextStack[] = $context;
$exception = null;
$result = null;
try {
$result = $callable();
} catch (Throwable $throwable) {
$exception = $throwable;
}
array_pop(static::$macroContextStack);
if ($exception) {
throw $exception;
}
return $result;
}
/**
* Return the current context from inside a macro callee or a null if static.
*
* @return static|null
*/
protected static function context()
{
return end(static::$macroContextStack) ?: null;
}
/**
* Return the current context from inside a macro callee or a new one if static.
*
* @return static
*/
protected static function this()
{
return end(static::$macroContextStack) ?: new static();
}
}

View File

@@ -0,0 +1,472 @@
<?php
/**
* 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 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->diffInRealMicroseconds($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->diffInRealMicroseconds($date1) < $this->diffInRealMicroseconds($date2) ? $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->diffInRealMicroseconds($date1) > $this->diffInRealMicroseconds($date2) ? $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|false
*/
#[ReturnTypeWillChange]
public function modify($modify)
{
return parent::modify((string) $modify);
}
/**
* 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,71 @@
<?php
/**
* 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.
*
* @return bool
*/
public static function isMutable()
{
return false;
}
/**
* Returns true if the current class/instance is immutable.
*
* @return bool
*/
public static function isImmutable()
{
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,22 @@
<?php
/**
* 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,471 @@
<?php
/**
* 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 \Carbon\Carbon|\Carbon\CarbonImmutable shiftTimezone($timezone) Set the timezone
*/
trait Options
{
use Localization;
/**
* Customizable PHP_INT_SIZE override.
*
* @var int
*/
public static $PHPIntSize = PHP_INT_SIZE;
/**
* First day of week.
*
* @var int|string
*/
protected static $weekStartsAt = CarbonInterface::MONDAY;
/**
* Last day of week.
*
* @var int|string
*/
protected static $weekEndsAt = CarbonInterface::SUNDAY;
/**
* Days of weekend.
*
* @var array
*/
protected static $weekendDays = [
CarbonInterface::SATURDAY,
CarbonInterface::SUNDAY,
];
/**
* Format regex patterns.
*
* @var array<string, string>
*/
protected static $regexFormats = [
'd' => '(3[01]|[12][0-9]|0[1-9])',
'D' => '(Sun|Mon|Tue|Wed|Thu|Fri|Sat)',
'j' => '([123][0-9]|[1-9])',
'l' => '([a-zA-Z]{2,})',
'N' => '([1-7])',
'S' => '(st|nd|rd|th)',
'w' => '([0-6])',
'z' => '(36[0-5]|3[0-5][0-9]|[12][0-9]{2}|[1-9]?[0-9])',
'W' => '(5[012]|[1-4][0-9]|0?[1-9])',
'F' => '([a-zA-Z]{2,})',
'm' => '(1[012]|0[1-9])',
'M' => '([a-zA-Z]{3})',
'n' => '(1[012]|[1-9])',
't' => '(2[89]|3[01])',
'L' => '(0|1)',
'o' => '([1-9][0-9]{0,4})',
'Y' => '([1-9]?[0-9]{4})',
'y' => '([0-9]{2})',
'a' => '(am|pm)',
'A' => '(AM|PM)',
'B' => '([0-9]{3})',
'g' => '(1[012]|[1-9])',
'G' => '(2[0-3]|1?[0-9])',
'h' => '(1[012]|0[1-9])',
'H' => '(2[0-3]|[01][0-9])',
'i' => '([0-5][0-9])',
's' => '([0-5][0-9])',
'u' => '([0-9]{1,6})',
'v' => '([0-9]{1,3})',
'e' => '([a-zA-Z]{1,5})|([a-zA-Z]*\\/[a-zA-Z]*)',
'I' => '(0|1)',
'O' => '([+-](1[012]|0[0-9])[0134][05])',
'P' => '([+-](1[012]|0[0-9]):[0134][05])',
'p' => '(Z|[+-](1[012]|0[0-9]):[0134][05])',
'T' => '([a-zA-Z]{1,5})',
'Z' => '(-?[1-5]?[0-9]{1,4})',
'U' => '([0-9]*)',
// The formats below are combinations of the above formats.
'c' => '(([1-9]?[0-9]{4})-(1[012]|0[1-9])-(3[01]|[12][0-9]|0[1-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])[+-](1[012]|0[0-9]):([0134][05]))', // Y-m-dTH:i:sP
'r' => '(([a-zA-Z]{3}), ([123][0-9]|0[1-9]) ([a-zA-Z]{3}) ([1-9]?[0-9]{4}) (2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9]) [+-](1[012]|0[0-9])([0134][05]))', // D, d M Y H:i:s O
];
/**
* Format modifiers (such as available in createFromFormat) regex patterns.
*
* @var array
*/
protected static $regexFormatModifiers = [
'*' => '.+',
' ' => '[ ]',
'#' => '[;:\\/.,()-]',
'?' => '([^a]|[a])',
'!' => '',
'|' => '',
'+' => '',
];
/**
* Indicates if months should be calculated with overflow.
* Global setting.
*
* @var bool
*/
protected static $monthsOverflow = true;
/**
* Indicates if years should be calculated with overflow.
* Global setting.
*
* @var bool
*/
protected static $yearsOverflow = true;
/**
* Indicates if the strict mode is in use.
* Global setting.
*
* @var bool
*/
protected static $strictModeEnabled = true;
/**
* 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;
/**
* Indicates if months should be calculated with overflow.
* Specific setting.
*
* @var bool|null
*/
protected $localMonthsOverflow;
/**
* Indicates if years should be calculated with overflow.
* Specific setting.
*
* @var bool|null
*/
protected $localYearsOverflow;
/**
* Indicates if the strict mode is in use.
* Specific setting.
*
* @var bool|null
*/
protected $localStrictModeEnabled;
/**
* Options for diffForHumans and forHumans methods.
*
* @var bool|null
*/
protected $localHumanDiffOptions;
/**
* Format to use on string cast.
*
* @var string|null
*/
protected $localToStringFormat;
/**
* Format to use on JSON serialization.
*
* @var string|null
*/
protected $localSerializer;
/**
* Instance-specific macros.
*
* @var array|null
*/
protected $localMacros;
/**
* Instance-specific generic macros.
*
* @var array|null
*/
protected $localGenericMacros;
/**
* Function to call instead of format.
*
* @var string|callable|null
*/
protected $localFormatFunction;
/**
* @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($strictModeEnabled = true)
{
static::$strictModeEnabled = $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()
{
return static::$strictModeEnabled;
}
/**
* @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($monthsOverflow = true)
{
static::$monthsOverflow = $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()
{
static::$monthsOverflow = true;
}
/**
* Get the month overflow global behavior (can be overridden in specific instances).
*
* @return bool
*/
public static function shouldOverflowMonths()
{
return static::$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: 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($yearsOverflow = true)
{
static::$yearsOverflow = $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()
{
static::$yearsOverflow = true;
}
/**
* Get the month overflow global behavior (can be overridden in specific instances).
*
* @return bool
*/
public static function shouldOverflowYears()
{
return static::$yearsOverflow;
}
/**
* 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)
{
$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);
}
if (isset($settings['innerTimezone'])) {
return $this->setTimezone($settings['innerTimezone']);
}
if (isset($settings['timezone'])) {
return $this->shiftTimezone($settings['timezone']);
}
return $this;
}
/**
* Returns current local settings.
*
* @return array
*/
public function getSettings()
{
$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) {
$settings[$key] = $value;
}
}
return $settings;
}
/**
* Show truthy properties on var_dump().
*
* @return array
*/
public function __debugInfo()
{
$infos = array_filter(get_object_vars($this), function ($var) {
return $var;
});
foreach (['dumpProperties', 'constructedObjectId'] as $property) {
if (isset($infos[$property])) {
unset($infos[$property]);
}
}
$this->addExtraDebugInfos($infos);
return $infos;
}
protected function addExtraDebugInfos(&$infos): void
{
if ($this instanceof DateTimeInterface) {
try {
if (!isset($infos['date'])) {
$infos['date'] = $this->format(CarbonInterface::MOCK_DATETIME_FORMAT);
}
if (!isset($infos['timezone'])) {
$infos['timezone'] = $this->tzName;
}
} catch (Throwable $exception) {
// noop
}
}
}
}

View File

@@ -0,0 +1,258 @@
<?php
/**
* 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;
/**
* Trait Rounding.
*
* Round, ceil, floor units.
*
* Depends on the following methods:
*
* @method static copy()
* @method static 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.
*
* @param string $unit
* @param float|int $precision
* @param string $function
*
* @return CarbonInterface
*/
public function roundUnit($unit, $precision = 1, $function = 'round')
{
$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;
$initialMonth = $this->month;
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->$normalizedUnit($normalizedValue);
foreach ($changes as $unit => $value) {
$result = $result->$unit($value);
}
return $normalizedUnit === 'month' && $precision <= 1 && abs($result->month - $initialMonth) === 2
// Re-run the change in case an overflow occurred
? $result->$normalizedUnit($normalizedValue)
: $result;
}
/**
* Truncate the current instance at the given unit with given precision if specified.
*
* @param string $unit
* @param float|int $precision
*
* @return CarbonInterface
*/
public function floorUnit($unit, $precision = 1)
{
return $this->roundUnit($unit, $precision, 'floor');
}
/**
* Ceil the current instance at the given unit with given precision if specified.
*
* @param string $unit
* @param float|int $precision
*
* @return CarbonInterface
*/
public function ceilUnit($unit, $precision = 1)
{
return $this->roundUnit($unit, $precision, 'ceil');
}
/**
* Round the current instance second with given precision if specified.
*
* @param float|int|string|\DateInterval|null $precision
* @param string $function
*
* @return CarbonInterface
*/
public function round($precision = 1, $function = 'round')
{
return $this->roundWith($precision, $function);
}
/**
* Round the current instance second with given precision if specified.
*
* @param float|int|string|\DateInterval|null $precision
*
* @return CarbonInterface
*/
public function floor($precision = 1)
{
return $this->round($precision, 'floor');
}
/**
* Ceil the current instance second with given precision if specified.
*
* @param float|int|string|\DateInterval|null $precision
*
* @return CarbonInterface
*/
public function ceil($precision = 1)
{
return $this->round($precision, 'ceil');
}
/**
* Round the current instance week.
*
* @param int $weekStartsAt optional start allow you to specify the day of week to use to start the week
*
* @return CarbonInterface
*/
public function roundWeek($weekStartsAt = null)
{
return $this->closest(
$this->avoidMutation()->floorWeek($weekStartsAt),
$this->avoidMutation()->ceilWeek($weekStartsAt)
);
}
/**
* Truncate the current instance week.
*
* @param int $weekStartsAt optional start allow you to specify the day of week to use to start the week
*
* @return CarbonInterface
*/
public function floorWeek($weekStartsAt = null)
{
return $this->startOfWeek($weekStartsAt);
}
/**
* Ceil the current instance week.
*
* @param int $weekStartsAt optional start allow you to specify the day of week to use to start the week
*
* @return CarbonInterface
*/
public function ceilWeek($weekStartsAt = null)
{
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,304 @@
<?php
/**
* 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 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;
/**
* The custom Carbon JSON serializer.
*
* @var callable|null
*/
protected static $serializer;
/**
* List of key to use for dump/serialization.
*
* @var string[]
*/
protected $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.
*
* @return string
*/
public function serialize()
{
return serialize($this);
}
/**
* Create an instance from a serialized string.
*
* @param string $value
*
* @throws InvalidFormatException
*
* @return static
*/
public static function fromSerialized($value)
{
$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)
{
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.
*
* @return array
*/
public function __sleep()
{
$properties = $this->getSleepProperties();
if ($this->localTranslator ?? null) {
$properties[] = 'dumpLocale';
$this->dumpLocale = $this->locale ?? null;
}
return $properties;
}
public function __serialize(): array
{
if (isset($this->timezone_type)) {
return [
'date' => $this->date ?? null,
'timezone_type' => $this->timezone_type,
'timezone' => $this->timezone ?? null,
];
}
$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)) {
$export['dumpDateProperties'] = [
'date' => $this->format('Y-m-d H:i:s.u'),
'timezone' => serialize($this->timezone ?? null),
];
}
// @codeCoverageIgnoreEnd
if ($this->localTranslator ?? null) {
$export['dumpLocale'] = $this->locale ?? null;
}
return $export;
}
/**
* Set locale if specified on unserialize() called.
*
* @return void
*/
#[ReturnTypeWillChange]
public function __wakeup()
{
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, unserialize($timezone));
} catch (Throwable $ignoredException) {
throw $exception;
}
}
// @codeCoverageIgnoreEnd
}
$this->constructedObjectId = spl_object_hash($this);
if (isset($this->dumpLocale)) {
$this->locale($this->dumpLocale);
$this->dumpLocale = null;
}
$this->cleanupDumpProperties();
}
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, unserialize($timezone));
} catch (Throwable $ignoredException) {
throw $exception;
}
}
// @codeCoverageIgnoreEnd
if (isset($data['dumpLocale'])) {
$this->locale($data['dumpLocale']);
}
}
/**
* Prepare the object for JSON serialization.
*
* @return array|string
*/
#[ReturnTypeWillChange]
public function jsonSerialize()
{
$serializer = $this->localSerializer ?? static::$serializer;
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.
*
* @param callable $callback
*
* @return void
*/
public static function serializeUsing($callback)
{
static::$serializer = $callback;
}
/**
* 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()
{
if (PHP_VERSION < 8.2) {
foreach ($this->dumpProperties as $property) {
if (isset($this->$property)) {
unset($this->$property);
}
}
}
return $this;
}
private function getSleepProperties(): array
{
$properties = $this->dumpProperties;
// @codeCoverageIgnoreStart
if (!\extension_loaded('msgpack')) {
return $properties;
}
if (isset($this->constructedObjectId)) {
$this->dumpDateProperties = [
'date' => $this->format('Y-m-d H:i:s.u'),
'timezone' => serialize($this->timezone ?? null),
];
$properties[] = 'dumpDateProperties';
}
return $properties;
// @codeCoverageIgnoreEnd
}
}

View File

@@ -0,0 +1,226 @@
<?php
/**
* 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 Closure;
use DateTimeImmutable;
use DateTimeInterface;
use InvalidArgumentException;
use Throwable;
trait Test
{
///////////////////////////////////////////////////////////////////
///////////////////////// TESTING AIDS ////////////////////////////
///////////////////////////////////////////////////////////////////
/**
* A test Carbon instance to be returned when now instances are created.
*
* @var Closure|static|null
*/
protected static $testNow;
/**
* The timezone to resto to when clearing the time mock.
*
* @var string|null
*/
protected static $testDefaultTimezone;
/**
* 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($testNow = null)
{
static::$testNow = $testNow instanceof self || $testNow instanceof Closure
? $testNow
: static::make($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, $tz = null)
{
if ($testNow) {
self::$testDefaultTimezone = self::$testDefaultTimezone ?? date_default_timezone_get();
}
$useDateInstanceTimezone = $testNow instanceof DateTimeInterface;
if ($useDateInstanceTimezone) {
self::setDefaultTimezone($testNow->getTimezone()->getName(), $testNow);
}
static::setTestNow($testNow);
if (!$useDateInstanceTimezone) {
$now = static::getMockedTestNow(\func_num_args() === 1 ? null : $tz);
$tzName = $now ? $now->tzName : null;
self::setDefaultTimezone($tzName ?? self::$testDefaultTimezone ?? 'UTC', $now);
}
if (!$testNow) {
self::$testDefaultTimezone = null;
}
}
/**
* 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.
*
* @param DateTimeInterface|Closure|static|string|false|null $testNow real or mock Carbon instance
* @param Closure|null $callback
*
* @return mixed
*/
public static function withTestNow($testNow = null, $callback = null)
{
static::setTestNow($testNow);
try {
$result = $callback();
} finally {
static::setTestNow();
}
return $result;
}
/**
* Get the Carbon instance (real or mock) to be returned when a "now"
* instance is created.
*
* @return Closure|static the current instance used for testing
*/
public static function getTestNow()
{
return static::$testNow;
}
/**
* 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()
{
return static::getTestNow() !== null;
}
/**
* Get the mocked date passed in setTestNow() and if it's a Closure, execute it.
*
* @param string|\DateTimeZone $tz
*
* @return \Carbon\CarbonImmutable|\Carbon\Carbon|null
*/
protected static function getMockedTestNow($tz)
{
$testNow = static::getTestNow();
if ($testNow instanceof Closure) {
$realNow = new DateTimeImmutable('now');
$testNow = $testNow(static::parse(
$realNow->format('Y-m-d H:i:s.u'),
$tz ?: $realNow->getTimezone()
));
}
/* @var \Carbon\CarbonImmutable|\Carbon\Carbon|null $testNow */
return $testNow instanceof CarbonInterface
? $testNow->avoidMutation()->tz($tz)
: $testNow;
}
protected static function mockConstructorParameters(&$time, $tz)
{
/** @var \Carbon\CarbonImmutable|\Carbon\Carbon $testInstance */
$testInstance = clone static::getMockedTestNow($tz);
if (static::hasRelativeKeywords($time)) {
$testInstance = $testInstance->modify($time);
}
$time = $testInstance instanceof self
? $testInstance->rawFormat(static::MOCK_DATETIME_FORMAT)
: $testInstance->format(static::MOCK_DATETIME_FORMAT);
}
private static function setDefaultTimezone($timezone, DateTimeInterface $date = null)
{
$previous = null;
$success = false;
try {
$success = date_default_timezone_set($timezone);
} catch (Throwable $exception) {
$previous = $exception;
}
if (!$success) {
$suggestion = @CarbonTimeZone::create($timezone)->toRegionName($date);
throw new InvalidArgumentException(
"Timezone ID '$timezone' is invalid".
($suggestion && $suggestion !== $timezone ? ", did you mean '$suggestion'?" : '.')."\n".
"It must be one of the IDs from DateTimeZone::listIdentifiers(),\n".
'For the record, hours/minutes offset are relevant only for a particular moment, '.
'but not as a default timezone.',
0,
$previous
);
}
}
}

View File

@@ -0,0 +1,198 @@
<?php
/**
* 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 Timestamp.
*/
trait Timestamp
{
/**
* Create a Carbon instance from a timestamp and set the timezone (use default one if not specified).
*
* Timestamp input can be given as int, float or a string containing one or more numbers.
*
* @param float|int|string $timestamp
* @param \DateTimeZone|string|null $tz
*
* @return static
*/
public static function createFromTimestamp($timestamp, $tz = null)
{
return static::createFromTimestampUTC($timestamp)->setTimezone($tz);
}
/**
* Create a Carbon instance from an timestamp keeping the timezone to UTC.
*
* 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 createFromTimestampUTC($timestamp)
{
[$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)
{
[$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 += $delta;
$microseconds -= $delta * static::MICROSECONDS_PER_SECOND;
$microseconds = str_pad($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.
*
* @param float|int|string $timestamp
* @param \DateTimeZone|string|null $tz
*
* @return static
*/
public static function createFromTimestampMs($timestamp, $tz = null)
{
return static::createFromTimestampMsUTC($timestamp)
->setTimezone($tz);
}
/**
* Set the instance's timestamp.
*
* Timestamp input can be given as int, float or a string containing one or more numbers.
*
* @param float|int|string $unixTimestamp
*
* @return static
*/
public function timestamp($unixTimestamp)
{
return $this->setTimestamp($unixTimestamp);
}
/**
* 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)
{
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()
{
return $this->getPreciseTimestamp(3);
}
/**
* Returns the timestamp with millisecond precision.
*
* @return int
*/
public function getTimestampMs()
{
return (int) $this->getPreciseTimestamp(3);
}
/**
* @alias getTimestamp
*
* Returns the UNIX timestamp for the current date.
*
* @return int
*/
public function unix()
{
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)
{
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,56 @@
<?php
/**
* 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 Closure;
/**
* Trait ToStringFormat.
*
* Handle global format customization for string cast of the object.
*/
trait ToStringFormat
{
/**
* Format to use for __toString method when type juggling occurs.
*
* @var string|Closure|null
*/
protected static $toStringFormat;
/**
* Reset the format used to the default when type juggling a Carbon instance to a string
*
* @return void
*/
public static function resetToStringFormat()
{
static::setToStringFormat(null);
}
/**
* @param string|Closure|null $format
*
* @return void
*
* @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.
*/
public static function setToStringFormat($format)
{
static::$toStringFormat = $format;
}
}

View File

@@ -0,0 +1,406 @@
<?php
/**
* 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\UnitException;
use Closure;
use DateInterval;
use ReturnTypeWillChange;
/**
* Trait Units.
*
* Add, subtract and set units.
*/
trait Units
{
/**
* Add seconds to the instance using timestamp. Positive $value travels
* forward while negative $value travels into the past.
*
* @param string $unit
* @param int $value
*
* @return static
*/
public function addRealUnit($unit, $value = 1)
{
switch ($unit) {
// @call addRealUnit
case 'micro':
// @call addRealUnit
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);
$tz = $this->tz;
return $this->tz('UTC')->modify("@$time.$microtime")->tz($tz);
// @call addRealUnit
case 'milli':
// @call addRealUnit
case 'millisecond':
return $this->addRealUnit('microsecond', $value * static::MICROSECONDS_PER_MILLISECOND);
// @call addRealUnit
case 'second':
break;
// @call addRealUnit
case 'minute':
$value *= static::SECONDS_PER_MINUTE;
break;
// @call addRealUnit
case 'hour':
$value *= static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE;
break;
// @call addRealUnit
case 'day':
$value *= static::HOURS_PER_DAY * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE;
break;
// @call addRealUnit
case 'week':
$value *= static::DAYS_PER_WEEK * static::HOURS_PER_DAY * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE;
break;
// @call addRealUnit
case 'month':
$value *= 30 * static::HOURS_PER_DAY * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE;
break;
// @call addRealUnit
case 'quarter':
$value *= static::MONTHS_PER_QUARTER * 30 * static::HOURS_PER_DAY * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE;
break;
// @call addRealUnit
case 'year':
$value *= 365 * static::HOURS_PER_DAY * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE;
break;
// @call addRealUnit
case 'decade':
$value *= static::YEARS_PER_DECADE * 365 * static::HOURS_PER_DAY * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE;
break;
// @call addRealUnit
case 'century':
$value *= static::YEARS_PER_CENTURY * 365 * static::HOURS_PER_DAY * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE;
break;
// @call addRealUnit
case 'millennium':
$value *= static::YEARS_PER_MILLENNIUM * 365 * static::HOURS_PER_DAY * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE;
break;
default:
if ($this->localStrictModeEnabled ?? static::isStrictModeEnabled()) {
throw new UnitException("Invalid unit for real timestamp add/sub: '$unit'");
}
return $this;
}
/* @var CarbonInterface $this */
return $this->setTimestamp((int) ($this->getTimestamp() + $value));
}
public function subRealUnit($unit, $value = 1)
{
return $this->addRealUnit($unit, -$value);
}
/**
* Returns true if a property can be changed via setter.
*
* @param string $unit
*
* @return bool
*/
public static function isModifiableUnit($unit)
{
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)
{
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 string|DateInterval|Closure|CarbonConverterInterface $unit
* @param int $value
* @param bool|null $overflow
*
* @return static
*/
#[ReturnTypeWillChange]
public function add($unit, $value = 1, $overflow = null)
{
if (\is_string($unit) && \func_num_args() === 1) {
$unit = CarbonInterval::make($unit);
}
if ($unit instanceof CarbonConverterInterface) {
return $this->resolveCarbon($unit->convertDate($this, false));
}
if ($unit instanceof Closure) {
return $this->resolveCarbon($unit($this, false));
}
if ($unit instanceof DateInterval) {
return parent::add($unit);
}
if (is_numeric($unit)) {
[$value, $unit] = [$unit, $value];
}
return $this->addUnit($unit, $value, $overflow);
}
/**
* Add given units to the current instance.
*
* @param string $unit
* @param int $value
* @param bool|null $overflow
*
* @return static
*/
public function addUnit($unit, $value = 1, $overflow = null)
{
$originalArgs = \func_get_args();
$date = $this;
if (!is_numeric($value) || !(float) $value) {
return $date->isMutable() ? $date : $date->avoidMutation();
}
$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 = static::getWeekendDays();
if ($weekendDays !== [static::SATURDAY, static::SUNDAY]) {
$absoluteValue = abs($value);
$sign = $value / max(1, $absoluteValue);
$weekDaysCount = 7 - min(6, \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;
}
$value = (int) $value;
if ($unit === 'milli' || $unit === 'millisecond') {
$unit = 'microsecond';
$value *= static::MICROSECONDS_PER_MILLISECOND;
}
// Work-around for bug https://bugs.php.net/bug.php?id=75642
if ($unit === 'micro' || $unit === 'microsecond') {
$microseconds = $this->micro + $value;
$second = (int) floor($microseconds / static::MICROSECONDS_PER_SECOND);
$microseconds %= static::MICROSECONDS_PER_SECOND;
if ($microseconds < 0) {
$microseconds += static::MICROSECONDS_PER_SECOND;
}
$date = $date->microseconds($microseconds);
$unit = 'second';
$value = $second;
}
$date = $date->modify("$value $unit");
if (isset($timeString)) {
$date = $date->setTimeFromTimeString($timeString);
} elseif (isset($canOverflow, $day) && $canOverflow && $day !== $date->day) {
$date = $date->modify('last day of previous month');
}
if (!$date) {
throw new UnitException('Unable to add unit '.var_export($originalArgs, true));
}
return $date;
}
/**
* Subtract given units to the current instance.
*
* @param string $unit
* @param int $value
* @param bool|null $overflow
*
* @return static
*/
public function subUnit($unit, $value = 1, $overflow = null)
{
return $this->addUnit($unit, -$value, $overflow);
}
/**
* Call native PHP DateTime/DateTimeImmutable sub() method.
*
* @param DateInterval $interval
*
* @return static
*/
public function rawSub(DateInterval $interval)
{
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 string|DateInterval|Closure|CarbonConverterInterface $unit
* @param int $value
* @param bool|null $overflow
*
* @return static
*/
#[ReturnTypeWillChange]
public function sub($unit, $value = 1, $overflow = null)
{
if (\is_string($unit) && \func_num_args() === 1) {
$unit = CarbonInterval::make($unit);
}
if ($unit instanceof CarbonConverterInterface) {
return $this->resolveCarbon($unit->convertDate($this, true));
}
if ($unit instanceof Closure) {
return $this->resolveCarbon($unit($this, true));
}
if ($unit instanceof DateInterval) {
return parent::sub($unit);
}
if (is_numeric($unit)) {
[$value, $unit] = [$unit, $value];
}
return $this->addUnit($unit, -(float) $value, $overflow);
}
/**
* Subtract given units or interval to the current instance.
*
* @see sub()
*
* @param string|DateInterval $unit
* @param int $value
* @param bool|null $overflow
*
* @return static
*/
public function subtract($unit, $value = 1, $overflow = null)
{
if (\is_string($unit) && \func_num_args() === 1) {
$unit = CarbonInterval::make($unit);
}
return $this->sub($unit, $value, $overflow);
}
}

View File

@@ -0,0 +1,219 @@
<?php
/**
* 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 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 static addWeeks(int $weeks = 1)
* @method static copy()
* @method static dayOfYear(int $dayOfYear)
* @method string getTranslationMessage(string $key, ?string $locale = null, ?string $default = null, $translator = null)
* @method static next(int|string $day = null)
* @method static startOfWeek(int $day = 1)
* @method static subWeeks(int $weeks = 1)
* @method static 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 ?? 1,
$dayOfYear ?? 4
);
}
/**
* 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') ?? 0;
$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);
switch ($date->weekYear(null, $dayOfWeek, $dayOfYear) - $year) {
case 1:
$date = $date->subWeeks(26);
break;
case -1:
$date = $date->addWeeks(26);
break;
}
$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 ?? 1,
$dayOfYear ?? 4
);
}
/**
* 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') ?? 0;
$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) / 7);
}
/**
* 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()->dayOfYear($dayOfYear)->startOfWeek($dayOfWeek);
$end = $date->avoidMutation()->startOfWeek($dayOfWeek);
if ($start > $end) {
$start = $start->subWeeks(26)->dayOfYear($dayOfYear)->startOfWeek($dayOfWeek);
}
$week = (int) ($start->diffInDays($end) / 7 + 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 ?? 1,
$dayOfYear ?? 4
);
}
}