CarbonPeriod.php 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580
  1. <?php
  2. /**
  3. * This file is part of the Carbon package.
  4. *
  5. * (c) Brian Nesbitt <brian@nesbot.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Carbon;
  11. use BadMethodCallException;
  12. use Carbon\Traits\Options;
  13. use Closure;
  14. use Countable;
  15. use DateInterval;
  16. use DateTime;
  17. use DateTimeInterface;
  18. use InvalidArgumentException;
  19. use Iterator;
  20. use ReflectionClass;
  21. use ReflectionMethod;
  22. use RuntimeException;
  23. /**
  24. * Substitution of DatePeriod with some modifications and many more features.
  25. *
  26. * @method static CarbonPeriod start($date, $inclusive = null) Create instance specifying start date.
  27. * @method static CarbonPeriod since($date, $inclusive = null) Alias for start().
  28. * @method static CarbonPeriod sinceNow($inclusive = null) Create instance with start date set to now.
  29. * @method static CarbonPeriod end($date = null, $inclusive = null) Create instance specifying end date.
  30. * @method static CarbonPeriod until($date = null, $inclusive = null) Alias for end().
  31. * @method static CarbonPeriod untilNow($inclusive = null) Create instance with end date set to now.
  32. * @method static CarbonPeriod dates($start, $end = null) Create instance with start and end date.
  33. * @method static CarbonPeriod between($start, $end = null) Create instance with start and end date.
  34. * @method static CarbonPeriod recurrences($recurrences = null) Create instance with maximum number of recurrences.
  35. * @method static CarbonPeriod times($recurrences = null) Alias for recurrences().
  36. * @method static CarbonPeriod options($options = null) Create instance with options.
  37. * @method static CarbonPeriod toggle($options, $state = null) Create instance with options toggled on or off.
  38. * @method static CarbonPeriod filter($callback, $name = null) Create instance with filter added to the stack.
  39. * @method static CarbonPeriod push($callback, $name = null) Alias for filter().
  40. * @method static CarbonPeriod prepend($callback, $name = null) Create instance with filter prepened to the stack.
  41. * @method static CarbonPeriod filters(array $filters) Create instance with filters stack.
  42. * @method static CarbonPeriod interval($interval) Create instance with given date interval.
  43. * @method static CarbonPeriod each($interval) Create instance with given date interval.
  44. * @method static CarbonPeriod every($interval) Create instance with given date interval.
  45. * @method static CarbonPeriod step($interval) Create instance with given date interval.
  46. * @method static CarbonPeriod stepBy($interval) Create instance with given date interval.
  47. * @method static CarbonPeriod invert() Create instance with inverted date interval.
  48. * @method static CarbonPeriod years($years = 1) Create instance specifying a number of years for date interval.
  49. * @method static CarbonPeriod year($years = 1) Alias for years().
  50. * @method static CarbonPeriod months($months = 1) Create instance specifying a number of months for date interval.
  51. * @method static CarbonPeriod month($months = 1) Alias for months().
  52. * @method static CarbonPeriod weeks($weeks = 1) Create instance specifying a number of weeks for date interval.
  53. * @method static CarbonPeriod week($weeks = 1) Alias for weeks().
  54. * @method static CarbonPeriod days($days = 1) Create instance specifying a number of days for date interval.
  55. * @method static CarbonPeriod dayz($days = 1) Alias for days().
  56. * @method static CarbonPeriod day($days = 1) Alias for days().
  57. * @method static CarbonPeriod hours($hours = 1) Create instance specifying a number of hours for date interval.
  58. * @method static CarbonPeriod hour($hours = 1) Alias for hours().
  59. * @method static CarbonPeriod minutes($minutes = 1) Create instance specifying a number of minutes for date interval.
  60. * @method static CarbonPeriod minute($minutes = 1) Alias for minutes().
  61. * @method static CarbonPeriod seconds($seconds = 1) Create instance specifying a number of seconds for date interval.
  62. * @method static CarbonPeriod second($seconds = 1) Alias for seconds().
  63. * @method CarbonPeriod start($date, $inclusive = null) Change the period start date.
  64. * @method CarbonPeriod since($date, $inclusive = null) Alias for start().
  65. * @method CarbonPeriod sinceNow($inclusive = null) Change the period start date to now.
  66. * @method CarbonPeriod end($date = null, $inclusive = null) Change the period end date.
  67. * @method CarbonPeriod until($date = null, $inclusive = null) Alias for end().
  68. * @method CarbonPeriod untilNow($inclusive = null) Change the period end date to now.
  69. * @method CarbonPeriod dates($start, $end = null) Change the period start and end date.
  70. * @method CarbonPeriod recurrences($recurrences = null) Change the maximum number of recurrences.
  71. * @method CarbonPeriod times($recurrences = null) Alias for recurrences().
  72. * @method CarbonPeriod options($options = null) Change the period options.
  73. * @method CarbonPeriod toggle($options, $state = null) Toggle given options on or off.
  74. * @method CarbonPeriod filter($callback, $name = null) Add a filter to the stack.
  75. * @method CarbonPeriod push($callback, $name = null) Alias for filter().
  76. * @method CarbonPeriod prepend($callback, $name = null) Prepend a filter to the stack.
  77. * @method CarbonPeriod filters(array $filters = []) Set filters stack.
  78. * @method CarbonPeriod interval($interval) Change the period date interval.
  79. * @method CarbonPeriod invert() Invert the period date interval.
  80. * @method CarbonPeriod years($years = 1) Set the years portion of the date interval.
  81. * @method CarbonPeriod year($years = 1) Alias for years().
  82. * @method CarbonPeriod months($months = 1) Set the months portion of the date interval.
  83. * @method CarbonPeriod month($months = 1) Alias for months().
  84. * @method CarbonPeriod weeks($weeks = 1) Set the weeks portion of the date interval.
  85. * @method CarbonPeriod week($weeks = 1) Alias for weeks().
  86. * @method CarbonPeriod days($days = 1) Set the days portion of the date interval.
  87. * @method CarbonPeriod dayz($days = 1) Alias for days().
  88. * @method CarbonPeriod day($days = 1) Alias for days().
  89. * @method CarbonPeriod hours($hours = 1) Set the hours portion of the date interval.
  90. * @method CarbonPeriod hour($hours = 1) Alias for hours().
  91. * @method CarbonPeriod minutes($minutes = 1) Set the minutes portion of the date interval.
  92. * @method CarbonPeriod minute($minutes = 1) Alias for minutes().
  93. * @method CarbonPeriod seconds($seconds = 1) Set the seconds portion of the date interval.
  94. * @method CarbonPeriod second($seconds = 1) Alias for seconds().
  95. */
  96. class CarbonPeriod implements Iterator, Countable
  97. {
  98. use Options;
  99. /**
  100. * Built-in filters.
  101. *
  102. * @var string
  103. */
  104. const RECURRENCES_FILTER = 'Carbon\CarbonPeriod::filterRecurrences';
  105. const END_DATE_FILTER = 'Carbon\CarbonPeriod::filterEndDate';
  106. /**
  107. * Special value which can be returned by filters to end iteration. Also a filter.
  108. *
  109. * @var string
  110. */
  111. const END_ITERATION = 'Carbon\CarbonPeriod::endIteration';
  112. /**
  113. * Available options.
  114. *
  115. * @var int
  116. */
  117. const EXCLUDE_START_DATE = 1;
  118. const EXCLUDE_END_DATE = 2;
  119. const IMMUTABLE = 4;
  120. /**
  121. * Number of maximum attempts before giving up on finding next valid date.
  122. *
  123. * @var int
  124. */
  125. const NEXT_MAX_ATTEMPTS = 1000;
  126. /**
  127. * The registered macros.
  128. *
  129. * @var array
  130. */
  131. protected static $macros = [];
  132. /**
  133. * Date class of iteration items.
  134. *
  135. * @var string
  136. */
  137. protected $dateClass = Carbon::class;
  138. /**
  139. * Underlying date interval instance. Always present, one day by default.
  140. *
  141. * @var CarbonInterval
  142. */
  143. protected $dateInterval;
  144. /**
  145. * Whether current date interval was set by default.
  146. *
  147. * @var bool
  148. */
  149. protected $isDefaultInterval;
  150. /**
  151. * The filters stack.
  152. *
  153. * @var array
  154. */
  155. protected $filters = [];
  156. /**
  157. * Period start date. Applied on rewind. Always present, now by default.
  158. *
  159. * @var CarbonInterface
  160. */
  161. protected $startDate;
  162. /**
  163. * Period end date. For inverted interval should be before the start date. Applied via a filter.
  164. *
  165. * @var CarbonInterface|null
  166. */
  167. protected $endDate;
  168. /**
  169. * Limit for number of recurrences. Applied via a filter.
  170. *
  171. * @var int|null
  172. */
  173. protected $recurrences;
  174. /**
  175. * Iteration options.
  176. *
  177. * @var int
  178. */
  179. protected $options;
  180. /**
  181. * Index of current date. Always sequential, even if some dates are skipped by filters.
  182. * Equal to null only before the first iteration.
  183. *
  184. * @var int
  185. */
  186. protected $key;
  187. /**
  188. * Current date. May temporarily hold unaccepted value when looking for a next valid date.
  189. * Equal to null only before the first iteration.
  190. *
  191. * @var CarbonInterface
  192. */
  193. protected $current;
  194. /**
  195. * Timezone of current date. Taken from the start date.
  196. *
  197. * @var \DateTimeZone|null
  198. */
  199. protected $timezone;
  200. /**
  201. * The cached validation result for current date.
  202. *
  203. * @var bool|string|null
  204. */
  205. protected $validationResult;
  206. /**
  207. * Timezone handler for settings() method.
  208. *
  209. * @var mixed
  210. */
  211. protected $tzName;
  212. /**
  213. * Create a new instance.
  214. *
  215. * @return static
  216. */
  217. public static function create(...$params)
  218. {
  219. return static::createFromArray($params);
  220. }
  221. /**
  222. * Create a new instance from an array of parameters.
  223. *
  224. * @param array $params
  225. *
  226. * @return static
  227. */
  228. public static function createFromArray(array $params)
  229. {
  230. return new static(...$params);
  231. }
  232. /**
  233. * Create CarbonPeriod from ISO 8601 string.
  234. *
  235. * @param string $iso
  236. * @param int|null $options
  237. *
  238. * @return static
  239. */
  240. public static function createFromIso($iso, $options = null)
  241. {
  242. $params = static::parseIso8601($iso);
  243. $instance = static::createFromArray($params);
  244. if ($options !== null) {
  245. $instance->setOptions($options);
  246. }
  247. return $instance;
  248. }
  249. /**
  250. * Return whether given interval contains non zero value of any time unit.
  251. *
  252. * @param \DateInterval $interval
  253. *
  254. * @return bool
  255. */
  256. protected static function intervalHasTime(DateInterval $interval)
  257. {
  258. return $interval->h || $interval->i || $interval->s || $interval->f;
  259. }
  260. /**
  261. * Return whether given variable is an ISO 8601 specification.
  262. *
  263. * Note: Check is very basic, as actual validation will be done later when parsing.
  264. * We just want to ensure that variable is not any other type of a valid parameter.
  265. *
  266. * @param mixed $var
  267. *
  268. * @return bool
  269. */
  270. protected static function isIso8601($var)
  271. {
  272. if (!is_string($var)) {
  273. return false;
  274. }
  275. // Match slash but not within a timezone name.
  276. $part = '[a-z]+(?:[_-][a-z]+)*';
  277. preg_match("#\b$part/$part\b|(/)#i", $var, $match);
  278. return isset($match[1]);
  279. }
  280. /**
  281. * Parse given ISO 8601 string into an array of arguments.
  282. *
  283. * @param string $iso
  284. *
  285. * @return array
  286. */
  287. protected static function parseIso8601($iso)
  288. {
  289. $result = [];
  290. $interval = null;
  291. $start = null;
  292. $end = null;
  293. foreach (explode('/', $iso) as $key => $part) {
  294. if ($key === 0 && preg_match('/^R([0-9]*)$/', $part, $match)) {
  295. $parsed = strlen($match[1]) ? (int) $match[1] : null;
  296. } elseif ($interval === null && $parsed = CarbonInterval::make($part)) {
  297. $interval = $part;
  298. } elseif ($start === null && $parsed = Carbon::make($part)) {
  299. $start = $part;
  300. } elseif ($end === null && $parsed = Carbon::make(static::addMissingParts($start, $part))) {
  301. $end = $part;
  302. } else {
  303. throw new InvalidArgumentException("Invalid ISO 8601 specification: $iso.");
  304. }
  305. $result[] = $parsed;
  306. }
  307. return $result;
  308. }
  309. /**
  310. * Add missing parts of the target date from the soure date.
  311. *
  312. * @param string $source
  313. * @param string $target
  314. *
  315. * @return string
  316. */
  317. protected static function addMissingParts($source, $target)
  318. {
  319. $pattern = '/'.preg_replace('/[0-9]+/', '[0-9]+', preg_quote($target, '/')).'$/';
  320. $result = preg_replace($pattern, $target, $source, 1, $count);
  321. return $count ? $result : $target;
  322. }
  323. /**
  324. * Register a custom macro.
  325. *
  326. * @example
  327. * ```
  328. * CarbonPeriod::macro('middle', function () {
  329. * return $this->getStartDate()->average($this->getEndDate());
  330. * });
  331. * echo CarbonPeriod::since('2011-05-12')->until('2011-06-03')->middle();
  332. * ```
  333. *
  334. * @param string $name
  335. * @param object|callable $macro
  336. *
  337. * @return void
  338. */
  339. public static function macro($name, $macro)
  340. {
  341. static::$macros[$name] = $macro;
  342. }
  343. /**
  344. * Register macros from a mixin object.
  345. *
  346. * @example
  347. * ```
  348. * CarbonPeriod::mixin(new class {
  349. * public function addDays() {
  350. * return function ($count = 1) {
  351. * return $this->setStartDate(
  352. * $this->getStartDate()->addDays($count)
  353. * )->setEndDate(
  354. * $this->getEndDate()->addDays($count)
  355. * );
  356. * };
  357. * }
  358. * public function subDays() {
  359. * return function ($count = 1) {
  360. * return $this->setStartDate(
  361. * $this->getStartDate()->subDays($count)
  362. * )->setEndDate(
  363. * $this->getEndDate()->subDays($count)
  364. * );
  365. * };
  366. * }
  367. * });
  368. * echo CarbonPeriod::create('2000-01-01', '2000-02-01')->addDays(5)->subDays(3);
  369. * ```
  370. *
  371. * @param object $mixin
  372. *
  373. * @throws \ReflectionException
  374. *
  375. * @return void
  376. */
  377. public static function mixin($mixin)
  378. {
  379. $reflection = new ReflectionClass($mixin);
  380. $methods = $reflection->getMethods(
  381. ReflectionMethod::IS_PUBLIC | ReflectionMethod::IS_PROTECTED
  382. );
  383. foreach ($methods as $method) {
  384. $method->setAccessible(true);
  385. static::macro($method->name, $method->invoke($mixin));
  386. }
  387. }
  388. /**
  389. * Check if macro is registered.
  390. *
  391. * @param string $name
  392. *
  393. * @return bool
  394. */
  395. public static function hasMacro($name)
  396. {
  397. return isset(static::$macros[$name]);
  398. }
  399. /**
  400. * Provide static proxy for instance aliases.
  401. *
  402. * @param string $method
  403. * @param array $parameters
  404. *
  405. * @return mixed
  406. */
  407. public static function __callStatic($method, $parameters)
  408. {
  409. return (new static)->$method(...$parameters);
  410. }
  411. /**
  412. * CarbonPeriod constructor.
  413. *
  414. * @throws InvalidArgumentException
  415. */
  416. public function __construct(...$arguments)
  417. {
  418. // Parse and assign arguments one by one. First argument may be an ISO 8601 spec,
  419. // which will be first parsed into parts and then processed the same way.
  420. if (count($arguments) && static::isIso8601($iso = $arguments[0])) {
  421. array_splice($arguments, 0, 1, static::parseIso8601($iso));
  422. }
  423. foreach ($arguments as $argument) {
  424. if ($this->dateInterval === null &&
  425. (
  426. is_string($argument) && preg_match('/^(\d.*|P[T0-9].*|(?:\h*\d+(?:\.\d+)?\h*[a-z]+)+)$/i', $argument) ||
  427. $argument instanceof DateInterval
  428. ) &&
  429. $parsed = @CarbonInterval::make($argument)
  430. ) {
  431. $this->setDateInterval($parsed);
  432. } elseif ($this->startDate === null && $parsed = Carbon::make($argument)) {
  433. $this->setStartDate($parsed);
  434. } elseif ($this->endDate === null && $parsed = Carbon::make($argument)) {
  435. $this->setEndDate($parsed);
  436. } elseif ($this->recurrences === null && $this->endDate === null && is_numeric($argument)) {
  437. $this->setRecurrences($argument);
  438. } elseif ($this->options === null && (is_int($argument) || $argument === null)) {
  439. $this->setOptions($argument);
  440. } else {
  441. throw new InvalidArgumentException('Invalid constructor parameters.');
  442. }
  443. }
  444. if ($this->startDate === null) {
  445. $this->setStartDate(Carbon::now());
  446. }
  447. if ($this->dateInterval === null) {
  448. $this->setDateInterval(CarbonInterval::day());
  449. $this->isDefaultInterval = true;
  450. }
  451. if ($this->options === null) {
  452. $this->setOptions(0);
  453. }
  454. }
  455. /**
  456. * Return whether given callable is a string pointing to one of Carbon's is* methods
  457. * and should be automatically converted to a filter callback.
  458. *
  459. * @param callable $callable
  460. *
  461. * @return bool
  462. */
  463. protected function isCarbonPredicateMethod($callable)
  464. {
  465. return is_string($callable) && substr($callable, 0, 2) === 'is' && (method_exists($this->dateClass, $callable) || call_user_func([$this->dateClass, 'hasMacro'], $callable));
  466. }
  467. /**
  468. * Set the iteration item class.
  469. *
  470. * @param string $dateClass
  471. *
  472. * @return $this
  473. */
  474. public function setDateClass(string $dateClass)
  475. {
  476. if (!is_a($dateClass, CarbonInterface::class, true)) {
  477. throw new InvalidArgumentException(sprintf(
  478. 'Given class does not implement %s: %s', CarbonInterface::class, $dateClass
  479. ));
  480. }
  481. $this->dateClass = $dateClass;
  482. if (is_a($dateClass, Carbon::class, true)) {
  483. $this->toggleOptions(static::IMMUTABLE, false);
  484. } elseif (is_a($dateClass, CarbonImmutable::class, true)) {
  485. $this->toggleOptions(static::IMMUTABLE, true);
  486. }
  487. return $this;
  488. }
  489. /**
  490. * Returns iteration item date class.
  491. *
  492. * @return string
  493. */
  494. public function getDateClass(): string
  495. {
  496. return $this->dateClass;
  497. }
  498. /**
  499. * Change the period date interval.
  500. *
  501. * @param DateInterval|string $interval
  502. *
  503. * @throws \InvalidArgumentException
  504. *
  505. * @return $this
  506. */
  507. public function setDateInterval($interval)
  508. {
  509. if (!$interval = CarbonInterval::make($interval)) {
  510. throw new InvalidArgumentException('Invalid interval.');
  511. }
  512. if ($interval->spec() === 'PT0S' && !$interval->f) {
  513. throw new InvalidArgumentException('Empty interval is not accepted.');
  514. }
  515. $this->dateInterval = $interval;
  516. $this->isDefaultInterval = false;
  517. $this->handleChangedParameters();
  518. return $this;
  519. }
  520. /**
  521. * Invert the period date interval.
  522. *
  523. * @return $this
  524. */
  525. public function invertDateInterval()
  526. {
  527. $interval = $this->dateInterval->invert();
  528. return $this->setDateInterval($interval);
  529. }
  530. /**
  531. * Set start and end date.
  532. *
  533. * @param DateTime|DateTimeInterface|string $start
  534. * @param DateTime|DateTimeInterface|string|null $end
  535. *
  536. * @return $this
  537. */
  538. public function setDates($start, $end)
  539. {
  540. $this->setStartDate($start);
  541. $this->setEndDate($end);
  542. return $this;
  543. }
  544. /**
  545. * Change the period options.
  546. *
  547. * @param int|null $options
  548. *
  549. * @throws \InvalidArgumentException
  550. *
  551. * @return $this
  552. */
  553. public function setOptions($options)
  554. {
  555. if (!is_int($options) && !is_null($options)) {
  556. throw new InvalidArgumentException('Invalid options.');
  557. }
  558. $this->options = $options ?: 0;
  559. $this->handleChangedParameters();
  560. return $this;
  561. }
  562. /**
  563. * Get the period options.
  564. *
  565. * @return int
  566. */
  567. public function getOptions()
  568. {
  569. return $this->options;
  570. }
  571. /**
  572. * Toggle given options on or off.
  573. *
  574. * @param int $options
  575. * @param bool|null $state
  576. *
  577. * @throws \InvalidArgumentException
  578. *
  579. * @return $this
  580. */
  581. public function toggleOptions($options, $state = null)
  582. {
  583. if ($state === null) {
  584. $state = ($this->options & $options) !== $options;
  585. }
  586. return $this->setOptions(
  587. $state ?
  588. $this->options | $options :
  589. $this->options & ~$options
  590. );
  591. }
  592. /**
  593. * Toggle EXCLUDE_START_DATE option.
  594. *
  595. * @param bool $state
  596. *
  597. * @return $this
  598. */
  599. public function excludeStartDate($state = true)
  600. {
  601. return $this->toggleOptions(static::EXCLUDE_START_DATE, $state);
  602. }
  603. /**
  604. * Toggle EXCLUDE_END_DATE option.
  605. *
  606. * @param bool $state
  607. *
  608. * @return $this
  609. */
  610. public function excludeEndDate($state = true)
  611. {
  612. return $this->toggleOptions(static::EXCLUDE_END_DATE, $state);
  613. }
  614. /**
  615. * Get the underlying date interval.
  616. *
  617. * @return CarbonInterval
  618. */
  619. public function getDateInterval()
  620. {
  621. return $this->dateInterval->copy();
  622. }
  623. /**
  624. * Get start date of the period.
  625. *
  626. * @return CarbonInterface
  627. */
  628. public function getStartDate()
  629. {
  630. return $this->startDate->copy();
  631. }
  632. /**
  633. * Get end date of the period.
  634. *
  635. * @return CarbonInterface|null
  636. */
  637. public function getEndDate()
  638. {
  639. return $this->endDate ? $this->endDate->copy() : null;
  640. }
  641. /**
  642. * Get number of recurrences.
  643. *
  644. * @return int|null
  645. */
  646. public function getRecurrences()
  647. {
  648. return $this->recurrences;
  649. }
  650. /**
  651. * Returns true if the start date should be excluded.
  652. *
  653. * @return bool
  654. */
  655. public function isStartExcluded()
  656. {
  657. return ($this->options & static::EXCLUDE_START_DATE) !== 0;
  658. }
  659. /**
  660. * Returns true if the end date should be excluded.
  661. *
  662. * @return bool
  663. */
  664. public function isEndExcluded()
  665. {
  666. return ($this->options & static::EXCLUDE_END_DATE) !== 0;
  667. }
  668. /**
  669. * Add a filter to the stack.
  670. *
  671. * @param callable $callback
  672. * @param string $name
  673. *
  674. * @return $this
  675. */
  676. public function addFilter($callback, $name = null)
  677. {
  678. $tuple = $this->createFilterTuple(func_get_args());
  679. $this->filters[] = $tuple;
  680. $this->handleChangedParameters();
  681. return $this;
  682. }
  683. /**
  684. * Prepend a filter to the stack.
  685. *
  686. * @param callable $callback
  687. * @param string $name
  688. *
  689. * @return $this
  690. */
  691. public function prependFilter($callback, $name = null)
  692. {
  693. $tuple = $this->createFilterTuple(func_get_args());
  694. array_unshift($this->filters, $tuple);
  695. $this->handleChangedParameters();
  696. return $this;
  697. }
  698. /**
  699. * Create a filter tuple from raw parameters.
  700. *
  701. * Will create an automatic filter callback for one of Carbon's is* methods.
  702. *
  703. * @param array $parameters
  704. *
  705. * @return array
  706. */
  707. protected function createFilterTuple(array $parameters)
  708. {
  709. $method = array_shift($parameters);
  710. if (!$this->isCarbonPredicateMethod($method)) {
  711. return [$method, array_shift($parameters)];
  712. }
  713. return [function ($date) use ($method, $parameters) {
  714. return call_user_func_array([$date, $method], $parameters);
  715. }, $method];
  716. }
  717. /**
  718. * Remove a filter by instance or name.
  719. *
  720. * @param callable|string $filter
  721. *
  722. * @return $this
  723. */
  724. public function removeFilter($filter)
  725. {
  726. $key = is_callable($filter) ? 0 : 1;
  727. $this->filters = array_values(array_filter(
  728. $this->filters,
  729. function ($tuple) use ($key, $filter) {
  730. return $tuple[$key] !== $filter;
  731. }
  732. ));
  733. $this->updateInternalState();
  734. $this->handleChangedParameters();
  735. return $this;
  736. }
  737. /**
  738. * Return whether given instance or name is in the filter stack.
  739. *
  740. * @param callable|string $filter
  741. *
  742. * @return bool
  743. */
  744. public function hasFilter($filter)
  745. {
  746. $key = is_callable($filter) ? 0 : 1;
  747. foreach ($this->filters as $tuple) {
  748. if ($tuple[$key] === $filter) {
  749. return true;
  750. }
  751. }
  752. return false;
  753. }
  754. /**
  755. * Get filters stack.
  756. *
  757. * @return array
  758. */
  759. public function getFilters()
  760. {
  761. return $this->filters;
  762. }
  763. /**
  764. * Set filters stack.
  765. *
  766. * @param array $filters
  767. *
  768. * @return $this
  769. */
  770. public function setFilters(array $filters)
  771. {
  772. $this->filters = $filters;
  773. $this->updateInternalState();
  774. $this->handleChangedParameters();
  775. return $this;
  776. }
  777. /**
  778. * Reset filters stack.
  779. *
  780. * @return $this
  781. */
  782. public function resetFilters()
  783. {
  784. $this->filters = [];
  785. if ($this->endDate !== null) {
  786. $this->filters[] = [static::END_DATE_FILTER, null];
  787. }
  788. if ($this->recurrences !== null) {
  789. $this->filters[] = [static::RECURRENCES_FILTER, null];
  790. }
  791. $this->handleChangedParameters();
  792. return $this;
  793. }
  794. /**
  795. * Update properties after removing built-in filters.
  796. *
  797. * @return void
  798. */
  799. protected function updateInternalState()
  800. {
  801. if (!$this->hasFilter(static::END_DATE_FILTER)) {
  802. $this->endDate = null;
  803. }
  804. if (!$this->hasFilter(static::RECURRENCES_FILTER)) {
  805. $this->recurrences = null;
  806. }
  807. }
  808. /**
  809. * Add a recurrences filter (set maximum number of recurrences).
  810. *
  811. * @param int|null $recurrences
  812. *
  813. * @throws \InvalidArgumentException
  814. *
  815. * @return $this
  816. */
  817. public function setRecurrences($recurrences)
  818. {
  819. if (!is_numeric($recurrences) && !is_null($recurrences) || $recurrences < 0) {
  820. throw new InvalidArgumentException('Invalid number of recurrences.');
  821. }
  822. if ($recurrences === null) {
  823. return $this->removeFilter(static::RECURRENCES_FILTER);
  824. }
  825. $this->recurrences = (int) $recurrences;
  826. if (!$this->hasFilter(static::RECURRENCES_FILTER)) {
  827. return $this->addFilter(static::RECURRENCES_FILTER);
  828. }
  829. $this->handleChangedParameters();
  830. return $this;
  831. }
  832. /**
  833. * Recurrences filter callback (limits number of recurrences).
  834. *
  835. * @param \Carbon\Carbon $current
  836. * @param int $key
  837. *
  838. * @return bool|string
  839. */
  840. protected function filterRecurrences($current, $key)
  841. {
  842. if ($key < $this->recurrences) {
  843. return true;
  844. }
  845. return static::END_ITERATION;
  846. }
  847. /**
  848. * Change the period start date.
  849. *
  850. * @param DateTime|DateTimeInterface|string $date
  851. * @param bool|null $inclusive
  852. *
  853. * @throws \InvalidArgumentException
  854. *
  855. * @return $this
  856. */
  857. public function setStartDate($date, $inclusive = null)
  858. {
  859. if (!$date = call_user_func([$this->dateClass, 'make'], $date)) {
  860. throw new InvalidArgumentException('Invalid start date.');
  861. }
  862. $this->startDate = $date;
  863. if ($inclusive !== null) {
  864. $this->toggleOptions(static::EXCLUDE_START_DATE, !$inclusive);
  865. }
  866. return $this;
  867. }
  868. /**
  869. * Change the period end date.
  870. *
  871. * @param DateTime|DateTimeInterface|string|null $date
  872. * @param bool|null $inclusive
  873. *
  874. * @throws \InvalidArgumentException
  875. *
  876. * @return $this
  877. */
  878. public function setEndDate($date, $inclusive = null)
  879. {
  880. if (!is_null($date) && !$date = call_user_func([$this->dateClass, 'make'], $date)) {
  881. throw new InvalidArgumentException('Invalid end date.');
  882. }
  883. if (!$date) {
  884. return $this->removeFilter(static::END_DATE_FILTER);
  885. }
  886. $this->endDate = $date;
  887. if ($inclusive !== null) {
  888. $this->toggleOptions(static::EXCLUDE_END_DATE, !$inclusive);
  889. }
  890. if (!$this->hasFilter(static::END_DATE_FILTER)) {
  891. return $this->addFilter(static::END_DATE_FILTER);
  892. }
  893. $this->handleChangedParameters();
  894. return $this;
  895. }
  896. /**
  897. * End date filter callback.
  898. *
  899. * @param \Carbon\Carbon $current
  900. *
  901. * @return bool|string
  902. */
  903. protected function filterEndDate($current)
  904. {
  905. if (!$this->isEndExcluded() && $current == $this->endDate) {
  906. return true;
  907. }
  908. if ($this->dateInterval->invert ? $current > $this->endDate : $current < $this->endDate) {
  909. return true;
  910. }
  911. return static::END_ITERATION;
  912. }
  913. /**
  914. * End iteration filter callback.
  915. *
  916. * @return string
  917. */
  918. protected function endIteration()
  919. {
  920. return static::END_ITERATION;
  921. }
  922. /**
  923. * Handle change of the parameters.
  924. */
  925. protected function handleChangedParameters()
  926. {
  927. if (($this->getOptions() & static::IMMUTABLE) && $this->dateClass === Carbon::class) {
  928. $this->setDateClass(CarbonImmutable::class);
  929. } elseif (!($this->getOptions() & static::IMMUTABLE) && $this->dateClass === CarbonImmutable::class) {
  930. $this->setDateClass(Carbon::class);
  931. }
  932. $this->validationResult = null;
  933. }
  934. /**
  935. * Validate current date and stop iteration when necessary.
  936. *
  937. * Returns true when current date is valid, false if it is not, or static::END_ITERATION
  938. * when iteration should be stopped.
  939. *
  940. * @return bool|string
  941. */
  942. protected function validateCurrentDate()
  943. {
  944. if ($this->current === null) {
  945. $this->rewind();
  946. }
  947. // Check after the first rewind to avoid repeating the initial validation.
  948. if ($this->validationResult !== null) {
  949. return $this->validationResult;
  950. }
  951. return $this->validationResult = $this->checkFilters();
  952. }
  953. /**
  954. * Check whether current value and key pass all the filters.
  955. *
  956. * @return bool|string
  957. */
  958. protected function checkFilters()
  959. {
  960. $current = $this->prepareForReturn($this->current);
  961. foreach ($this->filters as $tuple) {
  962. $result = call_user_func(
  963. $tuple[0],
  964. $current->copy(),
  965. $this->key,
  966. $this
  967. );
  968. if ($result === static::END_ITERATION) {
  969. return static::END_ITERATION;
  970. }
  971. if (!$result) {
  972. return false;
  973. }
  974. }
  975. return true;
  976. }
  977. /**
  978. * Prepare given date to be returned to the external logic.
  979. *
  980. * @param CarbonInterface $date
  981. *
  982. * @return CarbonInterface
  983. */
  984. protected function prepareForReturn(CarbonInterface $date)
  985. {
  986. $date = call_user_func([$this->dateClass, 'make'], $date);
  987. if ($this->timezone) {
  988. $date = $date->setTimezone($this->timezone);
  989. }
  990. return $date;
  991. }
  992. /**
  993. * Check if the current position is valid.
  994. *
  995. * @return bool
  996. */
  997. public function valid()
  998. {
  999. return $this->validateCurrentDate() === true;
  1000. }
  1001. /**
  1002. * Return the current key.
  1003. *
  1004. * @return int|null
  1005. */
  1006. public function key()
  1007. {
  1008. if ($this->valid()) {
  1009. return $this->key;
  1010. }
  1011. }
  1012. /**
  1013. * Return the current date.
  1014. *
  1015. * @return CarbonInterface|null
  1016. */
  1017. public function current()
  1018. {
  1019. if ($this->valid()) {
  1020. return $this->prepareForReturn($this->current);
  1021. }
  1022. }
  1023. /**
  1024. * Move forward to the next date.
  1025. *
  1026. * @throws \RuntimeException
  1027. *
  1028. * @return void
  1029. */
  1030. public function next()
  1031. {
  1032. if ($this->current === null) {
  1033. $this->rewind();
  1034. }
  1035. if ($this->validationResult !== static::END_ITERATION) {
  1036. $this->key++;
  1037. $this->incrementCurrentDateUntilValid();
  1038. }
  1039. }
  1040. /**
  1041. * Rewind to the start date.
  1042. *
  1043. * Iterating over a date in the UTC timezone avoids bug during backward DST change.
  1044. *
  1045. * @see https://bugs.php.net/bug.php?id=72255
  1046. * @see https://bugs.php.net/bug.php?id=74274
  1047. * @see https://wiki.php.net/rfc/datetime_and_daylight_saving_time
  1048. *
  1049. * @throws \RuntimeException
  1050. *
  1051. * @return void
  1052. */
  1053. public function rewind()
  1054. {
  1055. $this->key = 0;
  1056. $this->current = call_user_func([$this->dateClass, 'make'], $this->startDate);
  1057. $settings = $this->getSettings();
  1058. $locale = $this->getLocalTranslator()->getLocale();
  1059. if ($locale) {
  1060. $settings['locale'] = $locale;
  1061. }
  1062. $this->current->settings($settings);
  1063. $this->timezone = static::intervalHasTime($this->dateInterval) ? $this->current->getTimezone() : null;
  1064. if ($this->timezone) {
  1065. $this->current = $this->current->utc();
  1066. }
  1067. $this->validationResult = null;
  1068. if ($this->isStartExcluded() || $this->validateCurrentDate() === false) {
  1069. $this->incrementCurrentDateUntilValid();
  1070. }
  1071. }
  1072. /**
  1073. * Skip iterations and returns iteration state (false if ended, true if still valid).
  1074. *
  1075. * @param int $count steps number to skip (1 by default)
  1076. *
  1077. * @return bool
  1078. */
  1079. public function skip($count = 1)
  1080. {
  1081. for ($i = $count; $this->valid() && $i > 0; $i--) {
  1082. $this->next();
  1083. }
  1084. return $this->valid();
  1085. }
  1086. /**
  1087. * Keep incrementing the current date until a valid date is found or the iteration is ended.
  1088. *
  1089. * @throws \RuntimeException
  1090. *
  1091. * @return void
  1092. */
  1093. protected function incrementCurrentDateUntilValid()
  1094. {
  1095. $attempts = 0;
  1096. do {
  1097. $this->current = $this->current->add($this->dateInterval);
  1098. $this->validationResult = null;
  1099. if (++$attempts > static::NEXT_MAX_ATTEMPTS) {
  1100. throw new RuntimeException('Could not find next valid date.');
  1101. }
  1102. } while ($this->validateCurrentDate() === false);
  1103. }
  1104. /**
  1105. * Format the date period as ISO 8601.
  1106. *
  1107. * @return string
  1108. */
  1109. public function toIso8601String()
  1110. {
  1111. $parts = [];
  1112. if ($this->recurrences !== null) {
  1113. $parts[] = 'R'.$this->recurrences;
  1114. }
  1115. $parts[] = $this->startDate->toIso8601String();
  1116. $parts[] = $this->dateInterval->spec();
  1117. if ($this->endDate !== null) {
  1118. $parts[] = $this->endDate->toIso8601String();
  1119. }
  1120. return implode('/', $parts);
  1121. }
  1122. /**
  1123. * Convert the date period into a string.
  1124. *
  1125. * @return string
  1126. */
  1127. public function toString()
  1128. {
  1129. $translator = call_user_func([$this->dateClass, 'getTranslator']);
  1130. $parts = [];
  1131. $format = !$this->startDate->isStartOfDay() || $this->endDate && !$this->endDate->isStartOfDay()
  1132. ? 'Y-m-d H:i:s'
  1133. : 'Y-m-d';
  1134. if ($this->recurrences !== null) {
  1135. $parts[] = $this->translate('period_recurrences', [], $this->recurrences, $translator);
  1136. }
  1137. $parts[] = $this->translate('period_interval', [':interval' => $this->dateInterval->forHumans([
  1138. 'join' => true,
  1139. ])], null, $translator);
  1140. $parts[] = $this->translate('period_start_date', [':date' => $this->startDate->rawFormat($format)], null, $translator);
  1141. if ($this->endDate !== null) {
  1142. $parts[] = $this->translate('period_end_date', [':date' => $this->endDate->rawFormat($format)], null, $translator);
  1143. }
  1144. $result = implode(' ', $parts);
  1145. return mb_strtoupper(mb_substr($result, 0, 1)).mb_substr($result, 1);
  1146. }
  1147. /**
  1148. * Format the date period as ISO 8601.
  1149. *
  1150. * @return string
  1151. */
  1152. public function spec()
  1153. {
  1154. return $this->toIso8601String();
  1155. }
  1156. /**
  1157. * Convert the date period into an array without changing current iteration state.
  1158. *
  1159. * @return array
  1160. */
  1161. public function toArray()
  1162. {
  1163. $state = [
  1164. $this->key,
  1165. $this->current ? $this->current->copy() : null,
  1166. $this->validationResult,
  1167. ];
  1168. $result = iterator_to_array($this);
  1169. [
  1170. $this->key,
  1171. $this->current,
  1172. $this->validationResult
  1173. ] = $state;
  1174. return $result;
  1175. }
  1176. /**
  1177. * Count dates in the date period.
  1178. *
  1179. * @return int
  1180. */
  1181. public function count()
  1182. {
  1183. return count($this->toArray());
  1184. }
  1185. /**
  1186. * Return the first date in the date period.
  1187. *
  1188. * @return CarbonInterface|null
  1189. */
  1190. public function first()
  1191. {
  1192. if ($array = $this->toArray()) {
  1193. return $array[0];
  1194. }
  1195. }
  1196. /**
  1197. * Return the last date in the date period.
  1198. *
  1199. * @return CarbonInterface|null
  1200. */
  1201. public function last()
  1202. {
  1203. if ($array = $this->toArray()) {
  1204. return $array[count($array) - 1];
  1205. }
  1206. }
  1207. /**
  1208. * Call given macro.
  1209. *
  1210. * @param string $name
  1211. * @param array $parameters
  1212. *
  1213. * @return mixed
  1214. */
  1215. protected function callMacro($name, $parameters)
  1216. {
  1217. $macro = static::$macros[$name];
  1218. if ($macro instanceof Closure) {
  1219. return call_user_func_array($macro->bindTo($this, static::class), $parameters);
  1220. }
  1221. return call_user_func_array($macro, $parameters);
  1222. }
  1223. /**
  1224. * Convert the date period into a string.
  1225. *
  1226. * @return string
  1227. */
  1228. public function __toString()
  1229. {
  1230. return $this->toString();
  1231. }
  1232. /**
  1233. * Add aliases for setters.
  1234. *
  1235. * CarbonPeriod::days(3)->hours(5)->invert()
  1236. * ->sinceNow()->until('2010-01-10')
  1237. * ->filter(...)
  1238. * ->count()
  1239. *
  1240. * Note: We use magic method to let static and instance aliases with the same names.
  1241. *
  1242. * @param string $method
  1243. * @param array $parameters
  1244. *
  1245. * @return mixed
  1246. */
  1247. public function __call($method, $parameters)
  1248. {
  1249. if (static::hasMacro($method)) {
  1250. return $this->callMacro($method, $parameters);
  1251. }
  1252. $first = count($parameters) >= 1 ? $parameters[0] : null;
  1253. $second = count($parameters) >= 2 ? $parameters[1] : null;
  1254. switch ($method) {
  1255. case 'start':
  1256. case 'since':
  1257. return $this->setStartDate($first, $second);
  1258. case 'sinceNow':
  1259. return $this->setStartDate(new Carbon, $first);
  1260. case 'end':
  1261. case 'until':
  1262. return $this->setEndDate($first, $second);
  1263. case 'untilNow':
  1264. return $this->setEndDate(new Carbon, $first);
  1265. case 'dates':
  1266. case 'between':
  1267. return $this->setDates($first, $second);
  1268. case 'recurrences':
  1269. case 'times':
  1270. return $this->setRecurrences($first);
  1271. case 'options':
  1272. return $this->setOptions($first);
  1273. case 'toggle':
  1274. return $this->toggleOptions($first, $second);
  1275. case 'filter':
  1276. case 'push':
  1277. return $this->addFilter($first, $second);
  1278. case 'prepend':
  1279. return $this->prependFilter($first, $second);
  1280. case 'filters':
  1281. return $this->setFilters($first ?: []);
  1282. case 'interval':
  1283. case 'each':
  1284. case 'every':
  1285. case 'step':
  1286. case 'stepBy':
  1287. return $this->setDateInterval($first);
  1288. case 'invert':
  1289. return $this->invertDateInterval();
  1290. case 'years':
  1291. case 'year':
  1292. case 'months':
  1293. case 'month':
  1294. case 'weeks':
  1295. case 'week':
  1296. case 'days':
  1297. case 'dayz':
  1298. case 'day':
  1299. case 'hours':
  1300. case 'hour':
  1301. case 'minutes':
  1302. case 'minute':
  1303. case 'seconds':
  1304. case 'second':
  1305. return $this->setDateInterval(call_user_func(
  1306. // Override default P1D when instantiating via fluent setters.
  1307. [$this->isDefaultInterval ? new CarbonInterval('PT0S') : $this->dateInterval, $method],
  1308. count($parameters) === 0 ? 1 : $first
  1309. ));
  1310. }
  1311. if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) {
  1312. throw new BadMethodCallException("Method $method does not exist.");
  1313. }
  1314. return $this;
  1315. }
  1316. /**
  1317. * Set the instance's timezone from a string or object and add/subtract the offset difference.
  1318. *
  1319. * @param \DateTimeZone|string $timezone
  1320. *
  1321. * @return static
  1322. */
  1323. public function shiftTimezone($timezone)
  1324. {
  1325. $this->tzName = $timezone;
  1326. $this->timezone = $timezone;
  1327. return $this;
  1328. }
  1329. /**
  1330. * Returns the end is set, else calculated from start an recurrences.
  1331. *
  1332. * @return CarbonInterface
  1333. */
  1334. public function calculateEnd()
  1335. {
  1336. if ($end = $this->getEndDate()) {
  1337. return $end;
  1338. }
  1339. $dates = iterator_to_array($this);
  1340. return end($dates);
  1341. }
  1342. /**
  1343. * Returns true if the current period overlaps the given one (if 1 parameter passed)
  1344. * or the period between 2 dates (if 2 parameters passed).
  1345. *
  1346. * @param CarbonPeriod|\DateTimeInterface|Carbon|CarbonImmutable|string $rangeOrRangeStart
  1347. * @param \DateTimeInterface|Carbon|CarbonImmutable|string|null $rangeEnd
  1348. *
  1349. * @return bool
  1350. */
  1351. public function overlaps($rangeOrRangeStart, $rangeEnd = null)
  1352. {
  1353. $range = $rangeEnd ? static::create($rangeOrRangeStart, $rangeEnd) : $rangeOrRangeStart;
  1354. if (!($range instanceof self)) {
  1355. $range = static::create($range);
  1356. }
  1357. return $this->calculateEnd() > $range->getStartDate() && $range->calculateEnd() > $this->getStartDate();
  1358. }
  1359. }