CarbonInterval.php 104 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054
  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 Carbon\Exceptions\BadFluentConstructorException;
  12. use Carbon\Exceptions\BadFluentSetterException;
  13. use Carbon\Exceptions\InvalidCastException;
  14. use Carbon\Exceptions\InvalidIntervalException;
  15. use Carbon\Exceptions\OutOfRangeException;
  16. use Carbon\Exceptions\ParseErrorException;
  17. use Carbon\Exceptions\UnitNotConfiguredException;
  18. use Carbon\Exceptions\UnknownGetterException;
  19. use Carbon\Exceptions\UnknownSetterException;
  20. use Carbon\Exceptions\UnknownUnitException;
  21. use Carbon\Traits\IntervalRounding;
  22. use Carbon\Traits\IntervalStep;
  23. use Carbon\Traits\MagicParameter;
  24. use Carbon\Traits\Mixin;
  25. use Carbon\Traits\Options;
  26. use Carbon\Traits\ToStringFormat;
  27. use Closure;
  28. use DateInterval;
  29. use DateMalformedIntervalStringException;
  30. use DateTimeInterface;
  31. use DateTimeZone;
  32. use Exception;
  33. use InvalidArgumentException;
  34. use ReflectionException;
  35. use ReturnTypeWillChange;
  36. use RuntimeException;
  37. use Throwable;
  38. /**
  39. * A simple API extension for DateInterval.
  40. * The implementation provides helpers to handle weeks but only days are saved.
  41. * Weeks are calculated based on the total days of the current instance.
  42. *
  43. * @property int $years Total years of the current interval.
  44. * @property int $months Total months of the current interval.
  45. * @property int $weeks Total weeks of the current interval calculated from the days.
  46. * @property int $dayz Total days of the current interval (weeks * 7 + days).
  47. * @property int $hours Total hours of the current interval.
  48. * @property int $minutes Total minutes of the current interval.
  49. * @property int $seconds Total seconds of the current interval.
  50. * @property int $microseconds Total microseconds of the current interval.
  51. * @property int $milliseconds Total milliseconds of the current interval.
  52. * @property int $microExcludeMilli Remaining microseconds without the milliseconds.
  53. * @property int $dayzExcludeWeeks Total days remaining in the final week of the current instance (days % 7).
  54. * @property int $daysExcludeWeeks alias of dayzExcludeWeeks
  55. * @property-read float $totalYears Number of years equivalent to the interval.
  56. * @property-read float $totalMonths Number of months equivalent to the interval.
  57. * @property-read float $totalWeeks Number of weeks equivalent to the interval.
  58. * @property-read float $totalDays Number of days equivalent to the interval.
  59. * @property-read float $totalDayz Alias for totalDays.
  60. * @property-read float $totalHours Number of hours equivalent to the interval.
  61. * @property-read float $totalMinutes Number of minutes equivalent to the interval.
  62. * @property-read float $totalSeconds Number of seconds equivalent to the interval.
  63. * @property-read float $totalMilliseconds Number of milliseconds equivalent to the interval.
  64. * @property-read float $totalMicroseconds Number of microseconds equivalent to the interval.
  65. * @property-read string $locale locale of the current instance
  66. *
  67. * @method static CarbonInterval years($years = 1) Create instance specifying a number of years or modify the number of years if called on an instance.
  68. * @method static CarbonInterval year($years = 1) Alias for years()
  69. * @method static CarbonInterval months($months = 1) Create instance specifying a number of months or modify the number of months if called on an instance.
  70. * @method static CarbonInterval month($months = 1) Alias for months()
  71. * @method static CarbonInterval weeks($weeks = 1) Create instance specifying a number of weeks or modify the number of weeks if called on an instance.
  72. * @method static CarbonInterval week($weeks = 1) Alias for weeks()
  73. * @method static CarbonInterval days($days = 1) Create instance specifying a number of days or modify the number of days if called on an instance.
  74. * @method static CarbonInterval dayz($days = 1) Alias for days()
  75. * @method static CarbonInterval daysExcludeWeeks($days = 1) Create instance specifying a number of days or modify the number of days (keeping the current number of weeks) if called on an instance.
  76. * @method static CarbonInterval dayzExcludeWeeks($days = 1) Alias for daysExcludeWeeks()
  77. * @method static CarbonInterval day($days = 1) Alias for days()
  78. * @method static CarbonInterval hours($hours = 1) Create instance specifying a number of hours or modify the number of hours if called on an instance.
  79. * @method static CarbonInterval hour($hours = 1) Alias for hours()
  80. * @method static CarbonInterval minutes($minutes = 1) Create instance specifying a number of minutes or modify the number of minutes if called on an instance.
  81. * @method static CarbonInterval minute($minutes = 1) Alias for minutes()
  82. * @method static CarbonInterval seconds($seconds = 1) Create instance specifying a number of seconds or modify the number of seconds if called on an instance.
  83. * @method static CarbonInterval second($seconds = 1) Alias for seconds()
  84. * @method static CarbonInterval milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds or modify the number of milliseconds if called on an instance.
  85. * @method static CarbonInterval millisecond($milliseconds = 1) Alias for milliseconds()
  86. * @method static CarbonInterval microseconds($microseconds = 1) Create instance specifying a number of microseconds or modify the number of microseconds if called on an instance.
  87. * @method static CarbonInterval microsecond($microseconds = 1) Alias for microseconds()
  88. * @method $this addYears(int $years) Add given number of years to the current interval
  89. * @method $this subYears(int $years) Subtract given number of years to the current interval
  90. * @method $this addMonths(int $months) Add given number of months to the current interval
  91. * @method $this subMonths(int $months) Subtract given number of months to the current interval
  92. * @method $this addWeeks(int|float $weeks) Add given number of weeks to the current interval
  93. * @method $this subWeeks(int|float $weeks) Subtract given number of weeks to the current interval
  94. * @method $this addDays(int|float $days) Add given number of days to the current interval
  95. * @method $this subDays(int|float $days) Subtract given number of days to the current interval
  96. * @method $this addHours(int|float $hours) Add given number of hours to the current interval
  97. * @method $this subHours(int|float $hours) Subtract given number of hours to the current interval
  98. * @method $this addMinutes(int|float $minutes) Add given number of minutes to the current interval
  99. * @method $this subMinutes(int|float $minutes) Subtract given number of minutes to the current interval
  100. * @method $this addSeconds(int|float $seconds) Add given number of seconds to the current interval
  101. * @method $this subSeconds(int|float $seconds) Subtract given number of seconds to the current interval
  102. * @method $this addMilliseconds(int|float $milliseconds) Add given number of milliseconds to the current interval
  103. * @method $this subMilliseconds(int|float $milliseconds) Subtract given number of milliseconds to the current interval
  104. * @method $this addMicroseconds(int|float $microseconds) Add given number of microseconds to the current interval
  105. * @method $this subMicroseconds(int|float $microseconds) Subtract given number of microseconds to the current interval
  106. * @method $this roundYear(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function.
  107. * @method $this roundYears(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function.
  108. * @method $this floorYear(int|float $precision = 1) Truncate the current instance year with given precision.
  109. * @method $this floorYears(int|float $precision = 1) Truncate the current instance year with given precision.
  110. * @method $this ceilYear(int|float $precision = 1) Ceil the current instance year with given precision.
  111. * @method $this ceilYears(int|float $precision = 1) Ceil the current instance year with given precision.
  112. * @method $this roundMonth(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function.
  113. * @method $this roundMonths(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function.
  114. * @method $this floorMonth(int|float $precision = 1) Truncate the current instance month with given precision.
  115. * @method $this floorMonths(int|float $precision = 1) Truncate the current instance month with given precision.
  116. * @method $this ceilMonth(int|float $precision = 1) Ceil the current instance month with given precision.
  117. * @method $this ceilMonths(int|float $precision = 1) Ceil the current instance month with given precision.
  118. * @method $this roundWeek(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function.
  119. * @method $this roundWeeks(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function.
  120. * @method $this floorWeek(int|float $precision = 1) Truncate the current instance day with given precision.
  121. * @method $this floorWeeks(int|float $precision = 1) Truncate the current instance day with given precision.
  122. * @method $this ceilWeek(int|float $precision = 1) Ceil the current instance day with given precision.
  123. * @method $this ceilWeeks(int|float $precision = 1) Ceil the current instance day with given precision.
  124. * @method $this roundDay(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function.
  125. * @method $this roundDays(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function.
  126. * @method $this floorDay(int|float $precision = 1) Truncate the current instance day with given precision.
  127. * @method $this floorDays(int|float $precision = 1) Truncate the current instance day with given precision.
  128. * @method $this ceilDay(int|float $precision = 1) Ceil the current instance day with given precision.
  129. * @method $this ceilDays(int|float $precision = 1) Ceil the current instance day with given precision.
  130. * @method $this roundHour(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function.
  131. * @method $this roundHours(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function.
  132. * @method $this floorHour(int|float $precision = 1) Truncate the current instance hour with given precision.
  133. * @method $this floorHours(int|float $precision = 1) Truncate the current instance hour with given precision.
  134. * @method $this ceilHour(int|float $precision = 1) Ceil the current instance hour with given precision.
  135. * @method $this ceilHours(int|float $precision = 1) Ceil the current instance hour with given precision.
  136. * @method $this roundMinute(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function.
  137. * @method $this roundMinutes(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function.
  138. * @method $this floorMinute(int|float $precision = 1) Truncate the current instance minute with given precision.
  139. * @method $this floorMinutes(int|float $precision = 1) Truncate the current instance minute with given precision.
  140. * @method $this ceilMinute(int|float $precision = 1) Ceil the current instance minute with given precision.
  141. * @method $this ceilMinutes(int|float $precision = 1) Ceil the current instance minute with given precision.
  142. * @method $this roundSecond(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function.
  143. * @method $this roundSeconds(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function.
  144. * @method $this floorSecond(int|float $precision = 1) Truncate the current instance second with given precision.
  145. * @method $this floorSeconds(int|float $precision = 1) Truncate the current instance second with given precision.
  146. * @method $this ceilSecond(int|float $precision = 1) Ceil the current instance second with given precision.
  147. * @method $this ceilSeconds(int|float $precision = 1) Ceil the current instance second with given precision.
  148. * @method $this roundMillennium(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function.
  149. * @method $this roundMillennia(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function.
  150. * @method $this floorMillennium(int|float $precision = 1) Truncate the current instance millennium with given precision.
  151. * @method $this floorMillennia(int|float $precision = 1) Truncate the current instance millennium with given precision.
  152. * @method $this ceilMillennium(int|float $precision = 1) Ceil the current instance millennium with given precision.
  153. * @method $this ceilMillennia(int|float $precision = 1) Ceil the current instance millennium with given precision.
  154. * @method $this roundCentury(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function.
  155. * @method $this roundCenturies(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function.
  156. * @method $this floorCentury(int|float $precision = 1) Truncate the current instance century with given precision.
  157. * @method $this floorCenturies(int|float $precision = 1) Truncate the current instance century with given precision.
  158. * @method $this ceilCentury(int|float $precision = 1) Ceil the current instance century with given precision.
  159. * @method $this ceilCenturies(int|float $precision = 1) Ceil the current instance century with given precision.
  160. * @method $this roundDecade(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function.
  161. * @method $this roundDecades(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function.
  162. * @method $this floorDecade(int|float $precision = 1) Truncate the current instance decade with given precision.
  163. * @method $this floorDecades(int|float $precision = 1) Truncate the current instance decade with given precision.
  164. * @method $this ceilDecade(int|float $precision = 1) Ceil the current instance decade with given precision.
  165. * @method $this ceilDecades(int|float $precision = 1) Ceil the current instance decade with given precision.
  166. * @method $this roundQuarter(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function.
  167. * @method $this roundQuarters(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function.
  168. * @method $this floorQuarter(int|float $precision = 1) Truncate the current instance quarter with given precision.
  169. * @method $this floorQuarters(int|float $precision = 1) Truncate the current instance quarter with given precision.
  170. * @method $this ceilQuarter(int|float $precision = 1) Ceil the current instance quarter with given precision.
  171. * @method $this ceilQuarters(int|float $precision = 1) Ceil the current instance quarter with given precision.
  172. * @method $this roundMillisecond(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function.
  173. * @method $this roundMilliseconds(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function.
  174. * @method $this floorMillisecond(int|float $precision = 1) Truncate the current instance millisecond with given precision.
  175. * @method $this floorMilliseconds(int|float $precision = 1) Truncate the current instance millisecond with given precision.
  176. * @method $this ceilMillisecond(int|float $precision = 1) Ceil the current instance millisecond with given precision.
  177. * @method $this ceilMilliseconds(int|float $precision = 1) Ceil the current instance millisecond with given precision.
  178. * @method $this roundMicrosecond(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function.
  179. * @method $this roundMicroseconds(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function.
  180. * @method $this floorMicrosecond(int|float $precision = 1) Truncate the current instance microsecond with given precision.
  181. * @method $this floorMicroseconds(int|float $precision = 1) Truncate the current instance microsecond with given precision.
  182. * @method $this ceilMicrosecond(int|float $precision = 1) Ceil the current instance microsecond with given precision.
  183. * @method $this ceilMicroseconds(int|float $precision = 1) Ceil the current instance microsecond with given precision.
  184. */
  185. class CarbonInterval extends DateInterval implements CarbonConverterInterface
  186. {
  187. use IntervalRounding;
  188. use IntervalStep;
  189. use MagicParameter;
  190. use Mixin {
  191. Mixin::mixin as baseMixin;
  192. }
  193. use Options;
  194. use ToStringFormat;
  195. /**
  196. * Interval spec period designators
  197. */
  198. public const PERIOD_PREFIX = 'P';
  199. public const PERIOD_YEARS = 'Y';
  200. public const PERIOD_MONTHS = 'M';
  201. public const PERIOD_DAYS = 'D';
  202. public const PERIOD_TIME_PREFIX = 'T';
  203. public const PERIOD_HOURS = 'H';
  204. public const PERIOD_MINUTES = 'M';
  205. public const PERIOD_SECONDS = 'S';
  206. /**
  207. * A translator to ... er ... translate stuff
  208. *
  209. * @var \Symfony\Component\Translation\TranslatorInterface
  210. */
  211. protected static $translator;
  212. /**
  213. * @var array|null
  214. */
  215. protected static $cascadeFactors;
  216. /**
  217. * @var array
  218. */
  219. protected static $formats = [
  220. 'y' => 'y',
  221. 'Y' => 'y',
  222. 'o' => 'y',
  223. 'm' => 'm',
  224. 'n' => 'm',
  225. 'W' => 'weeks',
  226. 'd' => 'd',
  227. 'j' => 'd',
  228. 'z' => 'd',
  229. 'h' => 'h',
  230. 'g' => 'h',
  231. 'H' => 'h',
  232. 'G' => 'h',
  233. 'i' => 'i',
  234. 's' => 's',
  235. 'u' => 'micro',
  236. 'v' => 'milli',
  237. ];
  238. /**
  239. * @var array|null
  240. */
  241. private static $flipCascadeFactors;
  242. /**
  243. * @var bool
  244. */
  245. private static $floatSettersEnabled = false;
  246. /**
  247. * The registered macros.
  248. *
  249. * @var array
  250. */
  251. protected static $macros = [];
  252. /**
  253. * Timezone handler for settings() method.
  254. *
  255. * @var mixed
  256. */
  257. protected $tzName;
  258. /**
  259. * Set the instance's timezone from a string or object.
  260. *
  261. * @param \DateTimeZone|string $tzName
  262. *
  263. * @return static
  264. */
  265. public function setTimezone($tzName)
  266. {
  267. $this->tzName = $tzName;
  268. return $this;
  269. }
  270. /**
  271. * @internal
  272. *
  273. * Set the instance's timezone from a string or object and add/subtract the offset difference.
  274. *
  275. * @param \DateTimeZone|string $tzName
  276. *
  277. * @return static
  278. */
  279. public function shiftTimezone($tzName)
  280. {
  281. $this->tzName = $tzName;
  282. return $this;
  283. }
  284. /**
  285. * Mapping of units and factors for cascading.
  286. *
  287. * Should only be modified by changing the factors or referenced constants.
  288. *
  289. * @return array
  290. */
  291. public static function getCascadeFactors()
  292. {
  293. return static::$cascadeFactors ?: static::getDefaultCascadeFactors();
  294. }
  295. protected static function getDefaultCascadeFactors(): array
  296. {
  297. return [
  298. 'milliseconds' => [Carbon::MICROSECONDS_PER_MILLISECOND, 'microseconds'],
  299. 'seconds' => [Carbon::MILLISECONDS_PER_SECOND, 'milliseconds'],
  300. 'minutes' => [Carbon::SECONDS_PER_MINUTE, 'seconds'],
  301. 'hours' => [Carbon::MINUTES_PER_HOUR, 'minutes'],
  302. 'dayz' => [Carbon::HOURS_PER_DAY, 'hours'],
  303. 'weeks' => [Carbon::DAYS_PER_WEEK, 'dayz'],
  304. 'months' => [Carbon::WEEKS_PER_MONTH, 'weeks'],
  305. 'years' => [Carbon::MONTHS_PER_YEAR, 'months'],
  306. ];
  307. }
  308. private static function standardizeUnit($unit)
  309. {
  310. $unit = rtrim($unit, 'sz').'s';
  311. return $unit === 'days' ? 'dayz' : $unit;
  312. }
  313. private static function getFlipCascadeFactors()
  314. {
  315. if (!self::$flipCascadeFactors) {
  316. self::$flipCascadeFactors = [];
  317. foreach (static::getCascadeFactors() as $to => [$factor, $from]) {
  318. self::$flipCascadeFactors[self::standardizeUnit($from)] = [self::standardizeUnit($to), $factor];
  319. }
  320. }
  321. return self::$flipCascadeFactors;
  322. }
  323. /**
  324. * Set default cascading factors for ->cascade() method.
  325. *
  326. * @param array $cascadeFactors
  327. */
  328. public static function setCascadeFactors(array $cascadeFactors)
  329. {
  330. self::$flipCascadeFactors = null;
  331. static::$cascadeFactors = $cascadeFactors;
  332. }
  333. /**
  334. * This option allow you to opt-in for the Carbon 3 behavior where float
  335. * values will no longer be cast to integer (so truncated).
  336. *
  337. * ⚠️ This settings will be applied globally, which mean your whole application
  338. * code including the third-party dependencies that also may use Carbon will
  339. * adopt the new behavior.
  340. */
  341. public static function enableFloatSetters(bool $floatSettersEnabled = true): void
  342. {
  343. self::$floatSettersEnabled = $floatSettersEnabled;
  344. }
  345. ///////////////////////////////////////////////////////////////////
  346. //////////////////////////// CONSTRUCTORS /////////////////////////
  347. ///////////////////////////////////////////////////////////////////
  348. /**
  349. * Create a new CarbonInterval instance.
  350. *
  351. * @param Closure|DateInterval|string|int|null $years
  352. * @param int|float|null $months
  353. * @param int|float|null $weeks
  354. * @param int|float|null $days
  355. * @param int|float|null $hours
  356. * @param int|float|null $minutes
  357. * @param int|float|null $seconds
  358. * @param int|float|null $microseconds
  359. *
  360. * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval.
  361. */
  362. public function __construct($years = 1, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null)
  363. {
  364. if ($years instanceof Closure) {
  365. $this->step = $years;
  366. $years = null;
  367. }
  368. if ($years instanceof DateInterval) {
  369. parent::__construct(static::getDateIntervalSpec($years));
  370. $this->f = $years->f;
  371. self::copyNegativeUnits($years, $this);
  372. return;
  373. }
  374. $spec = $years;
  375. $isStringSpec = (\is_string($spec) && !preg_match('/^[\d.]/', $spec));
  376. if (!$isStringSpec || (float) $years) {
  377. $spec = static::PERIOD_PREFIX;
  378. $spec .= $years > 0 ? $years.static::PERIOD_YEARS : '';
  379. $spec .= $months > 0 ? $months.static::PERIOD_MONTHS : '';
  380. $specDays = 0;
  381. $specDays += $weeks > 0 ? $weeks * static::getDaysPerWeek() : 0;
  382. $specDays += $days > 0 ? $days : 0;
  383. $spec .= $specDays > 0 ? $specDays.static::PERIOD_DAYS : '';
  384. if ($hours > 0 || $minutes > 0 || $seconds > 0) {
  385. $spec .= static::PERIOD_TIME_PREFIX;
  386. $spec .= $hours > 0 ? $hours.static::PERIOD_HOURS : '';
  387. $spec .= $minutes > 0 ? $minutes.static::PERIOD_MINUTES : '';
  388. $spec .= $seconds > 0 ? $seconds.static::PERIOD_SECONDS : '';
  389. }
  390. if ($spec === static::PERIOD_PREFIX) {
  391. // Allow the zero interval.
  392. $spec .= '0'.static::PERIOD_YEARS;
  393. }
  394. }
  395. try {
  396. parent::__construct($spec);
  397. } catch (Throwable $exception) {
  398. try {
  399. parent::__construct('PT0S');
  400. if ($isStringSpec) {
  401. if (!preg_match('/^P
  402. (?:(?<year>[+-]?\d*(?:\.\d+)?)Y)?
  403. (?:(?<month>[+-]?\d*(?:\.\d+)?)M)?
  404. (?:(?<week>[+-]?\d*(?:\.\d+)?)W)?
  405. (?:(?<day>[+-]?\d*(?:\.\d+)?)D)?
  406. (?:T
  407. (?:(?<hour>[+-]?\d*(?:\.\d+)?)H)?
  408. (?:(?<minute>[+-]?\d*(?:\.\d+)?)M)?
  409. (?:(?<second>[+-]?\d*(?:\.\d+)?)S)?
  410. )?
  411. $/x', $spec, $match)) {
  412. throw new InvalidArgumentException("Invalid duration: $spec");
  413. }
  414. $years = (float) ($match['year'] ?? 0);
  415. $this->assertSafeForInteger('year', $years);
  416. $months = (float) ($match['month'] ?? 0);
  417. $this->assertSafeForInteger('month', $months);
  418. $weeks = (float) ($match['week'] ?? 0);
  419. $this->assertSafeForInteger('week', $weeks);
  420. $days = (float) ($match['day'] ?? 0);
  421. $this->assertSafeForInteger('day', $days);
  422. $hours = (float) ($match['hour'] ?? 0);
  423. $this->assertSafeForInteger('hour', $hours);
  424. $minutes = (float) ($match['minute'] ?? 0);
  425. $this->assertSafeForInteger('minute', $minutes);
  426. $seconds = (float) ($match['second'] ?? 0);
  427. $this->assertSafeForInteger('second', $seconds);
  428. }
  429. $totalDays = (($weeks * static::getDaysPerWeek()) + $days);
  430. $this->assertSafeForInteger('days total (including weeks)', $totalDays);
  431. $this->y = (int) $years;
  432. $this->m = (int) $months;
  433. $this->d = (int) $totalDays;
  434. $this->h = (int) $hours;
  435. $this->i = (int) $minutes;
  436. $this->s = (int) $seconds;
  437. if (
  438. ((float) $this->y) !== $years ||
  439. ((float) $this->m) !== $months ||
  440. ((float) $this->d) !== $totalDays ||
  441. ((float) $this->h) !== $hours ||
  442. ((float) $this->i) !== $minutes ||
  443. ((float) $this->s) !== $seconds
  444. ) {
  445. $this->add(static::fromString(
  446. ($years - $this->y).' years '.
  447. ($months - $this->m).' months '.
  448. ($totalDays - $this->d).' days '.
  449. ($hours - $this->h).' hours '.
  450. ($minutes - $this->i).' minutes '.
  451. ($seconds - $this->s).' seconds '
  452. ));
  453. }
  454. } catch (Throwable $secondException) {
  455. throw $secondException instanceof OutOfRangeException ? $secondException : $exception;
  456. }
  457. }
  458. if ($microseconds !== null) {
  459. $this->f = $microseconds / Carbon::MICROSECONDS_PER_SECOND;
  460. }
  461. }
  462. /**
  463. * Returns the factor for a given source-to-target couple.
  464. *
  465. * @param string $source
  466. * @param string $target
  467. *
  468. * @return int|float|null
  469. */
  470. public static function getFactor($source, $target)
  471. {
  472. $source = self::standardizeUnit($source);
  473. $target = self::standardizeUnit($target);
  474. $factors = self::getFlipCascadeFactors();
  475. if (isset($factors[$source])) {
  476. [$to, $factor] = $factors[$source];
  477. if ($to === $target) {
  478. return $factor;
  479. }
  480. return $factor * static::getFactor($to, $target);
  481. }
  482. return null;
  483. }
  484. /**
  485. * Returns the factor for a given source-to-target couple if set,
  486. * else try to find the appropriate constant as the factor, such as Carbon::DAYS_PER_WEEK.
  487. *
  488. * @param string $source
  489. * @param string $target
  490. *
  491. * @return int|float|null
  492. */
  493. public static function getFactorWithDefault($source, $target)
  494. {
  495. $factor = self::getFactor($source, $target);
  496. if ($factor) {
  497. return $factor;
  498. }
  499. static $defaults = [
  500. 'month' => ['year' => Carbon::MONTHS_PER_YEAR],
  501. 'week' => ['month' => Carbon::WEEKS_PER_MONTH],
  502. 'day' => ['week' => Carbon::DAYS_PER_WEEK],
  503. 'hour' => ['day' => Carbon::HOURS_PER_DAY],
  504. 'minute' => ['hour' => Carbon::MINUTES_PER_HOUR],
  505. 'second' => ['minute' => Carbon::SECONDS_PER_MINUTE],
  506. 'millisecond' => ['second' => Carbon::MILLISECONDS_PER_SECOND],
  507. 'microsecond' => ['millisecond' => Carbon::MICROSECONDS_PER_MILLISECOND],
  508. ];
  509. return $defaults[$source][$target] ?? null;
  510. }
  511. /**
  512. * Returns current config for days per week.
  513. *
  514. * @return int|float
  515. */
  516. public static function getDaysPerWeek()
  517. {
  518. return static::getFactor('dayz', 'weeks') ?: Carbon::DAYS_PER_WEEK;
  519. }
  520. /**
  521. * Returns current config for hours per day.
  522. *
  523. * @return int|float
  524. */
  525. public static function getHoursPerDay()
  526. {
  527. return static::getFactor('hours', 'dayz') ?: Carbon::HOURS_PER_DAY;
  528. }
  529. /**
  530. * Returns current config for minutes per hour.
  531. *
  532. * @return int|float
  533. */
  534. public static function getMinutesPerHour()
  535. {
  536. return static::getFactor('minutes', 'hours') ?: Carbon::MINUTES_PER_HOUR;
  537. }
  538. /**
  539. * Returns current config for seconds per minute.
  540. *
  541. * @return int|float
  542. */
  543. public static function getSecondsPerMinute()
  544. {
  545. return static::getFactor('seconds', 'minutes') ?: Carbon::SECONDS_PER_MINUTE;
  546. }
  547. /**
  548. * Returns current config for microseconds per second.
  549. *
  550. * @return int|float
  551. */
  552. public static function getMillisecondsPerSecond()
  553. {
  554. return static::getFactor('milliseconds', 'seconds') ?: Carbon::MILLISECONDS_PER_SECOND;
  555. }
  556. /**
  557. * Returns current config for microseconds per second.
  558. *
  559. * @return int|float
  560. */
  561. public static function getMicrosecondsPerMillisecond()
  562. {
  563. return static::getFactor('microseconds', 'milliseconds') ?: Carbon::MICROSECONDS_PER_MILLISECOND;
  564. }
  565. /**
  566. * Create a new CarbonInterval instance from specific values.
  567. * This is an alias for the constructor that allows better fluent
  568. * syntax as it allows you to do CarbonInterval::create(1)->fn() rather than
  569. * (new CarbonInterval(1))->fn().
  570. *
  571. * @param int $years
  572. * @param int $months
  573. * @param int $weeks
  574. * @param int $days
  575. * @param int $hours
  576. * @param int $minutes
  577. * @param int $seconds
  578. * @param int $microseconds
  579. *
  580. * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval.
  581. *
  582. * @return static
  583. */
  584. public static function create($years = 1, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null)
  585. {
  586. return new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $microseconds);
  587. }
  588. /**
  589. * Parse a string into a new CarbonInterval object according to the specified format.
  590. *
  591. * @example
  592. * ```
  593. * echo Carboninterval::createFromFormat('H:i', '1:30');
  594. * ```
  595. *
  596. * @param string $format Format of the $interval input string
  597. * @param string|null $interval Input string to convert into an interval
  598. *
  599. * @throws \Carbon\Exceptions\ParseErrorException when the $interval cannot be parsed as an interval.
  600. *
  601. * @return static
  602. */
  603. public static function createFromFormat(string $format, ?string $interval)
  604. {
  605. $instance = new static(0);
  606. $length = mb_strlen($format);
  607. if (preg_match('/s([,.])([uv])$/', $format, $match)) {
  608. $interval = explode($match[1], $interval);
  609. $index = \count($interval) - 1;
  610. $interval[$index] = str_pad($interval[$index], $match[2] === 'v' ? 3 : 6, '0');
  611. $interval = implode($match[1], $interval);
  612. }
  613. $interval = $interval ?? '';
  614. for ($index = 0; $index < $length; $index++) {
  615. $expected = mb_substr($format, $index, 1);
  616. $nextCharacter = mb_substr($interval, 0, 1);
  617. $unit = static::$formats[$expected] ?? null;
  618. if ($unit) {
  619. if (!preg_match('/^-?\d+/', $interval, $match)) {
  620. throw new ParseErrorException('number', $nextCharacter);
  621. }
  622. $interval = mb_substr($interval, mb_strlen($match[0]));
  623. $instance->$unit += (int) ($match[0]);
  624. continue;
  625. }
  626. if ($nextCharacter !== $expected) {
  627. throw new ParseErrorException(
  628. "'$expected'",
  629. $nextCharacter,
  630. 'Allowed substitutes for interval formats are '.implode(', ', array_keys(static::$formats))."\n".
  631. 'See https://php.net/manual/en/function.date.php for their meaning'
  632. );
  633. }
  634. $interval = mb_substr($interval, 1);
  635. }
  636. if ($interval !== '') {
  637. throw new ParseErrorException(
  638. 'end of string',
  639. $interval
  640. );
  641. }
  642. return $instance;
  643. }
  644. /**
  645. * Get a copy of the instance.
  646. *
  647. * @return static
  648. */
  649. public function copy()
  650. {
  651. $date = new static(0);
  652. $date->copyProperties($this);
  653. $date->step = $this->step;
  654. return $date;
  655. }
  656. /**
  657. * Get a copy of the instance.
  658. *
  659. * @return static
  660. */
  661. public function clone()
  662. {
  663. return $this->copy();
  664. }
  665. /**
  666. * Provide static helpers to create instances. Allows CarbonInterval::years(3).
  667. *
  668. * Note: This is done using the magic method to allow static and instance methods to
  669. * have the same names.
  670. *
  671. * @param string $method magic method name called
  672. * @param array $parameters parameters list
  673. *
  674. * @return static|null
  675. */
  676. public static function __callStatic($method, $parameters)
  677. {
  678. try {
  679. $interval = new static(0);
  680. $localStrictModeEnabled = $interval->localStrictModeEnabled;
  681. $interval->localStrictModeEnabled = true;
  682. $result = static::hasMacro($method)
  683. ? static::bindMacroContext(null, function () use (&$method, &$parameters, &$interval) {
  684. return $interval->callMacro($method, $parameters);
  685. })
  686. : $interval->$method(...$parameters);
  687. $interval->localStrictModeEnabled = $localStrictModeEnabled;
  688. return $result;
  689. } catch (BadFluentSetterException $exception) {
  690. if (Carbon::isStrictModeEnabled()) {
  691. throw new BadFluentConstructorException($method, 0, $exception);
  692. }
  693. return null;
  694. }
  695. }
  696. /**
  697. * Evaluate the PHP generated by var_export() and recreate the exported CarbonInterval instance.
  698. *
  699. * @param array $dump data as exported by var_export()
  700. *
  701. * @return static
  702. */
  703. #[ReturnTypeWillChange]
  704. public static function __set_state($dump)
  705. {
  706. /** @noinspection PhpVoidFunctionResultUsedInspection */
  707. /** @var DateInterval $dateInterval */
  708. $dateInterval = parent::__set_state($dump);
  709. return static::instance($dateInterval);
  710. }
  711. /**
  712. * Return the current context from inside a macro callee or a new one if static.
  713. *
  714. * @return static
  715. */
  716. protected static function this()
  717. {
  718. return end(static::$macroContextStack) ?: new static(0);
  719. }
  720. /**
  721. * Creates a CarbonInterval from string.
  722. *
  723. * Format:
  724. *
  725. * Suffix | Unit | Example | DateInterval expression
  726. * -------|---------|---------|------------------------
  727. * y | years | 1y | P1Y
  728. * mo | months | 3mo | P3M
  729. * w | weeks | 2w | P2W
  730. * d | days | 28d | P28D
  731. * h | hours | 4h | PT4H
  732. * m | minutes | 12m | PT12M
  733. * s | seconds | 59s | PT59S
  734. *
  735. * e. g. `1w 3d 4h 32m 23s` is converted to 10 days 4 hours 32 minutes and 23 seconds.
  736. *
  737. * Special cases:
  738. * - An empty string will return a zero interval
  739. * - Fractions are allowed for weeks, days, hours and minutes and will be converted
  740. * and rounded to the next smaller value (caution: 0.5w = 4d)
  741. *
  742. * @param string $intervalDefinition
  743. *
  744. * @return static
  745. */
  746. public static function fromString($intervalDefinition)
  747. {
  748. if (empty($intervalDefinition)) {
  749. return new static(0);
  750. }
  751. $years = 0;
  752. $months = 0;
  753. $weeks = 0;
  754. $days = 0;
  755. $hours = 0;
  756. $minutes = 0;
  757. $seconds = 0;
  758. $milliseconds = 0;
  759. $microseconds = 0;
  760. $pattern = '/(\d+(?:\.\d+)?)\h*([^\d\h]*)/i';
  761. preg_match_all($pattern, $intervalDefinition, $parts, PREG_SET_ORDER);
  762. while ([$part, $value, $unit] = array_shift($parts)) {
  763. $intValue = (int) $value;
  764. $fraction = (float) $value - $intValue;
  765. // Fix calculation precision
  766. switch (round($fraction, 6)) {
  767. case 1:
  768. $fraction = 0;
  769. $intValue++;
  770. break;
  771. case 0:
  772. $fraction = 0;
  773. break;
  774. }
  775. switch ($unit === 'µs' ? 'µs' : strtolower($unit)) {
  776. case 'millennia':
  777. case 'millennium':
  778. $years += $intValue * CarbonInterface::YEARS_PER_MILLENNIUM;
  779. break;
  780. case 'century':
  781. case 'centuries':
  782. $years += $intValue * CarbonInterface::YEARS_PER_CENTURY;
  783. break;
  784. case 'decade':
  785. case 'decades':
  786. $years += $intValue * CarbonInterface::YEARS_PER_DECADE;
  787. break;
  788. case 'year':
  789. case 'years':
  790. case 'y':
  791. case 'yr':
  792. case 'yrs':
  793. $years += $intValue;
  794. break;
  795. case 'quarter':
  796. case 'quarters':
  797. $months += $intValue * CarbonInterface::MONTHS_PER_QUARTER;
  798. break;
  799. case 'month':
  800. case 'months':
  801. case 'mo':
  802. case 'mos':
  803. $months += $intValue;
  804. break;
  805. case 'week':
  806. case 'weeks':
  807. case 'w':
  808. $weeks += $intValue;
  809. if ($fraction) {
  810. $parts[] = [null, $fraction * static::getDaysPerWeek(), 'd'];
  811. }
  812. break;
  813. case 'day':
  814. case 'days':
  815. case 'd':
  816. $days += $intValue;
  817. if ($fraction) {
  818. $parts[] = [null, $fraction * static::getHoursPerDay(), 'h'];
  819. }
  820. break;
  821. case 'hour':
  822. case 'hours':
  823. case 'h':
  824. $hours += $intValue;
  825. if ($fraction) {
  826. $parts[] = [null, $fraction * static::getMinutesPerHour(), 'm'];
  827. }
  828. break;
  829. case 'minute':
  830. case 'minutes':
  831. case 'm':
  832. $minutes += $intValue;
  833. if ($fraction) {
  834. $parts[] = [null, $fraction * static::getSecondsPerMinute(), 's'];
  835. }
  836. break;
  837. case 'second':
  838. case 'seconds':
  839. case 's':
  840. $seconds += $intValue;
  841. if ($fraction) {
  842. $parts[] = [null, $fraction * static::getMillisecondsPerSecond(), 'ms'];
  843. }
  844. break;
  845. case 'millisecond':
  846. case 'milliseconds':
  847. case 'milli':
  848. case 'ms':
  849. $milliseconds += $intValue;
  850. if ($fraction) {
  851. $microseconds += round($fraction * static::getMicrosecondsPerMillisecond());
  852. }
  853. break;
  854. case 'microsecond':
  855. case 'microseconds':
  856. case 'micro':
  857. case 'µs':
  858. $microseconds += $intValue;
  859. break;
  860. default:
  861. throw new InvalidIntervalException(
  862. sprintf('Invalid part %s in definition %s', $part, $intervalDefinition)
  863. );
  864. }
  865. }
  866. return new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $milliseconds * Carbon::MICROSECONDS_PER_MILLISECOND + $microseconds);
  867. }
  868. /**
  869. * Creates a CarbonInterval from string using a different locale.
  870. *
  871. * @param string $interval interval string in the given language (may also contain English).
  872. * @param string|null $locale if locale is null or not specified, current global locale will be used instead.
  873. *
  874. * @return static
  875. */
  876. public static function parseFromLocale($interval, $locale = null)
  877. {
  878. return static::fromString(Carbon::translateTimeString($interval, $locale ?: static::getLocale(), 'en'));
  879. }
  880. private static function castIntervalToClass(DateInterval $interval, string $className, array $skip = [])
  881. {
  882. $mainClass = DateInterval::class;
  883. if (!is_a($className, $mainClass, true)) {
  884. throw new InvalidCastException("$className is not a sub-class of $mainClass.");
  885. }
  886. $microseconds = $interval->f;
  887. $instance = new $className(static::getDateIntervalSpec($interval, false, $skip));
  888. if ($microseconds) {
  889. $instance->f = $microseconds;
  890. }
  891. if ($interval instanceof self && is_a($className, self::class, true)) {
  892. self::copyStep($interval, $instance);
  893. }
  894. self::copyNegativeUnits($interval, $instance);
  895. return $instance;
  896. }
  897. private static function copyNegativeUnits(DateInterval $from, DateInterval $to): void
  898. {
  899. $to->invert = $from->invert;
  900. foreach (['y', 'm', 'd', 'h', 'i', 's'] as $unit) {
  901. if ($from->$unit < 0) {
  902. $to->$unit *= -1;
  903. }
  904. }
  905. }
  906. private static function copyStep(self $from, self $to): void
  907. {
  908. $to->setStep($from->getStep());
  909. }
  910. /**
  911. * Cast the current instance into the given class.
  912. *
  913. * @param string $className The $className::instance() method will be called to cast the current object.
  914. *
  915. * @return DateInterval
  916. */
  917. public function cast(string $className)
  918. {
  919. return self::castIntervalToClass($this, $className);
  920. }
  921. /**
  922. * Create a CarbonInterval instance from a DateInterval one. Can not instance
  923. * DateInterval objects created from DateTime::diff() as you can't externally
  924. * set the $days field.
  925. *
  926. * @param DateInterval $interval
  927. * @param bool $skipCopy set to true to return the passed object
  928. * (without copying it) if it's already of the
  929. * current class
  930. *
  931. * @return static
  932. */
  933. public static function instance(DateInterval $interval, array $skip = [], bool $skipCopy = false)
  934. {
  935. if ($skipCopy && $interval instanceof static) {
  936. return $interval;
  937. }
  938. return self::castIntervalToClass($interval, static::class, $skip);
  939. }
  940. /**
  941. * Make a CarbonInterval instance from given variable if possible.
  942. *
  943. * Always return a new instance. Parse only strings and only these likely to be intervals (skip dates
  944. * and recurrences). Throw an exception for invalid format, but otherwise return null.
  945. *
  946. * @param mixed|int|DateInterval|string|Closure|null $interval interval or number of the given $unit
  947. * @param string|null $unit if specified, $interval must be an integer
  948. * @param bool $skipCopy set to true to return the passed object
  949. * (without copying it) if it's already of the
  950. * current class
  951. *
  952. * @return static|null
  953. */
  954. public static function make($interval, $unit = null, bool $skipCopy = false)
  955. {
  956. if ($unit) {
  957. $interval = "$interval ".Carbon::pluralUnit($unit);
  958. }
  959. if ($interval instanceof DateInterval) {
  960. return static::instance($interval, [], $skipCopy);
  961. }
  962. if ($interval instanceof Closure) {
  963. return new static($interval);
  964. }
  965. if (!\is_string($interval)) {
  966. return null;
  967. }
  968. return static::makeFromString($interval);
  969. }
  970. protected static function makeFromString(string $interval)
  971. {
  972. $interval = preg_replace('/\s+/', ' ', trim($interval));
  973. if (preg_match('/^P[T\d]/', $interval)) {
  974. return new static($interval);
  975. }
  976. if (preg_match('/^(?:\h*\d+(?:\.\d+)?\h*[a-z]+)+$/i', $interval)) {
  977. return static::fromString($interval);
  978. }
  979. // @codeCoverageIgnoreStart
  980. try {
  981. /** @var static $interval */
  982. $interval = static::createFromDateString($interval);
  983. } catch (DateMalformedIntervalStringException $e) {
  984. return null;
  985. }
  986. // @codeCoverageIgnoreEnd
  987. return !$interval || $interval->isEmpty() ? null : $interval;
  988. }
  989. protected function resolveInterval($interval)
  990. {
  991. if (!($interval instanceof self)) {
  992. return self::make($interval);
  993. }
  994. return $interval;
  995. }
  996. /**
  997. * Sets up a DateInterval from the relative parts of the string.
  998. *
  999. * @param string $time
  1000. *
  1001. * @return static
  1002. *
  1003. * @link https://php.net/manual/en/dateinterval.createfromdatestring.php
  1004. */
  1005. #[ReturnTypeWillChange]
  1006. public static function createFromDateString($time)
  1007. {
  1008. $interval = @parent::createFromDateString(strtr($time, [
  1009. ',' => ' ',
  1010. ' and ' => ' ',
  1011. ]));
  1012. if ($interval instanceof DateInterval) {
  1013. $interval = static::instance($interval);
  1014. }
  1015. return $interval;
  1016. }
  1017. ///////////////////////////////////////////////////////////////////
  1018. ///////////////////////// GETTERS AND SETTERS /////////////////////
  1019. ///////////////////////////////////////////////////////////////////
  1020. /**
  1021. * Get a part of the CarbonInterval object.
  1022. *
  1023. * @param string $name
  1024. *
  1025. * @throws UnknownGetterException
  1026. *
  1027. * @return int|float|string
  1028. */
  1029. public function get($name)
  1030. {
  1031. if (str_starts_with($name, 'total')) {
  1032. return $this->total(substr($name, 5));
  1033. }
  1034. switch ($name) {
  1035. case 'years':
  1036. return $this->y;
  1037. case 'months':
  1038. return $this->m;
  1039. case 'dayz':
  1040. return $this->d;
  1041. case 'hours':
  1042. return $this->h;
  1043. case 'minutes':
  1044. return $this->i;
  1045. case 'seconds':
  1046. return $this->s;
  1047. case 'milli':
  1048. case 'milliseconds':
  1049. return (int) (round($this->f * Carbon::MICROSECONDS_PER_SECOND) / Carbon::MICROSECONDS_PER_MILLISECOND);
  1050. case 'micro':
  1051. case 'microseconds':
  1052. return (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND);
  1053. case 'microExcludeMilli':
  1054. return (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND) % Carbon::MICROSECONDS_PER_MILLISECOND;
  1055. case 'weeks':
  1056. return (int) ($this->d / (int) static::getDaysPerWeek());
  1057. case 'daysExcludeWeeks':
  1058. case 'dayzExcludeWeeks':
  1059. return $this->d % (int) static::getDaysPerWeek();
  1060. case 'locale':
  1061. return $this->getTranslatorLocale();
  1062. default:
  1063. throw new UnknownGetterException($name);
  1064. }
  1065. }
  1066. /**
  1067. * Get a part of the CarbonInterval object.
  1068. *
  1069. * @param string $name
  1070. *
  1071. * @throws UnknownGetterException
  1072. *
  1073. * @return int|float|string
  1074. */
  1075. public function __get($name)
  1076. {
  1077. return $this->get($name);
  1078. }
  1079. /**
  1080. * Set a part of the CarbonInterval object.
  1081. *
  1082. * @param string|array $name
  1083. * @param int $value
  1084. *
  1085. * @throws UnknownSetterException
  1086. *
  1087. * @return $this
  1088. */
  1089. public function set($name, $value = null)
  1090. {
  1091. $properties = \is_array($name) ? $name : [$name => $value];
  1092. foreach ($properties as $key => $value) {
  1093. switch (Carbon::singularUnit(rtrim($key, 'z'))) {
  1094. case 'year':
  1095. $this->checkIntegerValue($key, $value);
  1096. $this->y = $value;
  1097. $this->handleDecimalPart('year', $value, $this->y);
  1098. break;
  1099. case 'month':
  1100. $this->checkIntegerValue($key, $value);
  1101. $this->m = $value;
  1102. $this->handleDecimalPart('month', $value, $this->m);
  1103. break;
  1104. case 'week':
  1105. $this->checkIntegerValue($key, $value);
  1106. $days = $value * (int) static::getDaysPerWeek();
  1107. $this->assertSafeForInteger('days total (including weeks)', $days);
  1108. $this->d = $days;
  1109. $this->handleDecimalPart('day', $days, $this->d);
  1110. break;
  1111. case 'day':
  1112. $this->checkIntegerValue($key, $value);
  1113. $this->d = $value;
  1114. $this->handleDecimalPart('day', $value, $this->d);
  1115. break;
  1116. case 'daysexcludeweek':
  1117. case 'dayzexcludeweek':
  1118. $this->checkIntegerValue($key, $value);
  1119. $days = $this->weeks * (int) static::getDaysPerWeek() + $value;
  1120. $this->assertSafeForInteger('days total (including weeks)', $days);
  1121. $this->d = $days;
  1122. $this->handleDecimalPart('day', $days, $this->d);
  1123. break;
  1124. case 'hour':
  1125. $this->checkIntegerValue($key, $value);
  1126. $this->h = $value;
  1127. $this->handleDecimalPart('hour', $value, $this->h);
  1128. break;
  1129. case 'minute':
  1130. $this->checkIntegerValue($key, $value);
  1131. $this->i = $value;
  1132. $this->handleDecimalPart('minute', $value, $this->i);
  1133. break;
  1134. case 'second':
  1135. $this->checkIntegerValue($key, $value);
  1136. $this->s = $value;
  1137. $this->handleDecimalPart('second', $value, $this->s);
  1138. break;
  1139. case 'milli':
  1140. case 'millisecond':
  1141. $this->microseconds = $value * Carbon::MICROSECONDS_PER_MILLISECOND + $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND;
  1142. break;
  1143. case 'micro':
  1144. case 'microsecond':
  1145. $this->f = $value / Carbon::MICROSECONDS_PER_SECOND;
  1146. break;
  1147. default:
  1148. if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) {
  1149. throw new UnknownSetterException($key);
  1150. }
  1151. $this->$key = $value;
  1152. }
  1153. }
  1154. return $this;
  1155. }
  1156. /**
  1157. * Set a part of the CarbonInterval object.
  1158. *
  1159. * @param string $name
  1160. * @param int $value
  1161. *
  1162. * @throws UnknownSetterException
  1163. */
  1164. public function __set($name, $value)
  1165. {
  1166. $this->set($name, $value);
  1167. }
  1168. /**
  1169. * Allow setting of weeks and days to be cumulative.
  1170. *
  1171. * @param int $weeks Number of weeks to set
  1172. * @param int $days Number of days to set
  1173. *
  1174. * @return static
  1175. */
  1176. public function weeksAndDays($weeks, $days)
  1177. {
  1178. $this->dayz = ($weeks * static::getDaysPerWeek()) + $days;
  1179. return $this;
  1180. }
  1181. /**
  1182. * Returns true if the interval is empty for each unit.
  1183. *
  1184. * @return bool
  1185. */
  1186. public function isEmpty()
  1187. {
  1188. return $this->years === 0 &&
  1189. $this->months === 0 &&
  1190. $this->dayz === 0 &&
  1191. !$this->days &&
  1192. $this->hours === 0 &&
  1193. $this->minutes === 0 &&
  1194. $this->seconds === 0 &&
  1195. $this->microseconds === 0;
  1196. }
  1197. /**
  1198. * Register a custom macro.
  1199. *
  1200. * @example
  1201. * ```
  1202. * CarbonInterval::macro('twice', function () {
  1203. * return $this->times(2);
  1204. * });
  1205. * echo CarbonInterval::hours(2)->twice();
  1206. * ```
  1207. *
  1208. * @param string $name
  1209. * @param object|callable $macro
  1210. *
  1211. * @return void
  1212. */
  1213. public static function macro($name, $macro)
  1214. {
  1215. static::$macros[$name] = $macro;
  1216. }
  1217. /**
  1218. * Register macros from a mixin object.
  1219. *
  1220. * @example
  1221. * ```
  1222. * CarbonInterval::mixin(new class {
  1223. * public function daysToHours() {
  1224. * return function () {
  1225. * $this->hours += $this->days;
  1226. * $this->days = 0;
  1227. *
  1228. * return $this;
  1229. * };
  1230. * }
  1231. * public function hoursToDays() {
  1232. * return function () {
  1233. * $this->days += $this->hours;
  1234. * $this->hours = 0;
  1235. *
  1236. * return $this;
  1237. * };
  1238. * }
  1239. * });
  1240. * echo CarbonInterval::hours(5)->hoursToDays() . "\n";
  1241. * echo CarbonInterval::days(5)->daysToHours() . "\n";
  1242. * ```
  1243. *
  1244. * @param object|string $mixin
  1245. *
  1246. * @throws ReflectionException
  1247. *
  1248. * @return void
  1249. */
  1250. public static function mixin($mixin)
  1251. {
  1252. static::baseMixin($mixin);
  1253. }
  1254. /**
  1255. * Check if macro is registered.
  1256. *
  1257. * @param string $name
  1258. *
  1259. * @return bool
  1260. */
  1261. public static function hasMacro($name)
  1262. {
  1263. return isset(static::$macros[$name]);
  1264. }
  1265. /**
  1266. * Call given macro.
  1267. *
  1268. * @param string $name
  1269. * @param array $parameters
  1270. *
  1271. * @return mixed
  1272. */
  1273. protected function callMacro($name, $parameters)
  1274. {
  1275. $macro = static::$macros[$name];
  1276. if ($macro instanceof Closure) {
  1277. $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class);
  1278. return ($boundMacro ?: $macro)(...$parameters);
  1279. }
  1280. return $macro(...$parameters);
  1281. }
  1282. /**
  1283. * Allow fluent calls on the setters... CarbonInterval::years(3)->months(5)->day().
  1284. *
  1285. * Note: This is done using the magic method to allow static and instance methods to
  1286. * have the same names.
  1287. *
  1288. * @param string $method magic method name called
  1289. * @param array $parameters parameters list
  1290. *
  1291. * @throws BadFluentSetterException|Throwable
  1292. *
  1293. * @return static
  1294. */
  1295. public function __call($method, $parameters)
  1296. {
  1297. if (static::hasMacro($method)) {
  1298. return static::bindMacroContext($this, function () use (&$method, &$parameters) {
  1299. return $this->callMacro($method, $parameters);
  1300. });
  1301. }
  1302. $roundedValue = $this->callRoundMethod($method, $parameters);
  1303. if ($roundedValue !== null) {
  1304. return $roundedValue;
  1305. }
  1306. if (preg_match('/^(?<method>add|sub)(?<unit>[A-Z].*)$/', $method, $match)) {
  1307. $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($match['unit']), 0);
  1308. return $this->{$match['method']}($value, $match['unit']);
  1309. }
  1310. $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($method), 1);
  1311. try {
  1312. $this->set($method, $value);
  1313. } catch (UnknownSetterException $exception) {
  1314. if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) {
  1315. throw new BadFluentSetterException($method, 0, $exception);
  1316. }
  1317. }
  1318. return $this;
  1319. }
  1320. protected function getForHumansInitialVariables($syntax, $short)
  1321. {
  1322. if (\is_array($syntax)) {
  1323. return $syntax;
  1324. }
  1325. if (\is_int($short)) {
  1326. return [
  1327. 'parts' => $short,
  1328. 'short' => false,
  1329. ];
  1330. }
  1331. if (\is_bool($syntax)) {
  1332. return [
  1333. 'short' => $syntax,
  1334. 'syntax' => CarbonInterface::DIFF_ABSOLUTE,
  1335. ];
  1336. }
  1337. return [];
  1338. }
  1339. /**
  1340. * @param mixed $syntax
  1341. * @param mixed $short
  1342. * @param mixed $parts
  1343. * @param mixed $options
  1344. *
  1345. * @return array
  1346. */
  1347. protected function getForHumansParameters($syntax = null, $short = false, $parts = -1, $options = null)
  1348. {
  1349. $optionalSpace = ' ';
  1350. $default = $this->getTranslationMessage('list.0') ?? $this->getTranslationMessage('list') ?? ' ';
  1351. $join = $default === '' ? '' : ' ';
  1352. $altNumbers = false;
  1353. $aUnit = false;
  1354. $minimumUnit = 's';
  1355. $skip = [];
  1356. extract($this->getForHumansInitialVariables($syntax, $short));
  1357. $skip = array_map('strtolower', array_filter((array) $skip, static function ($value) {
  1358. return \is_string($value) && $value !== '';
  1359. }));
  1360. if ($syntax === null) {
  1361. $syntax = CarbonInterface::DIFF_ABSOLUTE;
  1362. }
  1363. if ($parts === -1) {
  1364. $parts = INF;
  1365. }
  1366. if ($options === null) {
  1367. $options = static::getHumanDiffOptions();
  1368. }
  1369. if ($join === false) {
  1370. $join = ' ';
  1371. } elseif ($join === true) {
  1372. $join = [
  1373. $default,
  1374. $this->getTranslationMessage('list.1') ?? $default,
  1375. ];
  1376. }
  1377. if ($altNumbers && $altNumbers !== true) {
  1378. $language = new Language($this->locale);
  1379. $altNumbers = \in_array($language->getCode(), (array) $altNumbers, true);
  1380. }
  1381. if (\is_array($join)) {
  1382. [$default, $last] = $join;
  1383. if ($default !== ' ') {
  1384. $optionalSpace = '';
  1385. }
  1386. $join = function ($list) use ($default, $last) {
  1387. if (\count($list) < 2) {
  1388. return implode('', $list);
  1389. }
  1390. $end = array_pop($list);
  1391. return implode($default, $list).$last.$end;
  1392. };
  1393. }
  1394. if (\is_string($join)) {
  1395. if ($join !== ' ') {
  1396. $optionalSpace = '';
  1397. }
  1398. $glue = $join;
  1399. $join = function ($list) use ($glue) {
  1400. return implode($glue, $list);
  1401. };
  1402. }
  1403. $interpolations = [
  1404. ':optional-space' => $optionalSpace,
  1405. ];
  1406. return [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip];
  1407. }
  1408. protected static function getRoundingMethodFromOptions(int $options): ?string
  1409. {
  1410. if ($options & CarbonInterface::ROUND) {
  1411. return 'round';
  1412. }
  1413. if ($options & CarbonInterface::CEIL) {
  1414. return 'ceil';
  1415. }
  1416. if ($options & CarbonInterface::FLOOR) {
  1417. return 'floor';
  1418. }
  1419. return null;
  1420. }
  1421. /**
  1422. * Returns interval values as an array where key are the unit names and values the counts.
  1423. *
  1424. * @return int[]
  1425. */
  1426. public function toArray()
  1427. {
  1428. return [
  1429. 'years' => $this->years,
  1430. 'months' => $this->months,
  1431. 'weeks' => $this->weeks,
  1432. 'days' => $this->daysExcludeWeeks,
  1433. 'hours' => $this->hours,
  1434. 'minutes' => $this->minutes,
  1435. 'seconds' => $this->seconds,
  1436. 'microseconds' => $this->microseconds,
  1437. ];
  1438. }
  1439. /**
  1440. * Returns interval non-zero values as an array where key are the unit names and values the counts.
  1441. *
  1442. * @return int[]
  1443. */
  1444. public function getNonZeroValues()
  1445. {
  1446. return array_filter($this->toArray(), 'intval');
  1447. }
  1448. /**
  1449. * Returns interval values as an array where key are the unit names and values the counts
  1450. * from the biggest non-zero one the the smallest non-zero one.
  1451. *
  1452. * @return int[]
  1453. */
  1454. public function getValuesSequence()
  1455. {
  1456. $nonZeroValues = $this->getNonZeroValues();
  1457. if ($nonZeroValues === []) {
  1458. return [];
  1459. }
  1460. $keys = array_keys($nonZeroValues);
  1461. $firstKey = $keys[0];
  1462. $lastKey = $keys[\count($keys) - 1];
  1463. $values = [];
  1464. $record = false;
  1465. foreach ($this->toArray() as $unit => $count) {
  1466. if ($unit === $firstKey) {
  1467. $record = true;
  1468. }
  1469. if ($record) {
  1470. $values[$unit] = $count;
  1471. }
  1472. if ($unit === $lastKey) {
  1473. $record = false;
  1474. }
  1475. }
  1476. return $values;
  1477. }
  1478. /**
  1479. * Get the current interval in a human readable format in the current locale.
  1480. *
  1481. * @example
  1482. * ```
  1483. * echo CarbonInterval::fromString('4d 3h 40m')->forHumans() . "\n";
  1484. * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 2]) . "\n";
  1485. * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 3, 'join' => true]) . "\n";
  1486. * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['short' => true]) . "\n";
  1487. * echo CarbonInterval::fromString('1d 24h')->forHumans(['join' => ' or ']) . "\n";
  1488. * echo CarbonInterval::fromString('1d 24h')->forHumans(['minimumUnit' => 'hour']) . "\n";
  1489. * ```
  1490. *
  1491. * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains:
  1492. * - 'syntax' entry (see below)
  1493. * - 'short' entry (see below)
  1494. * - 'parts' entry (see below)
  1495. * - 'options' entry (see below)
  1496. * - 'skip' entry, list of units to skip (array of strings or a single string,
  1497. * ` it can be the unit name (singular or plural) or its shortcut
  1498. * ` (y, m, w, d, h, min, s, ms, µs).
  1499. * - 'aUnit' entry, prefer "an hour" over "1 hour" if true
  1500. * - 'join' entry determines how to join multiple parts of the string
  1501. * ` - if $join is a string, it's used as a joiner glue
  1502. * ` - if $join is a callable/closure, it get the list of string and should return a string
  1503. * ` - if $join is an array, the first item will be the default glue, and the second item
  1504. * ` will be used instead of the glue for the last item
  1505. * ` - if $join is true, it will be guessed from the locale ('list' translation file entry)
  1506. * ` - if $join is missing, a space will be used as glue
  1507. * - 'minimumUnit' entry determines the smallest unit of time to display can be long or
  1508. * ` short form of the units, e.g. 'hour' or 'h' (default value: s)
  1509. * if int passed, it add modifiers:
  1510. * Possible values:
  1511. * - CarbonInterface::DIFF_ABSOLUTE no modifiers
  1512. * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier
  1513. * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier
  1514. * Default value: CarbonInterface::DIFF_ABSOLUTE
  1515. * @param bool $short displays short format of time units
  1516. * @param int $parts maximum number of parts to display (default value: -1: no limits)
  1517. * @param int $options human diff options
  1518. *
  1519. * @throws Exception
  1520. *
  1521. * @return string
  1522. */
  1523. public function forHumans($syntax = null, $short = false, $parts = -1, $options = null)
  1524. {
  1525. [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip] = $this
  1526. ->getForHumansParameters($syntax, $short, $parts, $options);
  1527. $interval = [];
  1528. $syntax = (int) ($syntax ?? CarbonInterface::DIFF_ABSOLUTE);
  1529. $absolute = $syntax === CarbonInterface::DIFF_ABSOLUTE;
  1530. $relativeToNow = $syntax === CarbonInterface::DIFF_RELATIVE_TO_NOW;
  1531. $count = 1;
  1532. $unit = $short ? 's' : 'second';
  1533. $isFuture = $this->invert === 1;
  1534. $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before');
  1535. $declensionMode = null;
  1536. /** @var \Symfony\Component\Translation\Translator $translator */
  1537. $translator = $this->getLocalTranslator();
  1538. $handleDeclensions = function ($unit, $count, $index = 0, $parts = 1) use ($interpolations, $transId, $translator, $altNumbers, $absolute, &$declensionMode) {
  1539. if (!$absolute) {
  1540. $declensionMode = $declensionMode ?? $this->translate($transId.'_mode');
  1541. if ($this->needsDeclension($declensionMode, $index, $parts)) {
  1542. // Some languages have special pluralization for past and future tense.
  1543. $key = $unit.'_'.$transId;
  1544. $result = $this->translate($key, $interpolations, $count, $translator, $altNumbers);
  1545. if ($result !== $key) {
  1546. return $result;
  1547. }
  1548. }
  1549. }
  1550. $result = $this->translate($unit, $interpolations, $count, $translator, $altNumbers);
  1551. if ($result !== $unit) {
  1552. return $result;
  1553. }
  1554. return null;
  1555. };
  1556. $intervalValues = $this;
  1557. $method = static::getRoundingMethodFromOptions($options);
  1558. if ($method) {
  1559. $previousCount = INF;
  1560. while (
  1561. \count($intervalValues->getNonZeroValues()) > $parts &&
  1562. ($count = \count($keys = array_keys($intervalValues->getValuesSequence()))) > 1
  1563. ) {
  1564. $index = min($count, $previousCount - 1) - 2;
  1565. if ($index < 0) {
  1566. break;
  1567. }
  1568. $intervalValues = $this->copy()->roundUnit(
  1569. $keys[$index],
  1570. 1,
  1571. $method
  1572. );
  1573. $previousCount = $count;
  1574. }
  1575. }
  1576. $diffIntervalArray = [
  1577. ['value' => $intervalValues->years, 'unit' => 'year', 'unitShort' => 'y'],
  1578. ['value' => $intervalValues->months, 'unit' => 'month', 'unitShort' => 'm'],
  1579. ['value' => $intervalValues->weeks, 'unit' => 'week', 'unitShort' => 'w'],
  1580. ['value' => $intervalValues->daysExcludeWeeks, 'unit' => 'day', 'unitShort' => 'd'],
  1581. ['value' => $intervalValues->hours, 'unit' => 'hour', 'unitShort' => 'h'],
  1582. ['value' => $intervalValues->minutes, 'unit' => 'minute', 'unitShort' => 'min'],
  1583. ['value' => $intervalValues->seconds, 'unit' => 'second', 'unitShort' => 's'],
  1584. ['value' => $intervalValues->milliseconds, 'unit' => 'millisecond', 'unitShort' => 'ms'],
  1585. ['value' => $intervalValues->microExcludeMilli, 'unit' => 'microsecond', 'unitShort' => 'µs'],
  1586. ];
  1587. if (!empty($skip)) {
  1588. foreach ($diffIntervalArray as $index => &$unitData) {
  1589. $nextIndex = $index + 1;
  1590. if ($unitData['value'] &&
  1591. isset($diffIntervalArray[$nextIndex]) &&
  1592. \count(array_intersect([$unitData['unit'], $unitData['unit'].'s', $unitData['unitShort']], $skip))
  1593. ) {
  1594. $diffIntervalArray[$nextIndex]['value'] += $unitData['value'] *
  1595. self::getFactorWithDefault($diffIntervalArray[$nextIndex]['unit'], $unitData['unit']);
  1596. $unitData['value'] = 0;
  1597. }
  1598. }
  1599. }
  1600. $transChoice = function ($short, $unitData, $index, $parts) use ($absolute, $handleDeclensions, $translator, $aUnit, $altNumbers, $interpolations) {
  1601. $count = $unitData['value'];
  1602. if ($short) {
  1603. $result = $handleDeclensions($unitData['unitShort'], $count, $index, $parts);
  1604. if ($result !== null) {
  1605. return $result;
  1606. }
  1607. } elseif ($aUnit) {
  1608. $result = $handleDeclensions('a_'.$unitData['unit'], $count, $index, $parts);
  1609. if ($result !== null) {
  1610. return $result;
  1611. }
  1612. }
  1613. if (!$absolute) {
  1614. return $handleDeclensions($unitData['unit'], $count, $index, $parts);
  1615. }
  1616. return $this->translate($unitData['unit'], $interpolations, $count, $translator, $altNumbers);
  1617. };
  1618. $fallbackUnit = ['second', 's'];
  1619. foreach ($diffIntervalArray as $diffIntervalData) {
  1620. if ($diffIntervalData['value'] > 0) {
  1621. $unit = $short ? $diffIntervalData['unitShort'] : $diffIntervalData['unit'];
  1622. $count = $diffIntervalData['value'];
  1623. $interval[] = [$short, $diffIntervalData];
  1624. } elseif ($options & CarbonInterface::SEQUENTIAL_PARTS_ONLY && \count($interval) > 0) {
  1625. break;
  1626. }
  1627. // break the loop after we get the required number of parts in array
  1628. if (\count($interval) >= $parts) {
  1629. break;
  1630. }
  1631. // break the loop after we have reached the minimum unit
  1632. if (\in_array($minimumUnit, [$diffIntervalData['unit'], $diffIntervalData['unitShort']], true)) {
  1633. $fallbackUnit = [$diffIntervalData['unit'], $diffIntervalData['unitShort']];
  1634. break;
  1635. }
  1636. }
  1637. $actualParts = \count($interval);
  1638. foreach ($interval as $index => &$item) {
  1639. $item = $transChoice($item[0], $item[1], $index, $actualParts);
  1640. }
  1641. if (\count($interval) === 0) {
  1642. if ($relativeToNow && $options & CarbonInterface::JUST_NOW) {
  1643. $key = 'diff_now';
  1644. $translation = $this->translate($key, $interpolations, null, $translator);
  1645. if ($translation !== $key) {
  1646. return $translation;
  1647. }
  1648. }
  1649. $count = $options & CarbonInterface::NO_ZERO_DIFF ? 1 : 0;
  1650. $unit = $fallbackUnit[$short ? 1 : 0];
  1651. $interval[] = $this->translate($unit, $interpolations, $count, $translator, $altNumbers);
  1652. }
  1653. // join the interval parts by a space
  1654. $time = $join($interval);
  1655. unset($diffIntervalArray, $interval);
  1656. if ($absolute) {
  1657. return $time;
  1658. }
  1659. $isFuture = $this->invert === 1;
  1660. $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before');
  1661. if ($parts === 1) {
  1662. if ($relativeToNow && $unit === 'day') {
  1663. if ($count === 1 && $options & CarbonInterface::ONE_DAY_WORDS) {
  1664. $key = $isFuture ? 'diff_tomorrow' : 'diff_yesterday';
  1665. $translation = $this->translate($key, $interpolations, null, $translator);
  1666. if ($translation !== $key) {
  1667. return $translation;
  1668. }
  1669. }
  1670. if ($count === 2 && $options & CarbonInterface::TWO_DAY_WORDS) {
  1671. $key = $isFuture ? 'diff_after_tomorrow' : 'diff_before_yesterday';
  1672. $translation = $this->translate($key, $interpolations, null, $translator);
  1673. if ($translation !== $key) {
  1674. return $translation;
  1675. }
  1676. }
  1677. }
  1678. $aTime = $aUnit ? $handleDeclensions('a_'.$unit, $count) : null;
  1679. $time = $aTime ?: $handleDeclensions($unit, $count) ?: $time;
  1680. }
  1681. $time = [':time' => $time];
  1682. return $this->translate($transId, array_merge($time, $interpolations, $time), null, $translator);
  1683. }
  1684. /**
  1685. * Format the instance as a string using the forHumans() function.
  1686. *
  1687. * @throws Exception
  1688. *
  1689. * @return string
  1690. */
  1691. public function __toString()
  1692. {
  1693. $format = $this->localToStringFormat ?? static::$toStringFormat;
  1694. if (!$format) {
  1695. return $this->forHumans();
  1696. }
  1697. if ($format instanceof Closure) {
  1698. return $format($this);
  1699. }
  1700. return $this->format($format);
  1701. }
  1702. /**
  1703. * Return native DateInterval PHP object matching the current instance.
  1704. *
  1705. * @example
  1706. * ```
  1707. * var_dump(CarbonInterval::hours(2)->toDateInterval());
  1708. * ```
  1709. *
  1710. * @return DateInterval
  1711. */
  1712. public function toDateInterval()
  1713. {
  1714. return self::castIntervalToClass($this, DateInterval::class);
  1715. }
  1716. /**
  1717. * Convert the interval to a CarbonPeriod.
  1718. *
  1719. * @param DateTimeInterface|string|int ...$params Start date, [end date or recurrences] and optional settings.
  1720. *
  1721. * @return CarbonPeriod
  1722. */
  1723. public function toPeriod(...$params)
  1724. {
  1725. if ($this->tzName) {
  1726. $tz = \is_string($this->tzName) ? new DateTimeZone($this->tzName) : $this->tzName;
  1727. if ($tz instanceof DateTimeZone) {
  1728. array_unshift($params, $tz);
  1729. }
  1730. }
  1731. return CarbonPeriod::create($this, ...$params);
  1732. }
  1733. /**
  1734. * Invert the interval.
  1735. *
  1736. * @param bool|int $inverted if a parameter is passed, the passed value cast as 1 or 0 is used
  1737. * as the new value of the ->invert property.
  1738. *
  1739. * @return $this
  1740. */
  1741. public function invert($inverted = null)
  1742. {
  1743. $this->invert = (\func_num_args() === 0 ? !$this->invert : $inverted) ? 1 : 0;
  1744. return $this;
  1745. }
  1746. protected function solveNegativeInterval()
  1747. {
  1748. if (!$this->isEmpty() && $this->years <= 0 && $this->months <= 0 && $this->dayz <= 0 && $this->hours <= 0 && $this->minutes <= 0 && $this->seconds <= 0 && $this->microseconds <= 0) {
  1749. $this->years *= -1;
  1750. $this->months *= -1;
  1751. $this->dayz *= -1;
  1752. $this->hours *= -1;
  1753. $this->minutes *= -1;
  1754. $this->seconds *= -1;
  1755. $this->microseconds *= -1;
  1756. $this->invert();
  1757. }
  1758. return $this;
  1759. }
  1760. /**
  1761. * Add the passed interval to the current instance.
  1762. *
  1763. * @param string|DateInterval $unit
  1764. * @param int|float $value
  1765. *
  1766. * @return $this
  1767. */
  1768. public function add($unit, $value = 1)
  1769. {
  1770. if (is_numeric($unit)) {
  1771. [$value, $unit] = [$unit, $value];
  1772. }
  1773. if (\is_string($unit) && !preg_match('/^\s*\d/', $unit)) {
  1774. $unit = "$value $unit";
  1775. $value = 1;
  1776. }
  1777. $interval = static::make($unit);
  1778. if (!$interval) {
  1779. throw new InvalidIntervalException('This type of data cannot be added/subtracted.');
  1780. }
  1781. if ($value !== 1) {
  1782. $interval->times($value);
  1783. }
  1784. $sign = ($this->invert === 1) !== ($interval->invert === 1) ? -1 : 1;
  1785. $this->years += $interval->y * $sign;
  1786. $this->months += $interval->m * $sign;
  1787. $this->dayz += ($interval->days === false ? $interval->d : $interval->days) * $sign;
  1788. $this->hours += $interval->h * $sign;
  1789. $this->minutes += $interval->i * $sign;
  1790. $this->seconds += $interval->s * $sign;
  1791. $this->microseconds += $interval->microseconds * $sign;
  1792. $this->solveNegativeInterval();
  1793. return $this;
  1794. }
  1795. /**
  1796. * Subtract the passed interval to the current instance.
  1797. *
  1798. * @param string|DateInterval $unit
  1799. * @param int|float $value
  1800. *
  1801. * @return $this
  1802. */
  1803. public function sub($unit, $value = 1)
  1804. {
  1805. if (is_numeric($unit)) {
  1806. [$value, $unit] = [$unit, $value];
  1807. }
  1808. return $this->add($unit, -(float) $value);
  1809. }
  1810. /**
  1811. * Subtract the passed interval to the current instance.
  1812. *
  1813. * @param string|DateInterval $unit
  1814. * @param int|float $value
  1815. *
  1816. * @return $this
  1817. */
  1818. public function subtract($unit, $value = 1)
  1819. {
  1820. return $this->sub($unit, $value);
  1821. }
  1822. /**
  1823. * Add given parameters to the current interval.
  1824. *
  1825. * @param int $years
  1826. * @param int $months
  1827. * @param int|float $weeks
  1828. * @param int|float $days
  1829. * @param int|float $hours
  1830. * @param int|float $minutes
  1831. * @param int|float $seconds
  1832. * @param int|float $microseconds
  1833. *
  1834. * @return $this
  1835. */
  1836. public function plus(
  1837. $years = 0,
  1838. $months = 0,
  1839. $weeks = 0,
  1840. $days = 0,
  1841. $hours = 0,
  1842. $minutes = 0,
  1843. $seconds = 0,
  1844. $microseconds = 0
  1845. ): self {
  1846. return $this->add("
  1847. $years years $months months $weeks weeks $days days
  1848. $hours hours $minutes minutes $seconds seconds $microseconds microseconds
  1849. ");
  1850. }
  1851. /**
  1852. * Add given parameters to the current interval.
  1853. *
  1854. * @param int $years
  1855. * @param int $months
  1856. * @param int|float $weeks
  1857. * @param int|float $days
  1858. * @param int|float $hours
  1859. * @param int|float $minutes
  1860. * @param int|float $seconds
  1861. * @param int|float $microseconds
  1862. *
  1863. * @return $this
  1864. */
  1865. public function minus(
  1866. $years = 0,
  1867. $months = 0,
  1868. $weeks = 0,
  1869. $days = 0,
  1870. $hours = 0,
  1871. $minutes = 0,
  1872. $seconds = 0,
  1873. $microseconds = 0
  1874. ): self {
  1875. return $this->sub("
  1876. $years years $months months $weeks weeks $days days
  1877. $hours hours $minutes minutes $seconds seconds $microseconds microseconds
  1878. ");
  1879. }
  1880. /**
  1881. * Multiply current instance given number of times. times() is naive, it multiplies each unit
  1882. * (so day can be greater than 31, hour can be greater than 23, etc.) and the result is rounded
  1883. * separately for each unit.
  1884. *
  1885. * Use times() when you want a fast and approximated calculation that does not cascade units.
  1886. *
  1887. * For a precise and cascaded calculation,
  1888. *
  1889. * @see multiply()
  1890. *
  1891. * @param float|int $factor
  1892. *
  1893. * @return $this
  1894. */
  1895. public function times($factor)
  1896. {
  1897. if ($factor < 0) {
  1898. $this->invert = $this->invert ? 0 : 1;
  1899. $factor = -$factor;
  1900. }
  1901. $this->years = (int) round($this->years * $factor);
  1902. $this->months = (int) round($this->months * $factor);
  1903. $this->dayz = (int) round($this->dayz * $factor);
  1904. $this->hours = (int) round($this->hours * $factor);
  1905. $this->minutes = (int) round($this->minutes * $factor);
  1906. $this->seconds = (int) round($this->seconds * $factor);
  1907. $this->microseconds = (int) round($this->microseconds * $factor);
  1908. return $this;
  1909. }
  1910. /**
  1911. * Divide current instance by a given divider. shares() is naive, it divides each unit separately
  1912. * and the result is rounded for each unit. So 5 hours and 20 minutes shared by 3 becomes 2 hours
  1913. * and 7 minutes.
  1914. *
  1915. * Use shares() when you want a fast and approximated calculation that does not cascade units.
  1916. *
  1917. * For a precise and cascaded calculation,
  1918. *
  1919. * @see divide()
  1920. *
  1921. * @param float|int $divider
  1922. *
  1923. * @return $this
  1924. */
  1925. public function shares($divider)
  1926. {
  1927. return $this->times(1 / $divider);
  1928. }
  1929. protected function copyProperties(self $interval, $ignoreSign = false)
  1930. {
  1931. $this->years = $interval->years;
  1932. $this->months = $interval->months;
  1933. $this->dayz = $interval->dayz;
  1934. $this->hours = $interval->hours;
  1935. $this->minutes = $interval->minutes;
  1936. $this->seconds = $interval->seconds;
  1937. $this->microseconds = $interval->microseconds;
  1938. if (!$ignoreSign) {
  1939. $this->invert = $interval->invert;
  1940. }
  1941. return $this;
  1942. }
  1943. /**
  1944. * Multiply and cascade current instance by a given factor.
  1945. *
  1946. * @param float|int $factor
  1947. *
  1948. * @return $this
  1949. */
  1950. public function multiply($factor)
  1951. {
  1952. if ($factor < 0) {
  1953. $this->invert = $this->invert ? 0 : 1;
  1954. $factor = -$factor;
  1955. }
  1956. $yearPart = (int) floor($this->years * $factor); // Split calculation to prevent imprecision
  1957. if ($yearPart) {
  1958. $this->years -= $yearPart / $factor;
  1959. }
  1960. return $this->copyProperties(
  1961. static::create($yearPart)
  1962. ->microseconds(abs($this->totalMicroseconds) * $factor)
  1963. ->cascade(),
  1964. true
  1965. );
  1966. }
  1967. /**
  1968. * Divide and cascade current instance by a given divider.
  1969. *
  1970. * @param float|int $divider
  1971. *
  1972. * @return $this
  1973. */
  1974. public function divide($divider)
  1975. {
  1976. return $this->multiply(1 / $divider);
  1977. }
  1978. /**
  1979. * Get the interval_spec string of a date interval.
  1980. *
  1981. * @param DateInterval $interval
  1982. *
  1983. * @return string
  1984. */
  1985. public static function getDateIntervalSpec(DateInterval $interval, bool $microseconds = false, array $skip = [])
  1986. {
  1987. $date = array_filter([
  1988. static::PERIOD_YEARS => abs($interval->y),
  1989. static::PERIOD_MONTHS => abs($interval->m),
  1990. static::PERIOD_DAYS => abs($interval->d),
  1991. ]);
  1992. if (
  1993. $interval->days >= CarbonInterface::DAYS_PER_WEEK * CarbonInterface::WEEKS_PER_MONTH &&
  1994. (!isset($date[static::PERIOD_YEARS]) || \count(array_intersect(['y', 'year', 'years'], $skip))) &&
  1995. (!isset($date[static::PERIOD_MONTHS]) || \count(array_intersect(['m', 'month', 'months'], $skip)))
  1996. ) {
  1997. $date = [
  1998. static::PERIOD_DAYS => abs($interval->days),
  1999. ];
  2000. }
  2001. $seconds = abs($interval->s);
  2002. if ($microseconds && $interval->f > 0) {
  2003. $seconds = sprintf('%d.%06d', $seconds, abs($interval->f) * 1000000);
  2004. }
  2005. $time = array_filter([
  2006. static::PERIOD_HOURS => abs($interval->h),
  2007. static::PERIOD_MINUTES => abs($interval->i),
  2008. static::PERIOD_SECONDS => $seconds,
  2009. ]);
  2010. $specString = static::PERIOD_PREFIX;
  2011. foreach ($date as $key => $value) {
  2012. $specString .= $value.$key;
  2013. }
  2014. if (\count($time) > 0) {
  2015. $specString .= static::PERIOD_TIME_PREFIX;
  2016. foreach ($time as $key => $value) {
  2017. $specString .= $value.$key;
  2018. }
  2019. }
  2020. return $specString === static::PERIOD_PREFIX ? 'PT0S' : $specString;
  2021. }
  2022. /**
  2023. * Get the interval_spec string.
  2024. *
  2025. * @return string
  2026. */
  2027. public function spec(bool $microseconds = false)
  2028. {
  2029. return static::getDateIntervalSpec($this, $microseconds);
  2030. }
  2031. /**
  2032. * Comparing 2 date intervals.
  2033. *
  2034. * @param DateInterval $first
  2035. * @param DateInterval $second
  2036. *
  2037. * @return int
  2038. */
  2039. public static function compareDateIntervals(DateInterval $first, DateInterval $second)
  2040. {
  2041. $current = Carbon::now();
  2042. $passed = $current->avoidMutation()->add($second);
  2043. $current->add($first);
  2044. if ($current < $passed) {
  2045. return -1;
  2046. }
  2047. if ($current > $passed) {
  2048. return 1;
  2049. }
  2050. return 0;
  2051. }
  2052. /**
  2053. * Comparing with passed interval.
  2054. *
  2055. * @param DateInterval $interval
  2056. *
  2057. * @return int
  2058. */
  2059. public function compare(DateInterval $interval)
  2060. {
  2061. return static::compareDateIntervals($this, $interval);
  2062. }
  2063. private function invertCascade(array $values)
  2064. {
  2065. return $this->set(array_map(function ($value) {
  2066. return -$value;
  2067. }, $values))->doCascade(true)->invert();
  2068. }
  2069. private function doCascade(bool $deep)
  2070. {
  2071. $originalData = $this->toArray();
  2072. $originalData['milliseconds'] = (int) ($originalData['microseconds'] / static::getMicrosecondsPerMillisecond());
  2073. $originalData['microseconds'] = $originalData['microseconds'] % static::getMicrosecondsPerMillisecond();
  2074. $originalData['weeks'] = (int) ($this->d / static::getDaysPerWeek());
  2075. $originalData['daysExcludeWeeks'] = fmod($this->d, static::getDaysPerWeek());
  2076. unset($originalData['days']);
  2077. $newData = $originalData;
  2078. $previous = [];
  2079. foreach (self::getFlipCascadeFactors() as $source => [$target, $factor]) {
  2080. foreach (['source', 'target'] as $key) {
  2081. if ($$key === 'dayz') {
  2082. $$key = 'daysExcludeWeeks';
  2083. }
  2084. }
  2085. $value = $newData[$source];
  2086. $modulo = fmod($factor + fmod($value, $factor), $factor);
  2087. $newData[$source] = $modulo;
  2088. $newData[$target] += ($value - $modulo) / $factor;
  2089. $decimalPart = fmod($newData[$source], 1);
  2090. if ($decimalPart !== 0.0) {
  2091. $unit = $source;
  2092. foreach ($previous as [$subUnit, $subFactor]) {
  2093. $newData[$unit] -= $decimalPart;
  2094. $newData[$subUnit] += $decimalPart * $subFactor;
  2095. $decimalPart = fmod($newData[$subUnit], 1);
  2096. if ($decimalPart === 0.0) {
  2097. break;
  2098. }
  2099. $unit = $subUnit;
  2100. }
  2101. }
  2102. array_unshift($previous, [$source, $factor]);
  2103. }
  2104. $positive = null;
  2105. if (!$deep) {
  2106. foreach ($newData as $value) {
  2107. if ($value) {
  2108. if ($positive === null) {
  2109. $positive = ($value > 0);
  2110. continue;
  2111. }
  2112. if (($value > 0) !== $positive) {
  2113. return $this->invertCascade($originalData)
  2114. ->solveNegativeInterval();
  2115. }
  2116. }
  2117. }
  2118. }
  2119. return $this->set($newData)
  2120. ->solveNegativeInterval();
  2121. }
  2122. /**
  2123. * Convert overflowed values into bigger units.
  2124. *
  2125. * @return $this
  2126. */
  2127. public function cascade()
  2128. {
  2129. return $this->doCascade(false);
  2130. }
  2131. public function hasNegativeValues(): bool
  2132. {
  2133. foreach ($this->toArray() as $value) {
  2134. if ($value < 0) {
  2135. return true;
  2136. }
  2137. }
  2138. return false;
  2139. }
  2140. public function hasPositiveValues(): bool
  2141. {
  2142. foreach ($this->toArray() as $value) {
  2143. if ($value > 0) {
  2144. return true;
  2145. }
  2146. }
  2147. return false;
  2148. }
  2149. /**
  2150. * Get amount of given unit equivalent to the interval.
  2151. *
  2152. * @param string $unit
  2153. *
  2154. * @throws UnknownUnitException|UnitNotConfiguredException
  2155. *
  2156. * @return float
  2157. */
  2158. public function total($unit)
  2159. {
  2160. $realUnit = $unit = strtolower($unit);
  2161. if (\in_array($unit, ['days', 'weeks'])) {
  2162. $realUnit = 'dayz';
  2163. } elseif (!\in_array($unit, ['microseconds', 'milliseconds', 'seconds', 'minutes', 'hours', 'dayz', 'months', 'years'])) {
  2164. throw new UnknownUnitException($unit);
  2165. }
  2166. $result = 0;
  2167. $cumulativeFactor = 0;
  2168. $unitFound = false;
  2169. $factors = self::getFlipCascadeFactors();
  2170. $daysPerWeek = (int) static::getDaysPerWeek();
  2171. $values = [
  2172. 'years' => $this->years,
  2173. 'months' => $this->months,
  2174. 'weeks' => (int) ($this->d / $daysPerWeek),
  2175. 'dayz' => fmod($this->d, $daysPerWeek),
  2176. 'hours' => $this->hours,
  2177. 'minutes' => $this->minutes,
  2178. 'seconds' => $this->seconds,
  2179. 'milliseconds' => (int) ($this->microseconds / Carbon::MICROSECONDS_PER_MILLISECOND),
  2180. 'microseconds' => $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND,
  2181. ];
  2182. if (isset($factors['dayz']) && $factors['dayz'][0] !== 'weeks') {
  2183. $values['dayz'] += $values['weeks'] * $daysPerWeek;
  2184. $values['weeks'] = 0;
  2185. }
  2186. foreach ($factors as $source => [$target, $factor]) {
  2187. if ($source === $realUnit) {
  2188. $unitFound = true;
  2189. $value = $values[$source];
  2190. $result += $value;
  2191. $cumulativeFactor = 1;
  2192. }
  2193. if ($factor === false) {
  2194. if ($unitFound) {
  2195. break;
  2196. }
  2197. $result = 0;
  2198. $cumulativeFactor = 0;
  2199. continue;
  2200. }
  2201. if ($target === $realUnit) {
  2202. $unitFound = true;
  2203. }
  2204. if ($cumulativeFactor) {
  2205. $cumulativeFactor *= $factor;
  2206. $result += $values[$target] * $cumulativeFactor;
  2207. continue;
  2208. }
  2209. $value = $values[$source];
  2210. $result = ($result + $value) / $factor;
  2211. }
  2212. if (isset($target) && !$cumulativeFactor) {
  2213. $result += $values[$target];
  2214. }
  2215. if (!$unitFound) {
  2216. throw new UnitNotConfiguredException($unit);
  2217. }
  2218. if ($this->invert) {
  2219. $result *= -1;
  2220. }
  2221. if ($unit === 'weeks') {
  2222. $result /= $daysPerWeek;
  2223. }
  2224. // Cast as int numbers with no decimal part
  2225. return fmod($result, 1) === 0.0 ? (int) $result : $result;
  2226. }
  2227. /**
  2228. * Determines if the instance is equal to another
  2229. *
  2230. * @param CarbonInterval|DateInterval|mixed $interval
  2231. *
  2232. * @see equalTo()
  2233. *
  2234. * @return bool
  2235. */
  2236. public function eq($interval): bool
  2237. {
  2238. return $this->equalTo($interval);
  2239. }
  2240. /**
  2241. * Determines if the instance is equal to another
  2242. *
  2243. * @param CarbonInterval|DateInterval|mixed $interval
  2244. *
  2245. * @return bool
  2246. */
  2247. public function equalTo($interval): bool
  2248. {
  2249. $interval = $this->resolveInterval($interval);
  2250. return $interval !== null && $this->totalMicroseconds === $interval->totalMicroseconds;
  2251. }
  2252. /**
  2253. * Determines if the instance is not equal to another
  2254. *
  2255. * @param CarbonInterval|DateInterval|mixed $interval
  2256. *
  2257. * @see notEqualTo()
  2258. *
  2259. * @return bool
  2260. */
  2261. public function ne($interval): bool
  2262. {
  2263. return $this->notEqualTo($interval);
  2264. }
  2265. /**
  2266. * Determines if the instance is not equal to another
  2267. *
  2268. * @param CarbonInterval|DateInterval|mixed $interval
  2269. *
  2270. * @return bool
  2271. */
  2272. public function notEqualTo($interval): bool
  2273. {
  2274. return !$this->eq($interval);
  2275. }
  2276. /**
  2277. * Determines if the instance is greater (longer) than another
  2278. *
  2279. * @param CarbonInterval|DateInterval|mixed $interval
  2280. *
  2281. * @see greaterThan()
  2282. *
  2283. * @return bool
  2284. */
  2285. public function gt($interval): bool
  2286. {
  2287. return $this->greaterThan($interval);
  2288. }
  2289. /**
  2290. * Determines if the instance is greater (longer) than another
  2291. *
  2292. * @param CarbonInterval|DateInterval|mixed $interval
  2293. *
  2294. * @return bool
  2295. */
  2296. public function greaterThan($interval): bool
  2297. {
  2298. $interval = $this->resolveInterval($interval);
  2299. return $interval === null || $this->totalMicroseconds > $interval->totalMicroseconds;
  2300. }
  2301. /**
  2302. * Determines if the instance is greater (longer) than or equal to another
  2303. *
  2304. * @param CarbonInterval|DateInterval|mixed $interval
  2305. *
  2306. * @see greaterThanOrEqualTo()
  2307. *
  2308. * @return bool
  2309. */
  2310. public function gte($interval): bool
  2311. {
  2312. return $this->greaterThanOrEqualTo($interval);
  2313. }
  2314. /**
  2315. * Determines if the instance is greater (longer) than or equal to another
  2316. *
  2317. * @param CarbonInterval|DateInterval|mixed $interval
  2318. *
  2319. * @return bool
  2320. */
  2321. public function greaterThanOrEqualTo($interval): bool
  2322. {
  2323. return $this->greaterThan($interval) || $this->equalTo($interval);
  2324. }
  2325. /**
  2326. * Determines if the instance is less (shorter) than another
  2327. *
  2328. * @param CarbonInterval|DateInterval|mixed $interval
  2329. *
  2330. * @see lessThan()
  2331. *
  2332. * @return bool
  2333. */
  2334. public function lt($interval): bool
  2335. {
  2336. return $this->lessThan($interval);
  2337. }
  2338. /**
  2339. * Determines if the instance is less (shorter) than another
  2340. *
  2341. * @param CarbonInterval|DateInterval|mixed $interval
  2342. *
  2343. * @return bool
  2344. */
  2345. public function lessThan($interval): bool
  2346. {
  2347. $interval = $this->resolveInterval($interval);
  2348. return $interval !== null && $this->totalMicroseconds < $interval->totalMicroseconds;
  2349. }
  2350. /**
  2351. * Determines if the instance is less (shorter) than or equal to another
  2352. *
  2353. * @param CarbonInterval|DateInterval|mixed $interval
  2354. *
  2355. * @see lessThanOrEqualTo()
  2356. *
  2357. * @return bool
  2358. */
  2359. public function lte($interval): bool
  2360. {
  2361. return $this->lessThanOrEqualTo($interval);
  2362. }
  2363. /**
  2364. * Determines if the instance is less (shorter) than or equal to another
  2365. *
  2366. * @param CarbonInterval|DateInterval|mixed $interval
  2367. *
  2368. * @return bool
  2369. */
  2370. public function lessThanOrEqualTo($interval): bool
  2371. {
  2372. return $this->lessThan($interval) || $this->equalTo($interval);
  2373. }
  2374. /**
  2375. * Determines if the instance is between two others.
  2376. *
  2377. * The third argument allow you to specify if bounds are included or not (true by default)
  2378. * but for when you including/excluding bounds may produce different results in your application,
  2379. * we recommend to use the explicit methods ->betweenIncluded() or ->betweenExcluded() instead.
  2380. *
  2381. * @example
  2382. * ```
  2383. * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(3)); // true
  2384. * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::hours(36)); // false
  2385. * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2)); // true
  2386. * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2), false); // false
  2387. * ```
  2388. *
  2389. * @param CarbonInterval|DateInterval|mixed $interval1
  2390. * @param CarbonInterval|DateInterval|mixed $interval2
  2391. * @param bool $equal Indicates if an equal to comparison should be done
  2392. *
  2393. * @return bool
  2394. */
  2395. public function between($interval1, $interval2, $equal = true): bool
  2396. {
  2397. return $equal
  2398. ? $this->greaterThanOrEqualTo($interval1) && $this->lessThanOrEqualTo($interval2)
  2399. : $this->greaterThan($interval1) && $this->lessThan($interval2);
  2400. }
  2401. /**
  2402. * Determines if the instance is between two others, bounds excluded.
  2403. *
  2404. * @example
  2405. * ```
  2406. * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true
  2407. * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false
  2408. * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // true
  2409. * ```
  2410. *
  2411. * @param CarbonInterval|DateInterval|mixed $interval1
  2412. * @param CarbonInterval|DateInterval|mixed $interval2
  2413. *
  2414. * @return bool
  2415. */
  2416. public function betweenIncluded($interval1, $interval2): bool
  2417. {
  2418. return $this->between($interval1, $interval2, true);
  2419. }
  2420. /**
  2421. * Determines if the instance is between two others, bounds excluded.
  2422. *
  2423. * @example
  2424. * ```
  2425. * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true
  2426. * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false
  2427. * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // false
  2428. * ```
  2429. *
  2430. * @param CarbonInterval|DateInterval|mixed $interval1
  2431. * @param CarbonInterval|DateInterval|mixed $interval2
  2432. *
  2433. * @return bool
  2434. */
  2435. public function betweenExcluded($interval1, $interval2): bool
  2436. {
  2437. return $this->between($interval1, $interval2, false);
  2438. }
  2439. /**
  2440. * Determines if the instance is between two others
  2441. *
  2442. * @example
  2443. * ```
  2444. * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(3)); // true
  2445. * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::hours(36)); // false
  2446. * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2)); // true
  2447. * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2), false); // false
  2448. * ```
  2449. *
  2450. * @param CarbonInterval|DateInterval|mixed $interval1
  2451. * @param CarbonInterval|DateInterval|mixed $interval2
  2452. * @param bool $equal Indicates if an equal to comparison should be done
  2453. *
  2454. * @return bool
  2455. */
  2456. public function isBetween($interval1, $interval2, $equal = true): bool
  2457. {
  2458. return $this->between($interval1, $interval2, $equal);
  2459. }
  2460. /**
  2461. * Round the current instance at the given unit with given precision if specified and the given function.
  2462. *
  2463. * @param string $unit
  2464. * @param float|int|string|DateInterval|null $precision
  2465. * @param string $function
  2466. *
  2467. * @throws Exception
  2468. *
  2469. * @return $this
  2470. */
  2471. public function roundUnit($unit, $precision = 1, $function = 'round')
  2472. {
  2473. if (static::getCascadeFactors() !== static::getDefaultCascadeFactors()) {
  2474. $value = $function($this->total($unit) / $precision) * $precision;
  2475. $inverted = $value < 0;
  2476. return $this->copyProperties(self::fromString(
  2477. number_format(abs($value), 12, '.', '').' '.$unit
  2478. )->invert($inverted)->cascade());
  2479. }
  2480. $base = CarbonImmutable::parse('2000-01-01 00:00:00', 'UTC')
  2481. ->roundUnit($unit, $precision, $function);
  2482. $next = $base->add($this);
  2483. $inverted = $next < $base;
  2484. if ($inverted) {
  2485. $next = $base->sub($this);
  2486. }
  2487. $this->copyProperties(
  2488. $next
  2489. ->roundUnit($unit, $precision, $function)
  2490. ->diffAsCarbonInterval($base)
  2491. );
  2492. return $this->invert($inverted);
  2493. }
  2494. /**
  2495. * Truncate the current instance at the given unit with given precision if specified.
  2496. *
  2497. * @param string $unit
  2498. * @param float|int|string|DateInterval|null $precision
  2499. *
  2500. * @throws Exception
  2501. *
  2502. * @return $this
  2503. */
  2504. public function floorUnit($unit, $precision = 1)
  2505. {
  2506. return $this->roundUnit($unit, $precision, 'floor');
  2507. }
  2508. /**
  2509. * Ceil the current instance at the given unit with given precision if specified.
  2510. *
  2511. * @param string $unit
  2512. * @param float|int|string|DateInterval|null $precision
  2513. *
  2514. * @throws Exception
  2515. *
  2516. * @return $this
  2517. */
  2518. public function ceilUnit($unit, $precision = 1)
  2519. {
  2520. return $this->roundUnit($unit, $precision, 'ceil');
  2521. }
  2522. /**
  2523. * Round the current instance second with given precision if specified.
  2524. *
  2525. * @param float|int|string|DateInterval|null $precision
  2526. * @param string $function
  2527. *
  2528. * @throws Exception
  2529. *
  2530. * @return $this
  2531. */
  2532. public function round($precision = 1, $function = 'round')
  2533. {
  2534. return $this->roundWith($precision, $function);
  2535. }
  2536. /**
  2537. * Round the current instance second with given precision if specified.
  2538. *
  2539. * @param float|int|string|DateInterval|null $precision
  2540. *
  2541. * @throws Exception
  2542. *
  2543. * @return $this
  2544. */
  2545. public function floor($precision = 1)
  2546. {
  2547. return $this->round($precision, 'floor');
  2548. }
  2549. /**
  2550. * Ceil the current instance second with given precision if specified.
  2551. *
  2552. * @param float|int|string|DateInterval|null $precision
  2553. *
  2554. * @throws Exception
  2555. *
  2556. * @return $this
  2557. */
  2558. public function ceil($precision = 1)
  2559. {
  2560. return $this->round($precision, 'ceil');
  2561. }
  2562. private function needsDeclension(string $mode, int $index, int $parts): bool
  2563. {
  2564. switch ($mode) {
  2565. case 'last':
  2566. return $index === $parts - 1;
  2567. default:
  2568. return true;
  2569. }
  2570. }
  2571. private function checkIntegerValue(string $name, $value)
  2572. {
  2573. if (\is_int($value)) {
  2574. return;
  2575. }
  2576. $this->assertSafeForInteger($name, $value);
  2577. if (\is_float($value) && (((float) (int) $value) === $value)) {
  2578. return;
  2579. }
  2580. if (!self::$floatSettersEnabled) {
  2581. $type = \gettype($value);
  2582. @trigger_error(
  2583. "Since 2.70.0, it's deprecated to pass $type value for $name.\n".
  2584. "It's truncated when stored as an integer interval unit.\n".
  2585. "From 3.0.0, decimal part will no longer be truncated and will be cascaded to smaller units.\n".
  2586. "- To maintain the current behavior, use explicit cast: $name((int) \$value)\n".
  2587. "- To adopt the new behavior globally, call CarbonInterval::enableFloatSetters()\n",
  2588. \E_USER_DEPRECATED
  2589. );
  2590. }
  2591. }
  2592. /**
  2593. * Throw an exception if precision loss when storing the given value as an integer would be >= 1.0.
  2594. */
  2595. private function assertSafeForInteger(string $name, $value)
  2596. {
  2597. if ($value && !\is_int($value) && ($value >= 0x7fffffffffffffff || $value <= -0x7fffffffffffffff)) {
  2598. throw new OutOfRangeException($name, -0x7fffffffffffffff, 0x7fffffffffffffff, $value);
  2599. }
  2600. }
  2601. private function handleDecimalPart(string $unit, $value, $integerValue)
  2602. {
  2603. if (self::$floatSettersEnabled) {
  2604. $floatValue = (float) $value;
  2605. $base = (float) $integerValue;
  2606. if ($floatValue === $base) {
  2607. return;
  2608. }
  2609. $units = [
  2610. 'y' => 'year',
  2611. 'm' => 'month',
  2612. 'd' => 'day',
  2613. 'h' => 'hour',
  2614. 'i' => 'minute',
  2615. 's' => 'second',
  2616. ];
  2617. $upper = true;
  2618. foreach ($units as $property => $name) {
  2619. if ($name === $unit) {
  2620. $upper = false;
  2621. continue;
  2622. }
  2623. if (!$upper && $this->$property !== 0) {
  2624. throw new RuntimeException(
  2625. "You cannot set $unit to a float value as $name would be overridden, ".
  2626. 'set it first to 0 explicitly if you really want to erase its value'
  2627. );
  2628. }
  2629. }
  2630. $this->add($unit, $floatValue - $base);
  2631. }
  2632. }
  2633. }