4 * This file is part of the Carbon package.
6 * (c) Brian Nesbitt <brian@nesbot.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
16 use InvalidArgumentException
;
18 use ReflectionFunction
;
20 use Symfony\Component\Translation\TranslatorInterface
;
23 * A simple API extension for DateInterval.
24 * The implementation provides helpers to handle weeks but only days are saved.
25 * Weeks are calculated based on the total days of the current instance.
27 * @property int $years Total years of the current interval.
28 * @property int $months Total months of the current interval.
29 * @property int $weeks Total weeks of the current interval calculated from the days.
30 * @property int $dayz Total days of the current interval (weeks * 7 + days).
31 * @property int $hours Total hours of the current interval.
32 * @property int $minutes Total minutes of the current interval.
33 * @property int $seconds Total seconds of the current interval.
34 * @property-read int $dayzExcludeWeeks Total days remaining in the final week of the current instance (days % 7).
35 * @property-read int $daysExcludeWeeks alias of dayzExcludeWeeks
36 * @property-read float $totalYears Number of years equivalent to the interval.
37 * @property-read float $totalMonths Number of months equivalent to the interval.
38 * @property-read float $totalWeeks Number of weeks equivalent to the interval.
39 * @property-read float $totalDays Number of days equivalent to the interval.
40 * @property-read float $totalDayz Alias for totalDays.
41 * @property-read float $totalHours Number of hours equivalent to the interval.
42 * @property-read float $totalMinutes Number of minutes equivalent to the interval.
43 * @property-read float $totalSeconds Number of seconds equivalent to the interval.
45 * @method static CarbonInterval years($years = 1) Create instance specifying a number of years.
46 * @method static CarbonInterval year($years = 1) Alias for years()
47 * @method static CarbonInterval months($months = 1) Create instance specifying a number of months.
48 * @method static CarbonInterval month($months = 1) Alias for months()
49 * @method static CarbonInterval weeks($weeks = 1) Create instance specifying a number of weeks.
50 * @method static CarbonInterval week($weeks = 1) Alias for weeks()
51 * @method static CarbonInterval days($days = 1) Create instance specifying a number of days.
52 * @method static CarbonInterval dayz($days = 1) Alias for days()
53 * @method static CarbonInterval day($days = 1) Alias for days()
54 * @method static CarbonInterval hours($hours = 1) Create instance specifying a number of hours.
55 * @method static CarbonInterval hour($hours = 1) Alias for hours()
56 * @method static CarbonInterval minutes($minutes = 1) Create instance specifying a number of minutes.
57 * @method static CarbonInterval minute($minutes = 1) Alias for minutes()
58 * @method static CarbonInterval seconds($seconds = 1) Create instance specifying a number of seconds.
59 * @method static CarbonInterval second($seconds = 1) Alias for seconds()
60 * @method CarbonInterval years($years = 1) Set the years portion of the current interval.
61 * @method CarbonInterval year($years = 1) Alias for years().
62 * @method CarbonInterval months($months = 1) Set the months portion of the current interval.
63 * @method CarbonInterval month($months = 1) Alias for months().
64 * @method CarbonInterval weeks($weeks = 1) Set the weeks portion of the current interval. Will overwrite dayz value.
65 * @method CarbonInterval week($weeks = 1) Alias for weeks().
66 * @method CarbonInterval days($days = 1) Set the days portion of the current interval.
67 * @method CarbonInterval dayz($days = 1) Alias for days().
68 * @method CarbonInterval day($days = 1) Alias for days().
69 * @method CarbonInterval hours($hours = 1) Set the hours portion of the current interval.
70 * @method CarbonInterval hour($hours = 1) Alias for hours().
71 * @method CarbonInterval minutes($minutes = 1) Set the minutes portion of the current interval.
72 * @method CarbonInterval minute($minutes = 1) Alias for minutes().
73 * @method CarbonInterval seconds($seconds = 1) Set the seconds portion of the current interval.
74 * @method CarbonInterval second($seconds = 1) Alias for seconds().
76 class CarbonInterval
extends DateInterval
79 * Interval spec period designators
81 const PERIOD_PREFIX
= 'P';
82 const PERIOD_YEARS
= 'Y';
83 const PERIOD_MONTHS
= 'M';
84 const PERIOD_DAYS
= 'D';
85 const PERIOD_TIME_PREFIX
= 'T';
86 const PERIOD_HOURS
= 'H';
87 const PERIOD_MINUTES
= 'M';
88 const PERIOD_SECONDS
= 'S';
91 * A translator to ... er ... translate stuff
93 * @var \Symfony\Component\Translation\TranslatorInterface
95 protected static $translator;
100 protected static $cascadeFactors;
105 private static $flipCascadeFactors;
108 * The registered macros.
112 protected static $macros = array();
115 * Before PHP 5.4.20/5.5.4 instead of FALSE days will be set to -99999 when the interval instance
116 * was created by DateTime::diff().
118 const PHP_DAYS_FALSE
= -99999;
121 * Mapping of units and factors for cascading.
123 * Should only be modified by changing the factors or referenced constants.
127 public static function getCascadeFactors()
129 return static::$cascadeFactors ?
: array(
130 'minutes' => array(Carbon
::SECONDS_PER_MINUTE
, 'seconds'),
131 'hours' => array(Carbon
::MINUTES_PER_HOUR
, 'minutes'),
132 'dayz' => array(Carbon
::HOURS_PER_DAY
, 'hours'),
133 'months' => array(Carbon
::DAYS_PER_WEEK
* Carbon
::WEEKS_PER_MONTH
, 'dayz'),
134 'years' => array(Carbon
::MONTHS_PER_YEAR
, 'months'),
138 private static function standardizeUnit($unit)
140 $unit = rtrim($unit, 'sz').'s';
142 return $unit === 'days' ?
'dayz' : $unit;
145 private static function getFlipCascadeFactors()
147 if (!self
::$flipCascadeFactors) {
148 self
::$flipCascadeFactors = array();
149 foreach (static::getCascadeFactors() as $to => $tuple) {
150 list($factor, $from) = $tuple;
152 self
::$flipCascadeFactors[self
::standardizeUnit($from)] = array(self
::standardizeUnit($to), $factor);
156 return self
::$flipCascadeFactors;
160 * @param array $cascadeFactors
162 public static function setCascadeFactors(array $cascadeFactors)
164 self
::$flipCascadeFactors = null;
165 static::$cascadeFactors = $cascadeFactors;
169 * Determine if the interval was created via DateTime:diff() or not.
171 * @param DateInterval $interval
175 private static function wasCreatedFromDiff(DateInterval
$interval)
177 return $interval->days
!== false && $interval->days
!== static::PHP_DAYS_FALSE
;
180 ///////////////////////////////////////////////////////////////////
181 //////////////////////////// CONSTRUCTORS /////////////////////////
182 ///////////////////////////////////////////////////////////////////
185 * Create a new CarbonInterval instance.
192 * @param int $minutes
193 * @param int $seconds
195 public function __construct($years = 1, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null)
199 if (!is_string($spec) ||
floatval($years) ||
preg_match('/^[0-9.]/', $years)) {
200 $spec = static::PERIOD_PREFIX
;
202 $spec .= $years > 0 ?
$years.static::PERIOD_YEARS
: '';
203 $spec .= $months > 0 ?
$months.static::PERIOD_MONTHS
: '';
206 $specDays +
= $weeks > 0 ?
$weeks * static::getDaysPerWeek() : 0;
207 $specDays +
= $days > 0 ?
$days : 0;
209 $spec .= $specDays > 0 ?
$specDays.static::PERIOD_DAYS
: '';
211 if ($hours > 0 ||
$minutes > 0 ||
$seconds > 0) {
212 $spec .= static::PERIOD_TIME_PREFIX
;
213 $spec .= $hours > 0 ?
$hours.static::PERIOD_HOURS
: '';
214 $spec .= $minutes > 0 ?
$minutes.static::PERIOD_MINUTES
: '';
215 $spec .= $seconds > 0 ?
$seconds.static::PERIOD_SECONDS
: '';
218 if ($spec === static::PERIOD_PREFIX
) {
219 // Allow the zero interval.
220 $spec .= '0'.static::PERIOD_YEARS
;
224 parent
::__construct($spec);
228 * Returns the factor for a given source-to-target couple.
230 * @param string $source
231 * @param string $target
235 public static function getFactor($source, $target)
237 $source = self
::standardizeUnit($source);
238 $target = self
::standardizeUnit($target);
239 $factors = static::getFlipCascadeFactors();
240 if (isset($factors[$source])) {
241 list($to, $factor) = $factors[$source];
242 if ($to === $target) {
251 * Returns current config for days per week.
255 public static function getDaysPerWeek()
257 return static::getFactor('dayz', 'weeks') ?
: Carbon
::DAYS_PER_WEEK
;
261 * Returns current config for hours per day.
265 public static function getHoursPerDay()
267 return static::getFactor('hours', 'dayz') ?
: Carbon
::HOURS_PER_DAY
;
271 * Returns current config for minutes per hour.
275 public static function getMinutesPerHours()
277 return static::getFactor('minutes', 'hours') ?
: Carbon
::MINUTES_PER_HOUR
;
281 * Returns current config for seconds per minute.
285 public static function getSecondsPerMinutes()
287 return static::getFactor('seconds', 'minutes') ?
: Carbon
::SECONDS_PER_MINUTE
;
291 * Create a new CarbonInterval instance from specific values.
292 * This is an alias for the constructor that allows better fluent
293 * syntax as it allows you to do CarbonInterval::create(1)->fn() rather than
294 * (new CarbonInterval(1))->fn().
301 * @param int $minutes
302 * @param int $seconds
306 public static function create($years = 1, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null)
308 return new static($years, $months, $weeks, $days, $hours, $minutes, $seconds);
312 * Get a copy of the instance.
316 public function copy()
318 $date = new static($this->spec());
319 $date->invert
= $this->invert
;
325 * Provide static helpers to create instances. Allows CarbonInterval::years(3).
327 * Note: This is done using the magic method to allow static and instance methods to
328 * have the same names.
330 * @param string $name
335 public static function __callStatic($name, $args)
337 $arg = count($args) === 0 ?
1 : $args[0];
342 return new static($arg);
346 return new static(null, $arg);
350 return new static(null, null, $arg);
355 return new static(null, null, null, $arg);
359 return new static(null, null, null, null, $arg);
363 return new static(null, null, null, null, null, $arg);
367 return new static(null, null, null, null, null, null, $arg);
370 if (static::hasMacro($name)) {
371 return call_user_func_array(
372 array(new static(0), $name), $args
378 * Creates a CarbonInterval from string.
382 * Suffix | Unit | Example | DateInterval expression
383 * -------|---------|---------|------------------------
384 * y | years | 1y | P1Y
385 * mo | months | 3mo | P3M
386 * w | weeks | 2w | P2W
387 * d | days | 28d | P28D
388 * h | hours | 4h | PT4H
389 * m | minutes | 12m | PT12M
390 * s | seconds | 59s | PT59S
392 * e. g. `1w 3d 4h 32m 23s` is converted to 10 days 4 hours 32 minutes and 23 seconds.
395 * - An empty string will return a zero interval
396 * - Fractions are allowed for weeks, days, hours and minutes and will be converted
397 * and rounded to the next smaller value (caution: 0.5w = 4d)
399 * @param string $intervalDefinition
403 public static function fromString($intervalDefinition)
405 if (empty($intervalDefinition)) {
406 return new static(0);
417 $pattern = '/(\d+(?:\.\d+)?)\h*([^\d\h]*)/i';
418 preg_match_all($pattern, $intervalDefinition, $parts, PREG_SET_ORDER
);
419 while ($match = array_shift($parts)) {
420 list($part, $value, $unit) = $match;
421 $intValue = intval($value);
422 $fraction = floatval($value) - $intValue;
423 switch (strtolower($unit)) {
433 $months +
= $intValue;
441 $parts[] = array(null, $fraction * static::getDaysPerWeek(), 'd');
450 $parts[] = array(null, $fraction * static::getHoursPerDay(), 'h');
459 $parts[] = array(null, $fraction * static::getMinutesPerHours(), 'm');
466 $minutes +
= $intValue;
468 $seconds +
= round($fraction * static::getSecondsPerMinutes());
475 $seconds +
= $intValue;
479 throw new InvalidArgumentException(
480 sprintf('Invalid part %s in definition %s', $part, $intervalDefinition)
485 return new static($years, $months, $weeks, $days, $hours, $minutes, $seconds);
489 * Create a CarbonInterval instance from a DateInterval one. Can not instance
490 * DateInterval objects created from DateTime::diff() as you can't externally
491 * set the $days field.
493 * @param DateInterval $di
497 public static function instance(DateInterval
$di)
499 $instance = new static(static::getDateIntervalSpec($di));
500 $instance->invert
= $di->invert
;
506 * Make a CarbonInterval instance from given variable if possible.
508 * Always return a new instance. Parse only strings and only these likely to be intervals (skip dates
509 * and recurrences). Throw an exception for invalid format, but otherwise return null.
513 * @return static|null
515 public static function make($var)
517 if ($var instanceof DateInterval
) {
518 return static::instance($var);
521 if (is_string($var)) {
524 if (substr($var, 0, 1) === 'P') {
525 return new static($var);
528 if (preg_match('/^(?:\h*\d+(?:\.\d+)?\h*[a-z]+)+$/i', $var)) {
529 return static::fromString($var);
534 ///////////////////////////////////////////////////////////////////
535 /////////////////////// LOCALIZATION //////////////////////////////
536 ///////////////////////////////////////////////////////////////////
539 * Initialize the translator instance if necessary.
541 * @return \Symfony\Component\Translation\TranslatorInterface
543 protected static function translator()
545 if (static::$translator === null) {
546 static::$translator = Translator
::get();
549 return static::$translator;
553 * Get the translator instance in use.
555 * @return \Symfony\Component\Translation\TranslatorInterface
557 public static function getTranslator()
559 return static::translator();
563 * Set the translator instance to use.
565 * @param TranslatorInterface $translator
567 public static function setTranslator(TranslatorInterface
$translator)
569 static::$translator = $translator;
573 * Get the current translator locale.
577 public static function getLocale()
579 return static::translator()->getLocale();
583 * Set the current translator locale.
585 * @param string $locale
587 public static function setLocale($locale)
589 return static::translator()->setLocale($locale) !== false;
592 ///////////////////////////////////////////////////////////////////
593 ///////////////////////// GETTERS AND SETTERS /////////////////////
594 ///////////////////////////////////////////////////////////////////
597 * Get a part of the CarbonInterval object.
599 * @param string $name
601 * @throws \InvalidArgumentException
605 public function __get($name)
607 if (substr($name, 0, 5) === 'total') {
608 return $this->total(substr($name, 5));
631 return (int) floor($this->d
/ static::getDaysPerWeek());
633 case 'daysExcludeWeeks':
634 case 'dayzExcludeWeeks':
635 return $this->d %
static::getDaysPerWeek();
638 throw new InvalidArgumentException(sprintf("Unknown getter '%s'", $name));
643 * Set a part of the CarbonInterval object.
645 * @param string $name
648 * @throws \InvalidArgumentException
650 public function __set($name, $val)
662 $this->d
= $val * static::getDaysPerWeek();
684 * Allow setting of weeks and days to be cumulative.
686 * @param int $weeks Number of weeks to set
687 * @param int $days Number of days to set
691 public function weeksAndDays($weeks, $days)
693 $this->dayz
= ($weeks * static::getDaysPerWeek()) +
$days;
699 * Register a custom macro.
701 * @param string $name
702 * @param object|callable $macro
706 public static function macro($name, $macro)
708 static::$macros[$name] = $macro;
712 * Register macros from a mixin object.
714 * @param object $mixin
716 * @throws \ReflectionException
720 public static function mixin($mixin)
722 $reflection = new ReflectionClass($mixin);
724 $methods = $reflection->getMethods(
725 ReflectionMethod
::IS_PUBLIC | ReflectionMethod
::IS_PROTECTED
728 foreach ($methods as $method) {
729 $method->setAccessible(true);
731 static::macro($method->name
, $method->invoke($mixin));
736 * Check if macro is registered.
738 * @param string $name
742 public static function hasMacro($name)
744 return isset(static::$macros[$name]);
750 * @param string $name
751 * @param array $parameters
755 protected function callMacro($name, $parameters)
757 $macro = static::$macros[$name];
759 $reflection = new ReflectionFunction($macro);
761 $reflectionParameters = $reflection->getParameters();
763 $expectedCount = count($reflectionParameters);
764 $actualCount = count($parameters);
766 if ($expectedCount > $actualCount && $reflectionParameters[$expectedCount - 1]->name
=== 'self') {
767 for ($i = $actualCount; $i < $expectedCount - 1; $i++
) {
768 $parameters[] = $reflectionParameters[$i]->getDefaultValue();
771 $parameters[] = $this;
774 if ($macro instanceof Closure
&& method_exists($macro, 'bindTo')) {
775 $macro = $macro->bindTo($this, get_class($this));
778 return call_user_func_array($macro, $parameters);
782 * Allow fluent calls on the setters... CarbonInterval::years(3)->months(5)->day().
784 * Note: This is done using the magic method to allow static and instance methods to
785 * have the same names.
787 * @param string $name
792 public function __call($name, $args)
794 if (static::hasMacro($name)) {
795 return $this->callMacro($name, $args);
798 $arg = count($args) === 0 ?
1 : $args[0];
808 $this->months
= $arg;
813 $this->dayz
= $arg * static::getDaysPerWeek();
829 $this->minutes
= $arg;
834 $this->seconds
= $arg;
842 * Get the current interval in a human readable format in the current locale.
844 * @param bool $short (false by default), returns short units if true
848 public function forHumans($short = false)
851 'year' => array('y', $this->years
),
852 'month' => array('m', $this->months
),
853 'week' => array('w', $this->weeks
),
854 'day' => array('d', $this->daysExcludeWeeks
),
855 'hour' => array('h', $this->hours
),
856 'minute' => array('min', $this->minutes
),
857 'second' => array('s', $this->seconds
),
861 foreach ($periods as $unit => $options) {
862 list($shortUnit, $count) = $options;
864 $parts[] = static::translator()->transChoice($short ?
$shortUnit : $unit, $count, array(':count' => $count));
868 return implode(' ', $parts);
872 * Format the instance as a string using the forHumans() function.
876 public function __toString()
878 return $this->forHumans();
882 * Convert the interval to a CarbonPeriod.
884 * @return CarbonPeriod
886 public function toPeriod()
888 return CarbonPeriod
::createFromArray(
889 array_merge(array($this), func_get_args())
894 * Invert the interval.
898 public function invert()
900 $this->invert
= $this->invert ?
0 : 1;
906 * Add the passed interval to the current instance.
908 * @param DateInterval $interval
912 public function add(DateInterval
$interval)
914 $sign = $interval->invert
=== 1 ?
-1 : 1;
916 if (static::wasCreatedFromDiff($interval)) {
917 $this->dayz +
= $interval->days
* $sign;
919 $this->years +
= $interval->y
* $sign;
920 $this->months +
= $interval->m
* $sign;
921 $this->dayz +
= $interval->d
* $sign;
922 $this->hours +
= $interval->h
* $sign;
923 $this->minutes +
= $interval->i
* $sign;
924 $this->seconds +
= $interval->s
* $sign;
931 * Multiply current instance given number of times
933 * @param float $factor
937 public function times($factor)
940 $this->invert
= $this->invert ?
0 : 1;
944 $this->years
= (int) round($this->years
* $factor);
945 $this->months
= (int) round($this->months
* $factor);
946 $this->dayz
= (int) round($this->dayz
* $factor);
947 $this->hours
= (int) round($this->hours
* $factor);
948 $this->minutes
= (int) round($this->minutes
* $factor);
949 $this->seconds
= (int) round($this->seconds
* $factor);
955 * Get the interval_spec string of a date interval.
957 * @param DateInterval $interval
961 public static function getDateIntervalSpec(DateInterval
$interval)
963 $date = array_filter(array(
964 static::PERIOD_YEARS
=> $interval->y
,
965 static::PERIOD_MONTHS
=> $interval->m
,
966 static::PERIOD_DAYS
=> $interval->d
,
969 $time = array_filter(array(
970 static::PERIOD_HOURS
=> $interval->h
,
971 static::PERIOD_MINUTES
=> $interval->i
,
972 static::PERIOD_SECONDS
=> $interval->s
,
975 $specString = static::PERIOD_PREFIX
;
977 foreach ($date as $key => $value) {
978 $specString .= $value.$key;
981 if (count($time) > 0) {
982 $specString .= static::PERIOD_TIME_PREFIX
;
983 foreach ($time as $key => $value) {
984 $specString .= $value.$key;
988 return $specString === static::PERIOD_PREFIX ?
'PT0S' : $specString;
992 * Get the interval_spec string.
996 public function spec()
998 return static::getDateIntervalSpec($this);
1002 * Comparing 2 date intervals.
1004 * @param DateInterval $a
1005 * @param DateInterval $b
1009 public static function compareDateIntervals(DateInterval
$a, DateInterval
$b)
1011 $current = Carbon
::now();
1012 $passed = $current->copy()->add($b);
1015 if ($current < $passed) {
1018 if ($current > $passed) {
1026 * Comparing with passed interval.
1028 * @param DateInterval $interval
1032 public function compare(DateInterval
$interval)
1034 return static::compareDateIntervals($this, $interval);
1038 * Convert overflowed values into bigger units.
1042 public function cascade()
1044 foreach (static::getFlipCascadeFactors() as $source => $cascade) {
1045 list($target, $factor) = $cascade;
1047 if ($source === 'dayz' && $target === 'weeks') {
1051 $value = $this->$source;
1052 $this->$source = $modulo = $value %
$factor;
1053 $this->$target +
= ($value - $modulo) / $factor;
1060 * Get amount of given unit equivalent to the interval.
1062 * @param string $unit
1064 * @throws \InvalidArgumentException
1068 public function total($unit)
1070 $realUnit = $unit = strtolower($unit);
1072 if (in_array($unit, array('days', 'weeks'))) {
1074 } elseif (!in_array($unit, array('seconds', 'minutes', 'hours', 'dayz', 'months', 'years'))) {
1075 throw new InvalidArgumentException("Unknown unit '$unit'.");
1079 $cumulativeFactor = 0;
1082 foreach (static::getFlipCascadeFactors() as $source => $cascade) {
1083 list($target, $factor) = $cascade;
1085 if ($source === $realUnit) {
1087 $result +
= $this->$source;
1088 $cumulativeFactor = 1;
1091 if ($factor === false) {
1097 $cumulativeFactor = 0;
1102 if ($target === $realUnit) {
1106 if ($cumulativeFactor) {
1107 $cumulativeFactor *= $factor;
1108 $result +
= $this->$target * $cumulativeFactor;
1113 $result = ($result +
$this->$source) / $factor;
1116 if (isset($target) && !$cumulativeFactor) {
1117 $result +
= $this->$target;
1121 throw new \
InvalidArgumentException("Unit $unit have no configuration to get total from other units.");
1124 if ($unit === 'weeks') {
1125 return $result / static::getDaysPerWeek();