Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

CarbonPeriod.php 41KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540
  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. // The array_key_exists and get_object_vars are used as a workaround to check microsecond support.
  259. // Both isset and property_exists will fail on PHP 7.0.14 - 7.0.21 due to the following bug:
  260. // https://bugs.php.net/bug.php?id=74852
  261. return $interval->h || $interval->i || $interval->s || array_key_exists('f', get_object_vars($interval)) && $interval->f;
  262. }
  263. /**
  264. * Return whether given variable is an ISO 8601 specification.
  265. *
  266. * Note: Check is very basic, as actual validation will be done later when parsing.
  267. * We just want to ensure that variable is not any other type of a valid parameter.
  268. *
  269. * @param mixed $var
  270. *
  271. * @return bool
  272. */
  273. protected static function isIso8601($var)
  274. {
  275. if (!is_string($var)) {
  276. return false;
  277. }
  278. // Match slash but not within a timezone name.
  279. $part = '[a-z]+(?:[_-][a-z]+)*';
  280. preg_match("#\b$part/$part\b|(/)#i", $var, $match);
  281. return isset($match[1]);
  282. }
  283. /**
  284. * Parse given ISO 8601 string into an array of arguments.
  285. *
  286. * @param string $iso
  287. *
  288. * @return array
  289. */
  290. protected static function parseIso8601($iso)
  291. {
  292. $result = [];
  293. $interval = null;
  294. $start = null;
  295. $end = null;
  296. foreach (explode('/', $iso) as $key => $part) {
  297. if ($key === 0 && preg_match('/^R([0-9]*)$/', $part, $match)) {
  298. $parsed = strlen($match[1]) ? (int) $match[1] : null;
  299. } elseif ($interval === null && $parsed = CarbonInterval::make($part)) {
  300. $interval = $part;
  301. } elseif ($start === null && $parsed = Carbon::make($part)) {
  302. $start = $part;
  303. } elseif ($end === null && $parsed = Carbon::make(static::addMissingParts($start, $part))) {
  304. $end = $part;
  305. } else {
  306. throw new InvalidArgumentException("Invalid ISO 8601 specification: $iso.");
  307. }
  308. $result[] = $parsed;
  309. }
  310. return $result;
  311. }
  312. /**
  313. * Add missing parts of the target date from the soure date.
  314. *
  315. * @param string $source
  316. * @param string $target
  317. *
  318. * @return string
  319. */
  320. protected static function addMissingParts($source, $target)
  321. {
  322. $pattern = '/'.preg_replace('/[0-9]+/', '[0-9]+', preg_quote($target, '/')).'$/';
  323. $result = preg_replace($pattern, $target, $source, 1, $count);
  324. return $count ? $result : $target;
  325. }
  326. /**
  327. * Register a custom macro.
  328. *
  329. * @example
  330. * ```
  331. * CarbonPeriod::macro('middle', function () {
  332. * return $this->getStartDate()->average($this->getEndDate());
  333. * });
  334. * echo CarbonPeriod::since('2011-05-12')->until('2011-06-03')->middle();
  335. * ```
  336. *
  337. * @param string $name
  338. * @param object|callable $macro
  339. *
  340. * @return void
  341. */
  342. public static function macro($name, $macro)
  343. {
  344. static::$macros[$name] = $macro;
  345. }
  346. /**
  347. * Register macros from a mixin object.
  348. *
  349. * @example
  350. * ```
  351. * CarbonPeriod::mixin(new class {
  352. * public function addDays() {
  353. * return function ($count = 1) {
  354. * return $this->setStartDate(
  355. * $this->getStartDate()->addDays($count)
  356. * )->setEndDate(
  357. * $this->getEndDate()->addDays($count)
  358. * );
  359. * };
  360. * }
  361. * public function subDays() {
  362. * return function ($count = 1) {
  363. * return $this->setStartDate(
  364. * $this->getStartDate()->subDays($count)
  365. * )->setEndDate(
  366. * $this->getEndDate()->subDays($count)
  367. * );
  368. * };
  369. * }
  370. * });
  371. * echo CarbonPeriod::create('2000-01-01', '2000-02-01')->addDays(5)->subDays(3);
  372. * ```
  373. *
  374. * @param object $mixin
  375. *
  376. * @throws \ReflectionException
  377. *
  378. * @return void
  379. */
  380. public static function mixin($mixin)
  381. {
  382. $reflection = new ReflectionClass($mixin);
  383. $methods = $reflection->getMethods(
  384. ReflectionMethod::IS_PUBLIC | ReflectionMethod::IS_PROTECTED
  385. );
  386. foreach ($methods as $method) {
  387. $method->setAccessible(true);
  388. static::macro($method->name, $method->invoke($mixin));
  389. }
  390. }
  391. /**
  392. * Check if macro is registered.
  393. *
  394. * @param string $name
  395. *
  396. * @return bool
  397. */
  398. public static function hasMacro($name)
  399. {
  400. return isset(static::$macros[$name]);
  401. }
  402. /**
  403. * Provide static proxy for instance aliases.
  404. *
  405. * @param string $method
  406. * @param array $parameters
  407. *
  408. * @return mixed
  409. */
  410. public static function __callStatic($method, $parameters)
  411. {
  412. return (new static)->$method(...$parameters);
  413. }
  414. /**
  415. * CarbonPeriod constructor.
  416. *
  417. * @throws InvalidArgumentException
  418. */
  419. public function __construct(...$arguments)
  420. {
  421. // Parse and assign arguments one by one. First argument may be an ISO 8601 spec,
  422. // which will be first parsed into parts and then processed the same way.
  423. if (count($arguments) && static::isIso8601($iso = $arguments[0])) {
  424. array_splice($arguments, 0, 1, static::parseIso8601($iso));
  425. }
  426. foreach ($arguments as $argument) {
  427. if ($this->dateInterval === null &&
  428. (
  429. is_string($argument) && preg_match('/^(\d.*|P[T0-9].*|(?:\h*\d+(?:\.\d+)?\h*[a-z]+)+)$/i', $argument) ||
  430. $argument instanceof DateInterval
  431. ) &&
  432. $parsed = CarbonInterval::make($argument)
  433. ) {
  434. $this->setDateInterval($parsed);
  435. } elseif ($this->startDate === null && $parsed = Carbon::make($argument)) {
  436. $this->setStartDate($parsed);
  437. } elseif ($this->endDate === null && $parsed = Carbon::make($argument)) {
  438. $this->setEndDate($parsed);
  439. } elseif ($this->recurrences === null && $this->endDate === null && is_numeric($argument)) {
  440. $this->setRecurrences($argument);
  441. } elseif ($this->options === null && (is_int($argument) || $argument === null)) {
  442. $this->setOptions($argument);
  443. } else {
  444. throw new InvalidArgumentException('Invalid constructor parameters.');
  445. }
  446. }
  447. if ($this->startDate === null) {
  448. $this->setStartDate(Carbon::now());
  449. }
  450. if ($this->dateInterval === null) {
  451. $this->setDateInterval(CarbonInterval::day());
  452. $this->isDefaultInterval = true;
  453. }
  454. if ($this->options === null) {
  455. $this->setOptions(0);
  456. }
  457. }
  458. /**
  459. * Return whether given callable is a string pointing to one of Carbon's is* methods
  460. * and should be automatically converted to a filter callback.
  461. *
  462. * @param callable $callable
  463. *
  464. * @return bool
  465. */
  466. protected function isCarbonPredicateMethod($callable)
  467. {
  468. return is_string($callable) && substr($callable, 0, 2) === 'is' && (method_exists($this->dateClass, $callable) || call_user_func([$this->dateClass, 'hasMacro'], $callable));
  469. }
  470. /**
  471. * Set the iteration item class.
  472. *
  473. * @param string $dateClass
  474. *
  475. * @return $this
  476. */
  477. public function setDateClass(string $dateClass)
  478. {
  479. if (!is_a($dateClass, CarbonInterface::class, true)) {
  480. throw new InvalidArgumentException(sprintf(
  481. 'Given class does not implement %s: %s', CarbonInterface::class, $dateClass
  482. ));
  483. }
  484. $this->dateClass = $dateClass;
  485. if (is_a($dateClass, Carbon::class, true)) {
  486. $this->toggleOptions(static::IMMUTABLE, false);
  487. } elseif (is_a($dateClass, CarbonImmutable::class, true)) {
  488. $this->toggleOptions(static::IMMUTABLE, true);
  489. }
  490. return $this;
  491. }
  492. /**
  493. * Returns iteration item date class.
  494. *
  495. * @return string
  496. */
  497. public function getDateClass(): string
  498. {
  499. return $this->dateClass;
  500. }
  501. /**
  502. * Change the period date interval.
  503. *
  504. * @param DateInterval|string $interval
  505. *
  506. * @throws \InvalidArgumentException
  507. *
  508. * @return $this
  509. */
  510. public function setDateInterval($interval)
  511. {
  512. if (!$interval = CarbonInterval::make($interval)) {
  513. throw new InvalidArgumentException('Invalid interval.');
  514. }
  515. if ($interval->spec() === 'PT0S') {
  516. throw new InvalidArgumentException('Empty interval is not accepted.');
  517. }
  518. $this->dateInterval = $interval;
  519. $this->isDefaultInterval = false;
  520. $this->handleChangedParameters();
  521. return $this;
  522. }
  523. /**
  524. * Invert the period date interval.
  525. *
  526. * @return $this
  527. */
  528. public function invertDateInterval()
  529. {
  530. $interval = $this->dateInterval->invert();
  531. return $this->setDateInterval($interval);
  532. }
  533. /**
  534. * Set start and end date.
  535. *
  536. * @param DateTime|DateTimeInterface|string $start
  537. * @param DateTime|DateTimeInterface|string|null $end
  538. *
  539. * @return $this
  540. */
  541. public function setDates($start, $end)
  542. {
  543. $this->setStartDate($start);
  544. $this->setEndDate($end);
  545. return $this;
  546. }
  547. /**
  548. * Change the period options.
  549. *
  550. * @param int|null $options
  551. *
  552. * @throws \InvalidArgumentException
  553. *
  554. * @return $this
  555. */
  556. public function setOptions($options)
  557. {
  558. if (!is_int($options) && !is_null($options)) {
  559. throw new InvalidArgumentException('Invalid options.');
  560. }
  561. $this->options = $options ?: 0;
  562. $this->handleChangedParameters();
  563. return $this;
  564. }
  565. /**
  566. * Get the period options.
  567. *
  568. * @return int
  569. */
  570. public function getOptions()
  571. {
  572. return $this->options;
  573. }
  574. /**
  575. * Toggle given options on or off.
  576. *
  577. * @param int $options
  578. * @param bool|null $state
  579. *
  580. * @throws \InvalidArgumentException
  581. *
  582. * @return $this
  583. */
  584. public function toggleOptions($options, $state = null)
  585. {
  586. if ($state === null) {
  587. $state = ($this->options & $options) !== $options;
  588. }
  589. return $this->setOptions(
  590. $state ?
  591. $this->options | $options :
  592. $this->options & ~$options
  593. );
  594. }
  595. /**
  596. * Toggle EXCLUDE_START_DATE option.
  597. *
  598. * @param bool $state
  599. *
  600. * @return $this
  601. */
  602. public function excludeStartDate($state = true)
  603. {
  604. return $this->toggleOptions(static::EXCLUDE_START_DATE, $state);
  605. }
  606. /**
  607. * Toggle EXCLUDE_END_DATE option.
  608. *
  609. * @param bool $state
  610. *
  611. * @return $this
  612. */
  613. public function excludeEndDate($state = true)
  614. {
  615. return $this->toggleOptions(static::EXCLUDE_END_DATE, $state);
  616. }
  617. /**
  618. * Get the underlying date interval.
  619. *
  620. * @return CarbonInterval
  621. */
  622. public function getDateInterval()
  623. {
  624. return $this->dateInterval->copy();
  625. }
  626. /**
  627. * Get start date of the period.
  628. *
  629. * @return CarbonInterface
  630. */
  631. public function getStartDate()
  632. {
  633. return $this->startDate->copy();
  634. }
  635. /**
  636. * Get end date of the period.
  637. *
  638. * @return CarbonInterface|null
  639. */
  640. public function getEndDate()
  641. {
  642. return $this->endDate ? $this->endDate->copy() : null;
  643. }
  644. /**
  645. * Get number of recurrences.
  646. *
  647. * @return int|null
  648. */
  649. public function getRecurrences()
  650. {
  651. return $this->recurrences;
  652. }
  653. /**
  654. * Returns true if the start date should be excluded.
  655. *
  656. * @return bool
  657. */
  658. public function isStartExcluded()
  659. {
  660. return ($this->options & static::EXCLUDE_START_DATE) !== 0;
  661. }
  662. /**
  663. * Returns true if the end date should be excluded.
  664. *
  665. * @return bool
  666. */
  667. public function isEndExcluded()
  668. {
  669. return ($this->options & static::EXCLUDE_END_DATE) !== 0;
  670. }
  671. /**
  672. * Add a filter to the stack.
  673. *
  674. * @param callable $callback
  675. * @param string $name
  676. *
  677. * @return $this
  678. */
  679. public function addFilter($callback, $name = null)
  680. {
  681. $tuple = $this->createFilterTuple(func_get_args());
  682. $this->filters[] = $tuple;
  683. $this->handleChangedParameters();
  684. return $this;
  685. }
  686. /**
  687. * Prepend a filter to the stack.
  688. *
  689. * @param callable $callback
  690. * @param string $name
  691. *
  692. * @return $this
  693. */
  694. public function prependFilter($callback, $name = null)
  695. {
  696. $tuple = $this->createFilterTuple(func_get_args());
  697. array_unshift($this->filters, $tuple);
  698. $this->handleChangedParameters();
  699. return $this;
  700. }
  701. /**
  702. * Create a filter tuple from raw parameters.
  703. *
  704. * Will create an automatic filter callback for one of Carbon's is* methods.
  705. *
  706. * @param array $parameters
  707. *
  708. * @return array
  709. */
  710. protected function createFilterTuple(array $parameters)
  711. {
  712. $method = array_shift($parameters);
  713. if (!$this->isCarbonPredicateMethod($method)) {
  714. return [$method, array_shift($parameters)];
  715. }
  716. return [function ($date) use ($method, $parameters) {
  717. return call_user_func_array([$date, $method], $parameters);
  718. }, $method];
  719. }
  720. /**
  721. * Remove a filter by instance or name.
  722. *
  723. * @param callable|string $filter
  724. *
  725. * @return $this
  726. */
  727. public function removeFilter($filter)
  728. {
  729. $key = is_callable($filter) ? 0 : 1;
  730. $this->filters = array_values(array_filter(
  731. $this->filters,
  732. function ($tuple) use ($key, $filter) {
  733. return $tuple[$key] !== $filter;
  734. }
  735. ));
  736. $this->updateInternalState();
  737. $this->handleChangedParameters();
  738. return $this;
  739. }
  740. /**
  741. * Return whether given instance or name is in the filter stack.
  742. *
  743. * @param callable|string $filter
  744. *
  745. * @return bool
  746. */
  747. public function hasFilter($filter)
  748. {
  749. $key = is_callable($filter) ? 0 : 1;
  750. foreach ($this->filters as $tuple) {
  751. if ($tuple[$key] === $filter) {
  752. return true;
  753. }
  754. }
  755. return false;
  756. }
  757. /**
  758. * Get filters stack.
  759. *
  760. * @return array
  761. */
  762. public function getFilters()
  763. {
  764. return $this->filters;
  765. }
  766. /**
  767. * Set filters stack.
  768. *
  769. * @param array $filters
  770. *
  771. * @return $this
  772. */
  773. public function setFilters(array $filters)
  774. {
  775. $this->filters = $filters;
  776. $this->updateInternalState();
  777. $this->handleChangedParameters();
  778. return $this;
  779. }
  780. /**
  781. * Reset filters stack.
  782. *
  783. * @return $this
  784. */
  785. public function resetFilters()
  786. {
  787. $this->filters = [];
  788. if ($this->endDate !== null) {
  789. $this->filters[] = [static::END_DATE_FILTER, null];
  790. }
  791. if ($this->recurrences !== null) {
  792. $this->filters[] = [static::RECURRENCES_FILTER, null];
  793. }
  794. $this->handleChangedParameters();
  795. return $this;
  796. }
  797. /**
  798. * Update properties after removing built-in filters.
  799. *
  800. * @return void
  801. */
  802. protected function updateInternalState()
  803. {
  804. if (!$this->hasFilter(static::END_DATE_FILTER)) {
  805. $this->endDate = null;
  806. }
  807. if (!$this->hasFilter(static::RECURRENCES_FILTER)) {
  808. $this->recurrences = null;
  809. }
  810. }
  811. /**
  812. * Add a recurrences filter (set maximum number of recurrences).
  813. *
  814. * @param int|null $recurrences
  815. *
  816. * @throws \InvalidArgumentException
  817. *
  818. * @return $this
  819. */
  820. public function setRecurrences($recurrences)
  821. {
  822. if (!is_numeric($recurrences) && !is_null($recurrences) || $recurrences < 0) {
  823. throw new InvalidArgumentException('Invalid number of recurrences.');
  824. }
  825. if ($recurrences === null) {
  826. return $this->removeFilter(static::RECURRENCES_FILTER);
  827. }
  828. $this->recurrences = (int) $recurrences;
  829. if (!$this->hasFilter(static::RECURRENCES_FILTER)) {
  830. return $this->addFilter(static::RECURRENCES_FILTER);
  831. }
  832. $this->handleChangedParameters();
  833. return $this;
  834. }
  835. /**
  836. * Recurrences filter callback (limits number of recurrences).
  837. *
  838. * @param \Carbon\Carbon $current
  839. * @param int $key
  840. *
  841. * @return bool|string
  842. */
  843. protected function filterRecurrences($current, $key)
  844. {
  845. if ($key < $this->recurrences) {
  846. return true;
  847. }
  848. return static::END_ITERATION;
  849. }
  850. /**
  851. * Change the period start date.
  852. *
  853. * @param DateTime|DateTimeInterface|string $date
  854. * @param bool|null $inclusive
  855. *
  856. * @throws \InvalidArgumentException
  857. *
  858. * @return $this
  859. */
  860. public function setStartDate($date, $inclusive = null)
  861. {
  862. if (!$date = call_user_func([$this->dateClass, 'make'], $date)) {
  863. throw new InvalidArgumentException('Invalid start date.');
  864. }
  865. $this->startDate = $date;
  866. if ($inclusive !== null) {
  867. $this->toggleOptions(static::EXCLUDE_START_DATE, !$inclusive);
  868. }
  869. return $this;
  870. }
  871. /**
  872. * Change the period end date.
  873. *
  874. * @param DateTime|DateTimeInterface|string|null $date
  875. * @param bool|null $inclusive
  876. *
  877. * @throws \InvalidArgumentException
  878. *
  879. * @return $this
  880. */
  881. public function setEndDate($date, $inclusive = null)
  882. {
  883. if (!is_null($date) && !$date = call_user_func([$this->dateClass, 'make'], $date)) {
  884. throw new InvalidArgumentException('Invalid end date.');
  885. }
  886. if (!$date) {
  887. return $this->removeFilter(static::END_DATE_FILTER);
  888. }
  889. $this->endDate = $date;
  890. if ($inclusive !== null) {
  891. $this->toggleOptions(static::EXCLUDE_END_DATE, !$inclusive);
  892. }
  893. if (!$this->hasFilter(static::END_DATE_FILTER)) {
  894. return $this->addFilter(static::END_DATE_FILTER);
  895. }
  896. $this->handleChangedParameters();
  897. return $this;
  898. }
  899. /**
  900. * End date filter callback.
  901. *
  902. * @param \Carbon\Carbon $current
  903. *
  904. * @return bool|string
  905. */
  906. protected function filterEndDate($current)
  907. {
  908. if (!$this->isEndExcluded() && $current == $this->endDate) {
  909. return true;
  910. }
  911. if ($this->dateInterval->invert ? $current > $this->endDate : $current < $this->endDate) {
  912. return true;
  913. }
  914. return static::END_ITERATION;
  915. }
  916. /**
  917. * End iteration filter callback.
  918. *
  919. * @return string
  920. */
  921. protected function endIteration()
  922. {
  923. return static::END_ITERATION;
  924. }
  925. /**
  926. * Handle change of the parameters.
  927. */
  928. protected function handleChangedParameters()
  929. {
  930. if (($this->getOptions() & static::IMMUTABLE) && $this->dateClass === Carbon::class) {
  931. $this->setDateClass(CarbonImmutable::class);
  932. } elseif (!($this->getOptions() & static::IMMUTABLE) && $this->dateClass === CarbonImmutable::class) {
  933. $this->setDateClass(Carbon::class);
  934. }
  935. $this->validationResult = null;
  936. }
  937. /**
  938. * Validate current date and stop iteration when necessary.
  939. *
  940. * Returns true when current date is valid, false if it is not, or static::END_ITERATION
  941. * when iteration should be stopped.
  942. *
  943. * @return bool|string
  944. */
  945. protected function validateCurrentDate()
  946. {
  947. if ($this->current === null) {
  948. $this->rewind();
  949. }
  950. // Check after the first rewind to avoid repeating the initial validation.
  951. if ($this->validationResult !== null) {
  952. return $this->validationResult;
  953. }
  954. return $this->validationResult = $this->checkFilters();
  955. }
  956. /**
  957. * Check whether current value and key pass all the filters.
  958. *
  959. * @return bool|string
  960. */
  961. protected function checkFilters()
  962. {
  963. $current = $this->prepareForReturn($this->current);
  964. foreach ($this->filters as $tuple) {
  965. $result = call_user_func(
  966. $tuple[0],
  967. $current->copy(),
  968. $this->key,
  969. $this
  970. );
  971. if ($result === static::END_ITERATION) {
  972. return static::END_ITERATION;
  973. }
  974. if (!$result) {
  975. return false;
  976. }
  977. }
  978. return true;
  979. }
  980. /**
  981. * Prepare given date to be returned to the external logic.
  982. *
  983. * @param CarbonInterface $date
  984. *
  985. * @return Carbon
  986. */
  987. protected function prepareForReturn(CarbonInterface $date)
  988. {
  989. $date = call_user_func([$this->dateClass, 'make'], $date);
  990. if ($this->timezone) {
  991. $date = $date->setTimezone($this->timezone);
  992. }
  993. return $date;
  994. }
  995. /**
  996. * Check if the current position is valid.
  997. *
  998. * @return bool
  999. */
  1000. public function valid()
  1001. {
  1002. return $this->validateCurrentDate() === true;
  1003. }
  1004. /**
  1005. * Return the current key.
  1006. *
  1007. * @return int|null
  1008. */
  1009. public function key()
  1010. {
  1011. if ($this->valid()) {
  1012. return $this->key;
  1013. }
  1014. }
  1015. /**
  1016. * Return the current date.
  1017. *
  1018. * @return Carbon|null
  1019. */
  1020. public function current()
  1021. {
  1022. if ($this->valid()) {
  1023. return $this->prepareForReturn($this->current);
  1024. }
  1025. }
  1026. /**
  1027. * Move forward to the next date.
  1028. *
  1029. * @throws \RuntimeException
  1030. *
  1031. * @return void
  1032. */
  1033. public function next()
  1034. {
  1035. if ($this->current === null) {
  1036. $this->rewind();
  1037. }
  1038. if ($this->validationResult !== static::END_ITERATION) {
  1039. $this->key++;
  1040. $this->incrementCurrentDateUntilValid();
  1041. }
  1042. }
  1043. /**
  1044. * Rewind to the start date.
  1045. *
  1046. * Iterating over a date in the UTC timezone avoids bug during backward DST change.
  1047. *
  1048. * @see https://bugs.php.net/bug.php?id=72255
  1049. * @see https://bugs.php.net/bug.php?id=74274
  1050. * @see https://wiki.php.net/rfc/datetime_and_daylight_saving_time
  1051. *
  1052. * @throws \RuntimeException
  1053. *
  1054. * @return void
  1055. */
  1056. public function rewind()
  1057. {
  1058. $this->key = 0;
  1059. $this->current = call_user_func([$this->dateClass, 'make'], $this->startDate);
  1060. $settings = $this->getSettings();
  1061. $locale = $this->getLocalTranslator()->getLocale();
  1062. if ($locale) {
  1063. $settings['locale'] = $locale;
  1064. }
  1065. $this->current->settings($settings);
  1066. $this->timezone = static::intervalHasTime($this->dateInterval) ? $this->current->getTimezone() : null;
  1067. if ($this->timezone) {
  1068. $this->current = $this->current->utc();
  1069. }
  1070. $this->validationResult = null;
  1071. if ($this->isStartExcluded() || $this->validateCurrentDate() === false) {
  1072. $this->incrementCurrentDateUntilValid();
  1073. }
  1074. }
  1075. /**
  1076. * Skip iterations and returns iteration state (false if ended, true if still valid).
  1077. *
  1078. * @param int $count steps number to skip (1 by default)
  1079. *
  1080. * @return bool
  1081. */
  1082. public function skip($count = 1)
  1083. {
  1084. for ($i = $count; $this->valid() && $i > 0; $i--) {
  1085. $this->next();
  1086. }
  1087. return $this->valid();
  1088. }
  1089. /**
  1090. * Keep incrementing the current date until a valid date is found or the iteration is ended.
  1091. *
  1092. * @throws \RuntimeException
  1093. *
  1094. * @return void
  1095. */
  1096. protected function incrementCurrentDateUntilValid()
  1097. {
  1098. $attempts = 0;
  1099. do {
  1100. $this->current = $this->current->add($this->dateInterval);
  1101. $this->validationResult = null;
  1102. if (++$attempts > static::NEXT_MAX_ATTEMPTS) {
  1103. throw new RuntimeException('Could not find next valid date.');
  1104. }
  1105. } while ($this->validateCurrentDate() === false);
  1106. }
  1107. /**
  1108. * Format the date period as ISO 8601.
  1109. *
  1110. * @return string
  1111. */
  1112. public function toIso8601String()
  1113. {
  1114. $parts = [];
  1115. if ($this->recurrences !== null) {
  1116. $parts[] = 'R'.$this->recurrences;
  1117. }
  1118. $parts[] = $this->startDate->toIso8601String();
  1119. $parts[] = $this->dateInterval->spec();
  1120. if ($this->endDate !== null) {
  1121. $parts[] = $this->endDate->toIso8601String();
  1122. }
  1123. return implode('/', $parts);
  1124. }
  1125. /**
  1126. * Convert the date period into a string.
  1127. *
  1128. * @return string
  1129. */
  1130. public function toString()
  1131. {
  1132. $translator = call_user_func([$this->dateClass, 'getTranslator']);
  1133. $parts = [];
  1134. $format = !$this->startDate->isStartOfDay() || $this->endDate && !$this->endDate->isStartOfDay()
  1135. ? 'Y-m-d H:i:s'
  1136. : 'Y-m-d';
  1137. if ($this->recurrences !== null) {
  1138. $parts[] = $this->translate('period_recurrences', [], $this->recurrences, $translator);
  1139. }
  1140. $parts[] = $this->translate('period_interval', [':interval' => $this->dateInterval->forHumans([
  1141. 'join' => true,
  1142. ])], null, $translator);
  1143. $parts[] = $this->translate('period_start_date', [':date' => $this->startDate->rawFormat($format)], null, $translator);
  1144. if ($this->endDate !== null) {
  1145. $parts[] = $this->translate('period_end_date', [':date' => $this->endDate->rawFormat($format)], null, $translator);
  1146. }
  1147. $result = implode(' ', $parts);
  1148. return mb_strtoupper(mb_substr($result, 0, 1)).mb_substr($result, 1);
  1149. }
  1150. /**
  1151. * Format the date period as ISO 8601.
  1152. *
  1153. * @return string
  1154. */
  1155. public function spec()
  1156. {
  1157. return $this->toIso8601String();
  1158. }
  1159. /**
  1160. * Convert the date period into an array without changing current iteration state.
  1161. *
  1162. * @return array
  1163. */
  1164. public function toArray()
  1165. {
  1166. $state = [
  1167. $this->key,
  1168. $this->current ? $this->current->copy() : null,
  1169. $this->validationResult,
  1170. ];
  1171. $result = iterator_to_array($this);
  1172. [
  1173. $this->key,
  1174. $this->current,
  1175. $this->validationResult
  1176. ] = $state;
  1177. return $result;
  1178. }
  1179. /**
  1180. * Count dates in the date period.
  1181. *
  1182. * @return int
  1183. */
  1184. public function count()
  1185. {
  1186. return count($this->toArray());
  1187. }
  1188. /**
  1189. * Return the first date in the date period.
  1190. *
  1191. * @return Carbon|null
  1192. */
  1193. public function first()
  1194. {
  1195. if ($array = $this->toArray()) {
  1196. return $array[0];
  1197. }
  1198. }
  1199. /**
  1200. * Return the last date in the date period.
  1201. *
  1202. * @return Carbon|null
  1203. */
  1204. public function last()
  1205. {
  1206. if ($array = $this->toArray()) {
  1207. return $array[count($array) - 1];
  1208. }
  1209. }
  1210. /**
  1211. * Call given macro.
  1212. *
  1213. * @param string $name
  1214. * @param array $parameters
  1215. *
  1216. * @return mixed
  1217. */
  1218. protected function callMacro($name, $parameters)
  1219. {
  1220. $macro = static::$macros[$name];
  1221. if ($macro instanceof Closure) {
  1222. return call_user_func_array($macro->bindTo($this, static::class), $parameters);
  1223. }
  1224. return call_user_func_array($macro, $parameters);
  1225. }
  1226. /**
  1227. * Convert the date period into a string.
  1228. *
  1229. * @return string
  1230. */
  1231. public function __toString()
  1232. {
  1233. return $this->toString();
  1234. }
  1235. /**
  1236. * Add aliases for setters.
  1237. *
  1238. * CarbonPeriod::days(3)->hours(5)->invert()
  1239. * ->sinceNow()->until('2010-01-10')
  1240. * ->filter(...)
  1241. * ->count()
  1242. *
  1243. * Note: We use magic method to let static and instance aliases with the same names.
  1244. *
  1245. * @param string $method
  1246. * @param array $parameters
  1247. *
  1248. * @return mixed
  1249. */
  1250. public function __call($method, $parameters)
  1251. {
  1252. if (static::hasMacro($method)) {
  1253. return $this->callMacro($method, $parameters);
  1254. }
  1255. $first = count($parameters) >= 1 ? $parameters[0] : null;
  1256. $second = count($parameters) >= 2 ? $parameters[1] : null;
  1257. switch ($method) {
  1258. case 'start':
  1259. case 'since':
  1260. return $this->setStartDate($first, $second);
  1261. case 'sinceNow':
  1262. return $this->setStartDate(new Carbon, $first);
  1263. case 'end':
  1264. case 'until':
  1265. return $this->setEndDate($first, $second);
  1266. case 'untilNow':
  1267. return $this->setEndDate(new Carbon, $first);
  1268. case 'dates':
  1269. case 'between':
  1270. return $this->setDates($first, $second);
  1271. case 'recurrences':
  1272. case 'times':
  1273. return $this->setRecurrences($first);
  1274. case 'options':
  1275. return $this->setOptions($first);
  1276. case 'toggle':
  1277. return $this->toggleOptions($first, $second);
  1278. case 'filter':
  1279. case 'push':
  1280. return $this->addFilter($first, $second);
  1281. case 'prepend':
  1282. return $this->prependFilter($first, $second);
  1283. case 'filters':
  1284. return $this->setFilters($first ?: []);
  1285. case 'interval':
  1286. case 'each':
  1287. case 'every':
  1288. case 'step':
  1289. case 'stepBy':
  1290. return $this->setDateInterval($first);
  1291. case 'invert':
  1292. return $this->invertDateInterval();
  1293. case 'years':
  1294. case 'year':
  1295. case 'months':
  1296. case 'month':
  1297. case 'weeks':
  1298. case 'week':
  1299. case 'days':
  1300. case 'dayz':
  1301. case 'day':
  1302. case 'hours':
  1303. case 'hour':
  1304. case 'minutes':
  1305. case 'minute':
  1306. case 'seconds':
  1307. case 'second':
  1308. return $this->setDateInterval(call_user_func(
  1309. // Override default P1D when instantiating via fluent setters.
  1310. [$this->isDefaultInterval ? new CarbonInterval('PT0S') : $this->dateInterval, $method],
  1311. count($parameters) === 0 ? 1 : $first
  1312. ));
  1313. }
  1314. if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) {
  1315. throw new BadMethodCallException("Method $method does not exist.");
  1316. }
  1317. return $this;
  1318. }
  1319. public function shiftTimezone($timezone)
  1320. {
  1321. $this->tzName = $timezone;
  1322. $this->timezone = $timezone;
  1323. return $this;
  1324. }
  1325. }