update inbox list

This commit is contained in:
manhlab
2021-04-07 19:25:18 -04:00
parent fda7245f7c
commit 436de2efd6
8576 changed files with 1013325 additions and 3 deletions

View File

@@ -0,0 +1,442 @@
<?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,34 @@
<?php
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);
}
}

View File

@@ -0,0 +1,988 @@
<?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 BadMethodCallException;
use Carbon\CarbonInterface;
use Carbon\Exceptions\BadComparisonUnitException;
use InvalidArgumentException;
/**
* Trait Comparison.
*
* Comparison utils and testers. All the following methods return booleans.
* nowWithSameTz
*
* Depends on the following methods:
*
* @method CarbonInterface resolveCarbon($date)
* @method CarbonInterface copy()
* @method CarbonInterface nowWithSameTz()
* @method static CarbonInterface yesterday($timezone = null)
* @method static CarbonInterface tomorrow($timezone = null)
*/
trait Comparison
{
/**
* Determines if the instance is equal to another
*
* @example
* ```
* Carbon::parse('2018-07-25 12:45:16')->eq('2018-07-25 12:45:16'); // true
* Carbon::parse('2018-07-25 12:45:16')->eq(Carbon::parse('2018-07-25 12:45:16')); // true
* Carbon::parse('2018-07-25 12:45:16')->eq('2018-07-25 12:45:17'); // false
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date
*
* @see equalTo()
*
* @return bool
*/
public function eq($date): bool
{
return $this->equalTo($date);
}
/**
* Determines if the instance is equal to another
*
* @example
* ```
* Carbon::parse('2018-07-25 12:45:16')->equalTo('2018-07-25 12:45:16'); // true
* Carbon::parse('2018-07-25 12:45:16')->equalTo(Carbon::parse('2018-07-25 12:45:16')); // true
* Carbon::parse('2018-07-25 12:45:16')->equalTo('2018-07-25 12:45:17'); // false
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date
*
* @return bool
*/
public function equalTo($date): bool
{
return $this == $date;
}
/**
* Determines if the instance is not equal to another
*
* @example
* ```
* Carbon::parse('2018-07-25 12:45:16')->ne('2018-07-25 12:45:16'); // false
* Carbon::parse('2018-07-25 12:45:16')->ne(Carbon::parse('2018-07-25 12:45:16')); // false
* Carbon::parse('2018-07-25 12:45:16')->ne('2018-07-25 12:45:17'); // true
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date
*
* @see notEqualTo()
*
* @return bool
*/
public function ne($date): bool
{
return $this->notEqualTo($date);
}
/**
* Determines if the instance is not equal to another
*
* @example
* ```
* Carbon::parse('2018-07-25 12:45:16')->notEqualTo('2018-07-25 12:45:16'); // false
* Carbon::parse('2018-07-25 12:45:16')->notEqualTo(Carbon::parse('2018-07-25 12:45:16')); // false
* Carbon::parse('2018-07-25 12:45:16')->notEqualTo('2018-07-25 12:45:17'); // true
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date
*
* @return bool
*/
public function notEqualTo($date): bool
{
return !$this->equalTo($date);
}
/**
* Determines if the instance is greater (after) than another
*
* @example
* ```
* Carbon::parse('2018-07-25 12:45:16')->gt('2018-07-25 12:45:15'); // true
* Carbon::parse('2018-07-25 12:45:16')->gt('2018-07-25 12:45:16'); // false
* Carbon::parse('2018-07-25 12:45:16')->gt('2018-07-25 12:45:17'); // false
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date
*
* @see greaterThan()
*
* @return bool
*/
public function gt($date): bool
{
return $this->greaterThan($date);
}
/**
* Determines if the instance is greater (after) than another
*
* @example
* ```
* Carbon::parse('2018-07-25 12:45:16')->greaterThan('2018-07-25 12:45:15'); // true
* Carbon::parse('2018-07-25 12:45:16')->greaterThan('2018-07-25 12:45:16'); // false
* Carbon::parse('2018-07-25 12:45:16')->greaterThan('2018-07-25 12:45:17'); // false
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date
*
* @return bool
*/
public function greaterThan($date): bool
{
return $this > $date;
}
/**
* Determines if the instance is greater (after) than another
*
* @example
* ```
* Carbon::parse('2018-07-25 12:45:16')->isAfter('2018-07-25 12:45:15'); // true
* Carbon::parse('2018-07-25 12:45:16')->isAfter('2018-07-25 12:45:16'); // false
* Carbon::parse('2018-07-25 12:45:16')->isAfter('2018-07-25 12:45:17'); // false
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date
*
* @see greaterThan()
*
* @return bool
*/
public function isAfter($date): bool
{
return $this->greaterThan($date);
}
/**
* Determines if the instance is greater (after) than or equal to another
*
* @example
* ```
* Carbon::parse('2018-07-25 12:45:16')->gte('2018-07-25 12:45:15'); // true
* Carbon::parse('2018-07-25 12:45:16')->gte('2018-07-25 12:45:16'); // true
* Carbon::parse('2018-07-25 12:45:16')->gte('2018-07-25 12:45:17'); // false
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date
*
* @see greaterThanOrEqualTo()
*
* @return bool
*/
public function gte($date): bool
{
return $this->greaterThanOrEqualTo($date);
}
/**
* Determines if the instance is greater (after) than or equal to another
*
* @example
* ```
* Carbon::parse('2018-07-25 12:45:16')->greaterThanOrEqualTo('2018-07-25 12:45:15'); // true
* Carbon::parse('2018-07-25 12:45:16')->greaterThanOrEqualTo('2018-07-25 12:45:16'); // true
* Carbon::parse('2018-07-25 12:45:16')->greaterThanOrEqualTo('2018-07-25 12:45:17'); // false
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date
*
* @return bool
*/
public function greaterThanOrEqualTo($date): bool
{
return $this >= $date;
}
/**
* Determines if the instance is less (before) than another
*
* @example
* ```
* Carbon::parse('2018-07-25 12:45:16')->lt('2018-07-25 12:45:15'); // false
* Carbon::parse('2018-07-25 12:45:16')->lt('2018-07-25 12:45:16'); // false
* Carbon::parse('2018-07-25 12:45:16')->lt('2018-07-25 12:45:17'); // true
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date
*
* @see lessThan()
*
* @return bool
*/
public function lt($date): bool
{
return $this->lessThan($date);
}
/**
* Determines if the instance is less (before) than another
*
* @example
* ```
* Carbon::parse('2018-07-25 12:45:16')->lessThan('2018-07-25 12:45:15'); // false
* Carbon::parse('2018-07-25 12:45:16')->lessThan('2018-07-25 12:45:16'); // false
* Carbon::parse('2018-07-25 12:45:16')->lessThan('2018-07-25 12:45:17'); // true
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date
*
* @return bool
*/
public function lessThan($date): bool
{
return $this < $date;
}
/**
* Determines if the instance is less (before) than another
*
* @example
* ```
* Carbon::parse('2018-07-25 12:45:16')->isBefore('2018-07-25 12:45:15'); // false
* Carbon::parse('2018-07-25 12:45:16')->isBefore('2018-07-25 12:45:16'); // false
* Carbon::parse('2018-07-25 12:45:16')->isBefore('2018-07-25 12:45:17'); // true
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date
*
* @see lessThan()
*
* @return bool
*/
public function isBefore($date): bool
{
return $this->lessThan($date);
}
/**
* Determines if the instance is less (before) or equal to another
*
* @example
* ```
* Carbon::parse('2018-07-25 12:45:16')->lte('2018-07-25 12:45:15'); // false
* Carbon::parse('2018-07-25 12:45:16')->lte('2018-07-25 12:45:16'); // true
* Carbon::parse('2018-07-25 12:45:16')->lte('2018-07-25 12:45:17'); // true
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date
*
* @see lessThanOrEqualTo()
*
* @return bool
*/
public function lte($date): bool
{
return $this->lessThanOrEqualTo($date);
}
/**
* Determines if the instance is less (before) or equal to another
*
* @example
* ```
* Carbon::parse('2018-07-25 12:45:16')->lessThanOrEqualTo('2018-07-25 12:45:15'); // false
* Carbon::parse('2018-07-25 12:45:16')->lessThanOrEqualTo('2018-07-25 12:45:16'); // true
* Carbon::parse('2018-07-25 12:45:16')->lessThanOrEqualTo('2018-07-25 12:45:17'); // true
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date
*
* @return bool
*/
public function lessThanOrEqualTo($date): bool
{
return $this <= $date;
}
/**
* Determines if the instance is between two others.
*
* The third argument allow you to specify if bounds are included or not (true by default)
* but for when you including/excluding bounds may produce different results in your application,
* we recommend to use the explicit methods ->betweenIncluded() or ->betweenExcluded() instead.
*
* @example
* ```
* Carbon::parse('2018-07-25')->between('2018-07-14', '2018-08-01'); // true
* Carbon::parse('2018-07-25')->between('2018-08-01', '2018-08-20'); // false
* Carbon::parse('2018-07-25')->between('2018-07-25', '2018-08-01'); // true
* Carbon::parse('2018-07-25')->between('2018-07-25', '2018-08-01', false); // false
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date1
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date2
* @param bool $equal Indicates if an equal to comparison should be done
*
* @return bool
*/
public function between($date1, $date2, $equal = true): bool
{
$date1 = $this->resolveCarbon($date1);
$date2 = $this->resolveCarbon($date2);
if ($date1->greaterThan($date2)) {
[$date1, $date2] = [$date2, $date1];
}
if ($equal) {
return $this->greaterThanOrEqualTo($date1) && $this->lessThanOrEqualTo($date2);
}
return $this->greaterThan($date1) && $this->lessThan($date2);
}
/**
* Determines if the instance is between two others, bounds included.
*
* @example
* ```
* Carbon::parse('2018-07-25')->betweenIncluded('2018-07-14', '2018-08-01'); // true
* Carbon::parse('2018-07-25')->betweenIncluded('2018-08-01', '2018-08-20'); // false
* Carbon::parse('2018-07-25')->betweenIncluded('2018-07-25', '2018-08-01'); // true
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date1
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date2
*
* @return bool
*/
public function betweenIncluded($date1, $date2): bool
{
return $this->between($date1, $date2, true);
}
/**
* Determines if the instance is between two others, bounds excluded.
*
* @example
* ```
* Carbon::parse('2018-07-25')->betweenExcluded('2018-07-14', '2018-08-01'); // true
* Carbon::parse('2018-07-25')->betweenExcluded('2018-08-01', '2018-08-20'); // false
* Carbon::parse('2018-07-25')->betweenExcluded('2018-07-25', '2018-08-01'); // false
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date1
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date2
*
* @return bool
*/
public function betweenExcluded($date1, $date2): bool
{
return $this->between($date1, $date2, false);
}
/**
* Determines if the instance is between two others
*
* @example
* ```
* Carbon::parse('2018-07-25')->isBetween('2018-07-14', '2018-08-01'); // true
* Carbon::parse('2018-07-25')->isBetween('2018-08-01', '2018-08-20'); // false
* Carbon::parse('2018-07-25')->isBetween('2018-07-25', '2018-08-01'); // true
* Carbon::parse('2018-07-25')->isBetween('2018-07-25', '2018-08-01', false); // false
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date1
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date2
* @param bool $equal Indicates if an equal to comparison should be done
*
* @return bool
*/
public function isBetween($date1, $date2, $equal = true): bool
{
return $this->between($date1, $date2, $equal);
}
/**
* Determines if the instance is a weekday.
*
* @example
* ```
* Carbon::parse('2019-07-14')->isWeekday(); // false
* Carbon::parse('2019-07-15')->isWeekday(); // true
* ```
*
* @return bool
*/
public function isWeekday()
{
return !$this->isWeekend();
}
/**
* Determines if the instance is a weekend day.
*
* @example
* ```
* Carbon::parse('2019-07-14')->isWeekend(); // true
* Carbon::parse('2019-07-15')->isWeekend(); // false
* ```
*
* @return bool
*/
public function isWeekend()
{
return in_array($this->dayOfWeek, static::$weekendDays);
}
/**
* Determines if the instance is yesterday.
*
* @example
* ```
* Carbon::yesterday()->isYesterday(); // true
* Carbon::tomorrow()->isYesterday(); // false
* ```
*
* @return bool
*/
public function isYesterday()
{
return $this->toDateString() === static::yesterday($this->getTimezone())->toDateString();
}
/**
* Determines if the instance is today.
*
* @example
* ```
* Carbon::today()->isToday(); // true
* Carbon::tomorrow()->isToday(); // false
* ```
*
* @return bool
*/
public function isToday()
{
return $this->toDateString() === $this->nowWithSameTz()->toDateString();
}
/**
* Determines if the instance is tomorrow.
*
* @example
* ```
* Carbon::tomorrow()->isTomorrow(); // true
* Carbon::yesterday()->isTomorrow(); // false
* ```
*
* @return bool
*/
public function isTomorrow()
{
return $this->toDateString() === static::tomorrow($this->getTimezone())->toDateString();
}
/**
* Determines if the instance is in the future, ie. greater (after) than now.
*
* @example
* ```
* Carbon::now()->addHours(5)->isFuture(); // true
* Carbon::now()->subHours(5)->isFuture(); // false
* ```
*
* @return bool
*/
public function isFuture()
{
return $this->greaterThan($this->nowWithSameTz());
}
/**
* Determines if the instance is in the past, ie. less (before) than now.
*
* @example
* ```
* Carbon::now()->subHours(5)->isPast(); // true
* Carbon::now()->addHours(5)->isPast(); // false
* ```
*
* @return bool
*/
public function isPast()
{
return $this->lessThan($this->nowWithSameTz());
}
/**
* Determines if the instance is a leap year.
*
* @example
* ```
* Carbon::parse('2020-01-01')->isLeapYear(); // true
* Carbon::parse('2019-01-01')->isLeapYear(); // false
* ```
*
* @return bool
*/
public function isLeapYear()
{
return $this->rawFormat('L') === '1';
}
/**
* Determines if the instance is a long year
*
* @example
* ```
* Carbon::parse('2015-01-01')->isLongYear(); // true
* Carbon::parse('2016-01-01')->isLongYear(); // false
* ```
*
* @see https://en.wikipedia.org/wiki/ISO_8601#Week_dates
*
* @return bool
*/
public function isLongYear()
{
return static::create($this->year, 12, 28, 0, 0, 0, $this->tz)->weekOfYear === 53;
}
/**
* Compares the formatted values of the two dates.
*
* @example
* ```
* Carbon::parse('2019-06-13')->isSameAs('Y-d', Carbon::parse('2019-12-13')); // true
* Carbon::parse('2019-06-13')->isSameAs('Y-d', Carbon::parse('2019-06-14')); // false
* ```
*
* @param string $format date formats to compare.
* @param \Carbon\Carbon|\DateTimeInterface|string|null $date instance to compare with or null to use current day.
*
* @return bool
*/
public function isSameAs($format, $date = null)
{
return $this->rawFormat($format) === $this->resolveCarbon($date)->rawFormat($format);
}
/**
* Determines if the instance is in the current unit given.
*
* @example
* ```
* Carbon::parse('2019-01-13')->isSameUnit('year', Carbon::parse('2019-12-25')); // true
* Carbon::parse('2018-12-13')->isSameUnit('year', Carbon::parse('2019-12-25')); // false
* ```
*
* @param string $unit singular unit string
* @param \Carbon\Carbon|\DateTimeInterface|null $date instance to compare with or null to use current day.
*
* @throws BadComparisonUnitException
*
* @return bool
*/
public function isSameUnit($unit, $date = null)
{
$units = [
// @call isSameUnit
'year' => 'Y',
// @call isSameUnit
'week' => 'o-W',
// @call isSameUnit
'day' => 'Y-m-d',
// @call isSameUnit
'hour' => 'Y-m-d H',
// @call isSameUnit
'minute' => 'Y-m-d H:i',
// @call isSameUnit
'second' => 'Y-m-d H:i:s',
// @call isSameUnit
'micro' => 'Y-m-d H:i:s.u',
// @call isSameUnit
'microsecond' => 'Y-m-d H:i:s.u',
];
if (!isset($units[$unit])) {
if (isset($this->$unit)) {
return $this->$unit === $this->resolveCarbon($date)->$unit;
}
if ($this->localStrictModeEnabled ?? static::isStrictModeEnabled()) {
throw new BadComparisonUnitException($unit);
}
return false;
}
return $this->isSameAs($units[$unit], $date);
}
/**
* Determines if the instance is in the current unit given.
*
* @example
* ```
* Carbon::now()->isCurrentUnit('hour'); // true
* Carbon::now()->subHours(2)->isCurrentUnit('hour'); // false
* ```
*
* @param string $unit The unit to test.
*
* @throws BadMethodCallException
*
* @return bool
*/
public function isCurrentUnit($unit)
{
return $this->{'isSame'.ucfirst($unit)}();
}
/**
* Checks if the passed in date is in the same quarter as the instance quarter (and year if needed).
*
* @example
* ```
* Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2019-03-01')); // true
* Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2019-04-01')); // false
* Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2018-03-01')); // false
* Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2018-03-01'), false); // true
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|string|null $date The instance to compare with or null to use current day.
* @param bool $ofSameYear Check if it is the same month in the same year.
*
* @return bool
*/
public function isSameQuarter($date = null, $ofSameYear = true)
{
$date = $this->resolveCarbon($date);
return $this->quarter === $date->quarter && (!$ofSameYear || $this->isSameYear($date));
}
/**
* Checks if the passed in date is in the same month as the instance´s month.
*
* @example
* ```
* Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2019-01-01')); // true
* Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2019-02-01')); // false
* Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2018-01-01')); // false
* Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2018-01-01'), false); // true
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|null $date The instance to compare with or null to use the current date.
* @param bool $ofSameYear Check if it is the same month in the same year.
*
* @return bool
*/
public function isSameMonth($date = null, $ofSameYear = true)
{
return $this->isSameAs($ofSameYear ? 'Y-m' : 'm', $date);
}
/**
* Checks if this day is a specific day of the week.
*
* @example
* ```
* Carbon::parse('2019-07-17')->isDayOfWeek(Carbon::WEDNESDAY); // true
* Carbon::parse('2019-07-17')->isDayOfWeek(Carbon::FRIDAY); // false
* Carbon::parse('2019-07-17')->isDayOfWeek('Wednesday'); // true
* Carbon::parse('2019-07-17')->isDayOfWeek('Friday'); // false
* ```
*
* @param int $dayOfWeek
*
* @return bool
*/
public function isDayOfWeek($dayOfWeek)
{
if (is_string($dayOfWeek) && defined($constant = static::class.'::'.strtoupper($dayOfWeek))) {
$dayOfWeek = constant($constant);
}
return $this->dayOfWeek === $dayOfWeek;
}
/**
* Check if its the birthday. Compares the date/month values of the two dates.
*
* @example
* ```
* Carbon::now()->subYears(5)->isBirthday(); // true
* Carbon::now()->subYears(5)->subDay()->isBirthday(); // false
* Carbon::parse('2019-06-05')->isBirthday(Carbon::parse('2001-06-05')); // true
* Carbon::parse('2019-06-05')->isBirthday(Carbon::parse('2001-06-06')); // false
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|null $date The instance to compare with or null to use current day.
*
* @return bool
*/
public function isBirthday($date = null)
{
return $this->isSameAs('md', $date);
}
/**
* Check if today is the last day of the Month
*
* @example
* ```
* Carbon::parse('2019-02-28')->isLastOfMonth(); // true
* Carbon::parse('2019-03-28')->isLastOfMonth(); // false
* Carbon::parse('2019-03-30')->isLastOfMonth(); // false
* Carbon::parse('2019-03-31')->isLastOfMonth(); // true
* Carbon::parse('2019-04-30')->isLastOfMonth(); // true
* ```
*
* @return bool
*/
public function isLastOfMonth()
{
return $this->day === $this->daysInMonth;
}
/**
* Check if the instance is start of day / midnight.
*
* @example
* ```
* Carbon::parse('2019-02-28 00:00:00')->isStartOfDay(); // true
* Carbon::parse('2019-02-28 00:00:00.999999')->isStartOfDay(); // true
* Carbon::parse('2019-02-28 00:00:01')->isStartOfDay(); // false
* Carbon::parse('2019-02-28 00:00:00.000000')->isStartOfDay(true); // true
* Carbon::parse('2019-02-28 00:00:00.000012')->isStartOfDay(true); // false
* ```
*
* @param bool $checkMicroseconds check time at microseconds precision
*
* @return bool
*/
public function isStartOfDay($checkMicroseconds = false)
{
/* @var CarbonInterface $this */
return $checkMicroseconds
? $this->rawFormat('H:i:s.u') === '00:00:00.000000'
: $this->rawFormat('H:i:s') === '00:00:00';
}
/**
* Check if the instance is end of day.
*
* @example
* ```
* Carbon::parse('2019-02-28 23:59:59.999999')->isEndOfDay(); // true
* Carbon::parse('2019-02-28 23:59:59.123456')->isEndOfDay(); // true
* Carbon::parse('2019-02-28 23:59:59')->isEndOfDay(); // true
* Carbon::parse('2019-02-28 23:59:58.999999')->isEndOfDay(); // false
* Carbon::parse('2019-02-28 23:59:59.999999')->isEndOfDay(true); // true
* Carbon::parse('2019-02-28 23:59:59.123456')->isEndOfDay(true); // false
* Carbon::parse('2019-02-28 23:59:59')->isEndOfDay(true); // false
* ```
*
* @param bool $checkMicroseconds check time at microseconds precision
*
* @return bool
*/
public function isEndOfDay($checkMicroseconds = false)
{
/* @var CarbonInterface $this */
return $checkMicroseconds
? $this->rawFormat('H:i:s.u') === '23:59:59.999999'
: $this->rawFormat('H:i:s') === '23:59:59';
}
/**
* Check if the instance is start of day / midnight.
*
* @example
* ```
* Carbon::parse('2019-02-28 00:00:00')->isMidnight(); // true
* Carbon::parse('2019-02-28 00:00:00.999999')->isMidnight(); // true
* Carbon::parse('2019-02-28 00:00:01')->isMidnight(); // false
* ```
*
* @return bool
*/
public function isMidnight()
{
return $this->isStartOfDay();
}
/**
* Check if the instance is midday.
*
* @example
* ```
* Carbon::parse('2019-02-28 11:59:59.999999')->isMidday(); // false
* Carbon::parse('2019-02-28 12:00:00')->isMidday(); // true
* Carbon::parse('2019-02-28 12:00:00.999999')->isMidday(); // true
* Carbon::parse('2019-02-28 12:00:01')->isMidday(); // false
* ```
*
* @return bool
*/
public function isMidday()
{
/* @var CarbonInterface $this */
return $this->rawFormat('G:i:s') === static::$midDayAt.':00:00';
}
/**
* Checks if the (date)time string is in a given format.
*
* @example
* ```
* Carbon::hasFormat('11:12:45', 'h:i:s'); // true
* Carbon::hasFormat('13:12:45', 'h:i:s'); // false
* ```
*
* @SuppressWarnings(PHPMD.EmptyCatchBlock)
*
* @param string $date
* @param string $format
*
* @return bool
*/
public static function hasFormat($date, $format)
{
try {
// Try to create a DateTime object. Throws an InvalidArgumentException if the provided time string
// doesn't match the format in any way.
static::rawCreateFromFormat($format, $date);
// createFromFormat() is known to handle edge cases silently.
// E.g. "1975-5-1" (Y-n-j) will still be parsed correctly when "Y-m-d" is supplied as the format.
// To ensure we're really testing against our desired format, perform an additional regex validation.
// Preg quote, but remove escaped backslashes since we'll deal with escaped characters in the format string.
$quotedFormat = str_replace('\\\\', '\\', preg_quote($format, '/'));
// Build the regex string
$regex = '';
for ($i = 0; $i < strlen($quotedFormat); ++$i) {
// Backslash the next character does not represent a date token so add it on as-is and continue.
// We're doing an extra ++$i here to increment the loop by 2.
if ($quotedFormat[$i] === '\\') {
$char = $quotedFormat[++$i];
$regex .= $char === '\\' ? '\\\\' : $char;
continue;
}
$regex .= strtr($quotedFormat[$i], static::$regexFormats);
}
return (bool) preg_match('/^'.str_replace('/', '\\/', $regex).'$/', $date);
} catch (InvalidArgumentException $e) {
}
return false;
}
/**
* Returns true if the current date matches the given string.
*
* @example
* ```
* var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2019')); // true
* var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2018')); // false
* var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2019-06')); // true
* var_dump(Carbon::parse('2019-06-02 12:23:45')->is('06-02')); // true
* var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2019-06-02')); // true
* var_dump(Carbon::parse('2019-06-02 12:23:45')->is('Sunday')); // true
* var_dump(Carbon::parse('2019-06-02 12:23:45')->is('June')); // true
* var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12:23')); // true
* var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12:23:45')); // true
* var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12:23:00')); // false
* var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12h')); // true
* var_dump(Carbon::parse('2019-06-02 15:23:45')->is('3pm')); // true
* var_dump(Carbon::parse('2019-06-02 15:23:45')->is('3am')); // false
* ```
*
* @param string $tester day name, month name, hour, date, etc. as string
*
* @return bool
*/
public function is(string $tester)
{
$tester = trim($tester);
if (preg_match('/^\d+$/', $tester)) {
return $this->year === intval($tester);
}
if (preg_match('/^\d{3,}-\d{1,2}$/', $tester)) {
return $this->isSameMonth(static::parse($tester));
}
if (preg_match('/^\d{1,2}-\d{1,2}$/', $tester)) {
return $this->isSameDay(static::parse($this->year.'-'.$tester));
}
$modifier = preg_replace('/(\d)h$/i', '$1:00', $tester);
/* @var CarbonInterface $max */
$median = static::parse('5555-06-15 12:30:30.555555')->modify($modifier);
$current = $this->copy();
/* @var CarbonInterface $other */
$other = $this->copy()->modify($modifier);
if ($current->eq($other)) {
return true;
}
if (preg_match('/\d:\d{1,2}:\d{1,2}$/', $tester)) {
return $current->startOfSecond()->eq($other);
}
if (preg_match('/\d:\d{1,2}$/', $tester)) {
return $current->startOfMinute()->eq($other);
}
if (preg_match('/\d(h|am|pm)$/', $tester)) {
return $current->startOfHour()->eq($other);
}
if (preg_match(
'/^(january|february|march|april|may|june|july|august|september|october|november|december)\s+\d+$/i',
$tester
)) {
return $current->startOfMonth()->eq($other->startOfMonth());
}
$units = [
'month' => [1, 'year'],
'day' => [1, 'month'],
'hour' => [0, 'day'],
'minute' => [0, 'hour'],
'second' => [0, 'minute'],
'microsecond' => [0, 'second'],
];
foreach ($units as $unit => [$minimum, $startUnit]) {
if ($median->$unit === $minimum) {
$current = $current->startOf($startUnit);
break;
}
}
return $current->eq($other);
}
}

View File

@@ -0,0 +1,640 @@
<?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;
/**
* Trait Converter.
*
* Change date into different string formats and types and
* handle the string cast.
*
* Depends on the following methods:
*
* @method Carbon|CarbonImmutable copy()
*/
trait Converter
{
/**
* Format to use for __toString method when type juggling occurs.
*
* @var string|Closure|null
*/
protected static $toStringFormat = null;
/**
* 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);
}
/**
* @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
* You should rather let Carbon object being casted to string with DEFAULT_TO_STRING_FORMAT, and
* use other method or custom format passed to format() method if you need to dump an other string
* format.
*
* Set the default format used when type juggling a Carbon instance to a string
*
* @param string|Closure|null $format
*
* @return void
*/
public static function setToStringFormat($format)
{
static::$toStringFormat = $format;
}
/**
* 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
*/
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 casted 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 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->copy()->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
*
* @example
* ```
* echo Carbon::now()->toRfc3339String();
* ```
*
* @return string
*/
public function toRfc3339String()
{
return $this->rawFormat(DateTime::RFC3339);
}
/**
* 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->copy()
->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->copy()->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->copy()->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,905 @@
<?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;
/**
* 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 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_int($time)) {
$time = "@$time";
}
// 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 (strpos((string) .1, '.') === false) {
$locale = setlocale(LC_NUMERIC, '0');
setlocale(LC_NUMERIC, 'C');
}
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);
}
static::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 || $date instanceof Options) {
$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|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|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;
}
/**
* 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
*/
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)) {
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 === null ? $getDefault('year') : $year;
$month = $month === null ? $getDefault('month') : $month;
$day = $day === null ? $getDefault('day') : $day;
$hour = $hour === null ? $getDefault('hour') : $hour;
$minute = $minute === null ? $getDefault('minute') : $minute;
$second = (float) ($second === null ? $getDefault('second') : $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);
/** @var CarbonImmutable|Carbon $instance */
$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 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, "$time");
}
$tz = is_int($originalTz)
? @timezone_name_from_abbr('', (int) ($originalTz * 3600), 1)
: $originalTz;
$tz = static::safeCreateDateTimeZone($tz, $originalTz);
if ($tz === false) {
return false;
}
return parent::createFromFormat($format, "$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)
{
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
*/
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 (is_string($var) &&
!preg_match('/^P[0-9T]/', $var) &&
!preg_match('/^R[0-9]/', $var) &&
preg_match('/[a-z0-9]/i', $var)
) {
$date = static::parse($var);
}
}
return $date;
}
/**
* Set last errors.
*
* @param array $lastErrors
*
* @return void
*/
private static function setLastErrors(array $lastErrors)
{
static::$lastErrors = $lastErrors;
}
/**
* {@inheritdoc}
*/
public static function getLastErrors()
{
return static::$lastErrors;
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

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 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,808 @@
<?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 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\\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 = $translator->getCatalogue($locale)->get($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 null $number
* @param \Symfony\Component\Translation\TranslatorInterface $translator
*
* @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 "$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 ($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+.\/,_-])/i', function ($match) use ($fromTranslations, $toTranslations) {
[$chunk] = $match;
foreach ($fromTranslations as $index => $word) {
if (preg_match("/^$word\$/i", $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->setLocalTranslator($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 = call_user_func($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 && $translator->getCatalogue($newLocale)->get($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);
}
return $translator;
}
/**
* 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'
? static::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;
}
}

View File

@@ -0,0 +1,148 @@
<?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 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 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,176 @@
<?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 ReflectionClass;
use ReflectionException;
use ReflectionMethod;
use Throwable;
/**
* 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 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)
? static::loadMixinTrait($mixin)
: static::loadMixinClass($mixin);
}
/**
* @param 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)
{
$baseClass = static::class;
$context = eval('return new class() extends '.$baseClass.' {use '.$trait.';};');
$className = get_class($context);
foreach (get_class_methods($context) as $name) {
if (method_exists($baseClass, $name)) {
continue;
}
$closureBase = Closure::fromCallable([$context, $name]);
static::macro($name, function () use ($closureBase, $className) {
$context = isset($this) ? $this->cast($className) : new $className();
try {
$closure = $closureBase->bindTo($context);
} catch (Throwable $e) {
$closure = $closureBase;
}
return $closure(...func_get_args());
});
}
}
/**
* 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 new one if static.
*
* @return static
*/
protected static function this()
{
return end(static::$macroContextStack) ?: new static();
}
}

View File

@@ -0,0 +1,467 @@
<?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;
/**
* 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 $step */
$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->copy()->firstOfMonth();
$check = $date->rawFormat('Y-m');
$date = $date->modify('+'.$nth.' '.static::$days[$dayOfWeek]);
return $date->rawFormat('Y-m') === $check ? $this->modify("$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->copy()->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("$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->copy()->firstOfYear()->modify('+'.$nth.' '.static::$days[$dayOfWeek]);
return $this->year === $date->year ? $this->modify("$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
*/
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->copy()->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,70 @@
<?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,21 @@
<?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 = null;
}

View File

@@ -0,0 +1,442 @@
<?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;
/**
* 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
*/
protected static $regexFormats = [
'd' => '(3[01]|[12][0-9]|0[1-9])',
'D' => '([a-zA-Z]{3})',
'j' => '([123][0-9]|[1-9])',
'l' => '([a-zA-Z]{2,})',
'N' => '([1-7])',
'S' => '([a-zA-Z]{2})',
'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]|[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])',
'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]|[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, j M Y H:i:s O
];
/**
* 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 = null;
/**
* Function to call instead of createFromFormat.
*
* @var string|callable|null
*/
protected static $createFromFormatFunction = null;
/**
* Function to call instead of parse.
*
* @var string|callable|null
*/
protected static $parseFunction = null;
/**
* Indicates if months should be calculated with overflow.
* Specific setting.
*
* @var bool|null
*/
protected $localMonthsOverflow = null;
/**
* Indicates if years should be calculated with overflow.
* Specific setting.
*
* @var bool|null
*/
protected $localYearsOverflow = null;
/**
* Indicates if the strict mode is in use.
* Specific setting.
*
* @var bool|null
*/
protected $localStrictModeEnabled = null;
/**
* Options for diffForHumans and forHumans methods.
*
* @var bool|null
*/
protected $localHumanDiffOptions = null;
/**
* Format to use on string cast.
*
* @var string|null
*/
protected $localToStringFormat = null;
/**
* Format to use on JSON serialization.
*
* @var string|null
*/
protected $localSerializer = null;
/**
* Instance-specific macros.
*
* @var array|null
*/
protected $localMacros = null;
/**
* Instance-specific generic macros.
*
* @var array|null
*/
protected $localGenericMacros = null;
/**
* Function to call instead of format.
*
* @var string|callable|null
*/
protected $localFormatFunction = null;
/**
* @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['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]);
}
}
// @codeCoverageIgnoreStart
if ($this instanceof CarbonInterface || $this instanceof DateTimeInterface) {
if (!isset($infos['date'])) {
$infos['date'] = $this->format(CarbonInterface::MOCK_DATETIME_FORMAT);
}
if (!isset($infos['timezone'])) {
$infos['timezone'] = $this->tzName;
}
}
// @codeCoverageIgnoreEnd
return $infos;
}
}

View File

@@ -0,0 +1,227 @@
<?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 CarbonInterface copy()
* @method CarbonInterface startOfWeek(int $weekStartsAt = null)
*/
trait Rounding
{
use IntervalRounding;
/**
* Round the current instance at the given unit with given precision if specified and the given function.
*
* @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(), [
// @call roundUnit
'microsecond' => [0, 999999],
]);
$factor = 1;
if ($normalizedUnit === 'week') {
$normalizedUnit = 'day';
$precision *= static::DAYS_PER_WEEK;
}
if (isset($metaUnits[$normalizedUnit])) {
[$factor, $normalizedUnit] = $metaUnits[$normalizedUnit];
}
$precision *= $factor;
if (!isset($ranges[$normalizedUnit])) {
throw new UnknownUnitException($unit);
}
$found = false;
$fraction = 0;
$arguments = null;
$factor = $this->year < 0 ? -1 : 1;
$changes = [];
foreach ($ranges as $unit => [$minimum, $maximum]) {
if ($normalizedUnit === $unit) {
$arguments = [$this->$unit, $minimum];
$fraction = $precision - floor($precision);
$found = true;
continue;
}
if ($found) {
$delta = $maximum + 1 - $minimum;
$factor /= $delta;
$fraction *= $delta;
$arguments[0] += $this->$unit * $factor;
$changes[$unit] = round($minimum + ($fraction ? $fraction * call_user_func($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;
/** @var CarbonInterface $result */
$result = $this->$normalizedUnit(floor(call_user_func($function, ($value - $minimum) / $precision) * $precision + $minimum));
foreach ($changes as $unit => $value) {
$result = $result->$unit($value);
}
return $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->copy()->floorWeek($weekStartsAt), $this->copy()->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->copy()->startOfWeek($weekStartsAt);
return $startOfWeek != $this ?
$this->startOfWeek($weekStartsAt)->addWeek() :
$this;
}
$startOfWeek = $this->startOfWeek($weekStartsAt);
return $startOfWeek != $this ?
$startOfWeek->addWeek() :
$this->copy();
}
}

View File

@@ -0,0 +1,193 @@
<?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;
/**
* 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)
* @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 = null;
/**
* 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("$value");
if (!$instance instanceof static) {
throw new InvalidFormatException("Invalid serialized value: $value");
}
return $instance;
}
/**
* The __set_state handler.
*
* @param string|array $dump
*
* @return static
*/
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->dumpProperties;
if ($this->localTranslator ?? null) {
$properties[] = 'dumpLocale';
$this->dumpLocale = $this->locale ?? null;
}
return $properties;
}
/**
* Set locale if specified on unserialize() called.
*/
public function __wakeup()
{
if (get_parent_class() && method_exists(parent::class, '__wakeup')) {
parent::__wakeup();
}
$this->constructedObjectId = spl_object_hash($this);
if (isset($this->dumpLocale)) {
$this->locale($this->dumpLocale);
$this->dumpLocale = null;
}
$this->cleanupDumpProperties();
}
/**
* Prepare the object for JSON serialization.
*
* @return array|string
*/
public function jsonSerialize()
{
$serializer = $this->localSerializer ?? static::$serializer;
if ($serializer) {
return is_string($serializer)
? $this->rawFormat($serializer)
: call_user_func($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()
{
foreach ($this->dumpProperties as $property) {
if (isset($this->$property)) {
unset($this->$property);
}
}
return $this;
}
}

View File

@@ -0,0 +1,132 @@
<?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 DateTimeImmutable;
trait Test
{
///////////////////////////////////////////////////////////////////
///////////////////////// TESTING AIDS ////////////////////////////
///////////////////////////////////////////////////////////////////
/**
* A test Carbon instance to be returned when now instances are created.
*
* @var static
*/
protected static $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().
*
* 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.
*
* To clear the test instance call this method using the default
* parameter of null.
*
* /!\ Use this method for unit tests only.
*
* @param Closure|static|string|null $testNow real or mock Carbon instance
*/
public static function setTestNow($testNow = null)
{
static::$testNow = is_string($testNow) ? static::parse($testNow) : $testNow;
}
/**
* 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;
}
/**
* Return the given timezone and set it to the test instance if not null.
* If null, get the timezone from the test instance and return it.
*
* @param string|\DateTimeZone $tz
* @param \Carbon\CarbonInterface $testInstance
*
* @return string|\DateTimeZone
*/
protected static function handleMockTimezone($tz, &$testInstance)
{
//shift the time according to the given time zone
if ($tz !== null && $tz !== static::getMockedTestNow($tz)->getTimezone()) {
$testInstance = $testInstance->setTimezone($tz);
return $tz;
}
return $testInstance->getTimezone();
}
/**
* 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;
}
protected static function mockConstructorParameters(&$time, &$tz)
{
/** @var \Carbon\CarbonImmutable|\Carbon\Carbon $testInstance */
$testInstance = clone static::getMockedTestNow($tz);
$tz = static::handleMockTimezone($tz, $testInstance);
if (static::hasRelativeKeywords($time)) {
$testInstance = $testInstance->modify($time);
}
$time = $testInstance instanceof self ? $testInstance->rawFormat(static::MOCK_DATETIME_FORMAT) : $testInstance->format(static::MOCK_DATETIME_FORMAT);
}
}

View File

@@ -0,0 +1,122 @@
<?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 DateTime;
/**
* Trait Timestamp.
*/
trait Timestamp
{
/**
* Create a Carbon instance from a timestamp.
*
* @param int $timestamp
* @param \DateTimeZone|string|null $tz
*
* @return static
*/
public static function createFromTimestamp($timestamp, $tz = null)
{
$date = new DateTime('@'.((int) $timestamp));
$tz = static::safeCreateDateTimeZone($tz);
if ($tz) {
$date->setTimezone($tz);
}
return (new static($date->format(DateTime::ATOM)))->tz($tz);
}
/**
* Create a Carbon instance from a timestamp in milliseconds.
*
* @param float $timestamp
* @param \DateTimeZone|string|null $tz
*
* @return static
*/
public static function createFromTimestampMs($timestamp, $tz = null)
{
return static::rawCreateFromFormat('U.u', sprintf('%F', $timestamp / 1000))
->setTimezone($tz);
}
/**
* Create a Carbon instance from an UTC timestamp.
*
* @param int $timestamp
*
* @return static
*/
public static function createFromTimestampUTC($timestamp)
{
return new static('@'.$timestamp);
}
/**
* Set the instance's timestamp.
*
* @param int $value
*
* @return static
*/
public function timestamp($value)
{
return $this->setTimestamp((int) $value);
}
/**
* 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($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);
}
/**
* @alias getTimestamp
*
* Returns the UNIX timestamp for the current date.
*
* @return int
*/
public function unix()
{
return $this->getTimestamp();
}
}

View File

@@ -0,0 +1,357 @@
<?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\CarbonInterval;
use Carbon\Exceptions\UnitException;
use DateInterval;
/**
* 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("$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);
break;
// @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) || in_array($unit, static::$units);
}
/**
* 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 $unit
* @param int $value
* @param bool|null $overflow
*
* @return static
*/
public function add($unit, $value = 1, $overflow = null)
{
if (is_string($unit) && func_num_args() === 1) {
$unit = CarbonInterval::make($unit);
}
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)
{
$date = $this;
if (!is_numeric($value) || !floatval($value)) {
return $date->isMutable() ? $date : $date->copy();
}
$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)) {
$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)) {
return $date->setTimeFromTimeString($timeString);
}
if (isset($canOverflow, $day) && $canOverflow && $day !== $date->day) {
$date = $date->modify('last day of previous month');
}
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);
}
/**
* 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 $unit
* @param int $value
* @param bool|null $overflow
*
* @return static
*/
public function sub($unit, $value = 1, $overflow = null)
{
if (is_string($unit) && func_num_args() === 1) {
$unit = CarbonInterval::make($unit);
}
if ($unit instanceof DateInterval) {
return parent::sub($unit);
}
if (is_numeric($unit)) {
[$value, $unit] = [$unit, $value];
}
return $this->addUnit($unit, -floatval($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,218 @@
<?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 $day)
* @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->copy();
}
$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->copy()->dayOfYear($dayOfYear)->startOfWeek($dayOfWeek);
if ($date->year === $year && $day < $date->dayOfYear) {
return $year - 1;
}
$date = $this->copy()->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->copy()->dayOfYear($dayOfYear)->startOfWeek($dayOfWeek);
$startDay = $start->dayOfYear;
if ($start->year !== $year) {
$startDay -= $start->daysInYear;
}
$end = $this->copy()->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->copy()->dayOfYear($dayOfYear)->startOfWeek($dayOfWeek);
$end = $date->copy()->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
);
}
}