repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/en_AI.php
src/Carbon/Lang/en_AI.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ return require __DIR__.'/en.php';
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/ru_KG.php
src/Carbon/Lang/ru_KG.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ return require __DIR__.'/ru.php';
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/ewo.php
src/Carbon/Lang/ewo.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ return array_replace_recursive(require __DIR__.'/en.php', [ 'meridiem' => ['kíkíríg', 'ngəgógəle'], 'weekdays' => ['sɔ́ndɔ', 'mɔ́ndi', 'sɔ́ndɔ məlú mə́bɛ̌', 'sɔ́ndɔ məlú mə́lɛ́', 'sɔ́ndɔ məlú mə́nyi', 'fúladé', 'séradé'], 'weekdays_short' => ['sɔ́n', 'mɔ́n', 'smb', 'sml', 'smn', 'fúl', 'sér'], 'weekdays_min' => ['sɔ́n', 'mɔ́n', 'smb', 'sml', 'smn', 'fúl', 'sér'], 'months' => ['ngɔn osú', 'ngɔn bɛ̌', 'ngɔn lála', 'ngɔn nyina', 'ngɔn tána', 'ngɔn saməna', 'ngɔn zamgbála', 'ngɔn mwom', 'ngɔn ebulú', 'ngɔn awóm', 'ngɔn awóm ai dziá', 'ngɔn awóm ai bɛ̌'], 'months_short' => ['ngo', 'ngb', 'ngl', 'ngn', 'ngt', 'ngs', 'ngz', 'ngm', 'nge', 'nga', 'ngad', 'ngab'], 'first_day_of_week' => 1, 'formats' => [ 'LT' => 'HH:mm', 'LTS' => 'HH:mm:ss', 'L' => 'D/M/YYYY', 'LL' => 'D MMM YYYY', 'LLL' => 'D MMMM YYYY HH:mm', 'LLLL' => 'dddd D MMMM YYYY HH:mm', ], // Too unreliable /* 'year' => ':count mbu', // less reliable 'y' => ':count mbu', // less reliable 'a_year' => ':count mbu', // less reliable 'month' => ':count ngòn', // less reliable 'm' => ':count ngòn', // less reliable 'a_month' => ':count ngòn', // less reliable 'week' => ':count mësë', // less reliable 'w' => ':count mësë', // less reliable 'a_week' => ':count mësë', // less reliable 'day' => ':count mësë', // less reliable 'd' => ':count mësë', // less reliable 'a_day' => ':count mësë', // less reliable 'hour' => ':count awola', // less reliable 'h' => ':count awola', // less reliable 'a_hour' => ':count awola', // less reliable 'minute' => ':count awola', // less reliable 'min' => ':count awola', // less reliable 'a_minute' => ':count awola', // less reliable */ ]);
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/dje.php
src/Carbon/Lang/dje.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ return array_replace_recursive(require __DIR__.'/en.php', [ 'meridiem' => ['Subbaahi', 'Zaarikay b'], 'weekdays' => ['Alhadi', 'Atinni', 'Atalaata', 'Alarba', 'Alhamisi', 'Alzuma', 'Asibti'], 'weekdays_short' => ['Alh', 'Ati', 'Ata', 'Ala', 'Alm', 'Alz', 'Asi'], 'weekdays_min' => ['Alh', 'Ati', 'Ata', 'Ala', 'Alm', 'Alz', 'Asi'], 'months' => ['Žanwiye', 'Feewiriye', 'Marsi', 'Awiril', 'Me', 'Žuweŋ', 'Žuyye', 'Ut', 'Sektanbur', 'Oktoobur', 'Noowanbur', 'Deesanbur'], 'months_short' => ['Žan', 'Fee', 'Mar', 'Awi', 'Me', 'Žuw', 'Žuy', 'Ut', 'Sek', 'Okt', 'Noo', 'Dee'], 'first_day_of_week' => 1, 'formats' => [ 'LT' => 'HH:mm', 'LTS' => 'HH:mm:ss', 'L' => 'D/M/YYYY', 'LL' => 'D MMM, YYYY', 'LLL' => 'D MMMM YYYY HH:mm', 'LLLL' => 'dddd D MMMM YYYY HH:mm', ], 'year' => ':count hari', // less reliable 'y' => ':count hari', // less reliable 'a_year' => ':count hari', // less reliable 'week' => ':count alzuma', // less reliable 'w' => ':count alzuma', // less reliable 'a_week' => ':count alzuma', // less reliable 'second' => ':count atinni', // less reliable 's' => ':count atinni', // less reliable 'a_second' => ':count atinni', // less reliable ]);
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/unm_US.php
src/Carbon/Lang/unm_US.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* * Authors: * - bug-glibc-locales@gnu.org */ return array_replace_recursive(require __DIR__.'/en.php', [ 'formats' => [ 'L' => 'DD/MM/YY', ], 'months' => ['enikwsi', 'chkwali', 'xamokhwite', 'kwetayoxe', 'tainipen', 'kichinipen', 'lainipen', 'winaminke', 'kichitahkok', 'puksit', 'wini', 'muxkotae'], 'months_short' => ['eni', 'chk', 'xam', 'kwe', 'tai', 'nip', 'lai', 'win', 'tah', 'puk', 'kun', 'mux'], 'weekdays' => ['kentuwei', 'manteke', 'tusteke', 'lelai', 'tasteke', 'pelaiteke', 'sateteke'], 'weekdays_short' => ['ken', 'man', 'tus', 'lel', 'tas', 'pel', 'sat'], 'weekdays_min' => ['ken', 'man', 'tus', 'lel', 'tas', 'pel', 'sat'], 'first_day_of_week' => 0, 'day_of_first_week_of_year' => 1, // Too unreliable /* 'year' => ':count kaxtëne', 'y' => ':count kaxtëne', 'a_year' => ':count kaxtëne', 'month' => ':count piskewëni kishux', // less reliable 'm' => ':count piskewëni kishux', // less reliable 'a_month' => ':count piskewëni kishux', // less reliable 'week' => ':count kishku', // less reliable 'w' => ':count kishku', // less reliable 'a_week' => ':count kishku', // less reliable 'day' => ':count kishku', 'd' => ':count kishku', 'a_day' => ':count kishku', 'hour' => ':count xkuk', // less reliable 'h' => ':count xkuk', // less reliable 'a_hour' => ':count xkuk', // less reliable 'minute' => ':count txituwàk', // less reliable 'min' => ':count txituwàk', // less reliable 'a_minute' => ':count txituwàk', // less reliable 'second' => ':count nisha', // less reliable 's' => ':count nisha', // less reliable 'a_second' => ':count nisha', // less reliable */ ]);
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/it_CH.php
src/Carbon/Lang/it_CH.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* * Authors: * - Propaganistas */ return array_replace_recursive(require __DIR__.'/it.php', [ 'formats' => [ 'L' => 'DD.MM.YYYY', ], ]);
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/ar_SY.php
src/Carbon/Lang/ar_SY.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* * Authors: * - IBM Globalization Center of Competency, Yamato Software Laboratory bug-glibc-locales@gnu.org * - Abdullah-Alhariri */ return array_replace_recursive(require __DIR__.'/ar.php', [ 'formats' => [ 'L' => 'DD MMM, YYYY', ], 'months' => ['كانون الثاني', 'شباط', 'آذار', 'نيسان', 'أيار', 'حزيران', 'تموز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني', 'كانون الأول'], 'months_short' => ['كانون الثاني', 'شباط', 'آذار', 'نيسان', 'أيار', 'حزيران', 'تموز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني', 'كانون الأول'], 'weekdays' => ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'], 'weekdays_short' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], 'weekdays_min' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], 'first_day_of_week' => 6, 'day_of_first_week_of_year' => 1, 'alt_numbers' => ['۰۰', '۰۱', '۰۲', '۰۳', '۰٤', '۰٥', '۰٦', '۰۷', '۰۸', '۰۹', '۱۰', '۱۱', '۱۲', '۱۳', '۱٤', '۱٥', '۱٦', '۱۷', '۱۸', '۱۹', '۲۰', '۲۱', '۲۲', '۲۳', '۲٤', '۲٥', '۲٦', '۲۷', '۲۸', '۲۹', '۳۰', '۳۱', '۳۲', '۳۳', '۳٤', '۳٥', '۳٦', '۳۷', '۳۸', '۳۹', '٤۰', '٤۱', '٤۲', '٤۳', '٤٤', '٤٥', '٤٦', '٤۷', '٤۸', '٤۹', '٥۰', '٥۱', '٥۲', '٥۳', '٥٤', '٥٥', '٥٦', '٥۷', '٥۸', '٥۹', '٦۰', '٦۱', '٦۲', '٦۳', '٦٤', '٦٥', '٦٦', '٦۷', '٦۸', '٦۹', '۷۰', '۷۱', '۷۲', '۷۳', '۷٤', '۷٥', '۷٦', '۷۷', '۷۸', '۷۹', '۸۰', '۸۱', '۸۲', '۸۳', '۸٤', '۸٥', '۸٦', '۸۷', '۸۸', '۸۹', '۹۰', '۹۱', '۹۲', '۹۳', '۹٤', '۹٥', '۹٦', '۹۷', '۹۸', '۹۹'], ]);
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/fr_PM.php
src/Carbon/Lang/fr_PM.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ return require __DIR__.'/fr.php';
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/ha_GH.php
src/Carbon/Lang/ha_GH.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ return require __DIR__.'/ha.php';
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/de.php
src/Carbon/Lang/de.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* * Authors: * - Michael Hohl * - sheriffmarley * - dennisoderwald * - Timo * - Karag2006 * - Pete Scopes (pdscopes) */ return [ 'year' => ':count Jahr|:count Jahre', 'a_year' => 'ein Jahr|:count Jahre', 'y' => ':count J.', 'month' => ':count Monat|:count Monate', 'a_month' => 'ein Monat|:count Monate', 'm' => ':count Mon.', 'week' => ':count Woche|:count Wochen', 'a_week' => 'eine Woche|:count Wochen', 'w' => ':count Wo.', 'day' => ':count Tag|:count Tage', 'a_day' => 'ein Tag|:count Tage', 'd' => ':count Tg.', 'hour' => ':count Stunde|:count Stunden', 'a_hour' => 'eine Stunde|:count Stunden', 'h' => ':count Std.', 'minute' => ':count Minute|:count Minuten', 'a_minute' => 'eine Minute|:count Minuten', 'min' => ':count Min.', 'second' => ':count Sekunde|:count Sekunden', 'a_second' => 'ein paar Sekunden|:count Sekunden', 's' => ':count Sek.', 'millisecond' => ':count Millisekunde|:count Millisekunden', 'a_millisecond' => 'eine Millisekunde|:count Millisekunden', 'ms' => ':countms', 'microsecond' => ':count Mikrosekunde|:count Mikrosekunden', 'a_microsecond' => 'eine Mikrosekunde|:count Mikrosekunden', 'µs' => ':countµs', 'ago' => 'vor :time', 'from_now' => 'in :time', 'after' => ':time später', 'before' => ':time zuvor', 'year_from_now' => ':count Jahr|:count Jahren', 'month_from_now' => ':count Monat|:count Monaten', 'week_from_now' => ':count Woche|:count Wochen', 'day_from_now' => ':count Tag|:count Tagen', 'year_ago' => ':count Jahr|:count Jahren', 'month_ago' => ':count Monat|:count Monaten', 'week_ago' => ':count Woche|:count Wochen', 'day_ago' => ':count Tag|:count Tagen', 'a_year_from_now' => 'ein Jahr|:count Jahren', 'a_month_from_now' => 'ein Monat|:count Monaten', 'a_week_from_now' => 'eine Woche|:count Wochen', 'a_day_from_now' => 'ein Tag|:count Tagen', 'a_year_ago' => 'ein Jahr|:count Jahren', 'a_month_ago' => 'ein Monat|:count Monaten', 'a_week_ago' => 'eine Woche|:count Wochen', 'a_day_ago' => 'ein Tag|:count Tagen', 'diff_now' => 'Gerade eben', 'diff_today' => 'heute', 'diff_today_regexp' => 'heute(?:\\s+um)?', 'diff_yesterday' => 'Gestern', 'diff_yesterday_regexp' => 'gestern(?:\\s+um)?', 'diff_tomorrow' => 'Morgen', 'diff_tomorrow_regexp' => 'morgen(?:\\s+um)?', 'diff_before_yesterday' => 'Vorgestern', 'diff_after_tomorrow' => 'Übermorgen', 'period_recurrences' => 'einmal|:count mal', 'period_interval' => static function (string $interval = '') { /** @var string $output */ $output = preg_replace('/^(ein|eine|1)\s+/u', '', $interval); if (preg_match('/^(ein|1)( Monat| Mon.| Tag| Tg.)/u', $interval)) { return "jeden $output"; } if (preg_match('/^(ein|1)( Jahr| J.)/u', $interval)) { return "jedes $output"; } return "jede $output"; }, 'period_start_date' => 'von :date', 'period_end_date' => 'bis :date', 'formats' => [ 'LT' => 'HH:mm', 'LTS' => 'HH:mm:ss', 'L' => 'DD.MM.YYYY', 'LL' => 'D. MMMM YYYY', 'LLL' => 'D. MMMM YYYY HH:mm', 'LLLL' => 'dddd, D. MMMM YYYY HH:mm', ], 'calendar' => [ 'sameDay' => '[heute um] LT [Uhr]', 'nextDay' => '[morgen um] LT [Uhr]', 'nextWeek' => 'dddd [um] LT [Uhr]', 'lastDay' => '[gestern um] LT [Uhr]', 'lastWeek' => '[letzten] dddd [um] LT [Uhr]', 'sameElse' => 'L', ], 'months' => ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'], 'months_short' => ['Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'], 'weekdays' => ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'], 'weekdays_short' => ['So.', 'Mo.', 'Di.', 'Mi.', 'Do.', 'Fr.', 'Sa.'], 'weekdays_min' => ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'], 'ordinal' => ':number.', 'first_day_of_week' => 1, 'day_of_first_week_of_year' => 4, 'list' => [', ', ' und '], 'ordinal_words' => [ 'of' => 'im', 'first' => 'erster', 'second' => 'zweiter', 'third' => 'dritter', 'fourth' => 'vierten', 'fifth' => 'fünfter', 'last' => 'letzten', ], ];
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/zh_HK.php
src/Carbon/Lang/zh_HK.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ return require __DIR__.'/zh_Hant_HK.php';
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/mas_TZ.php
src/Carbon/Lang/mas_TZ.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ return array_replace_recursive(require __DIR__.'/mas.php', [ 'first_day_of_week' => 1, ]);
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/en_ISO.php
src/Carbon/Lang/en_ISO.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ return array_replace_recursive(require __DIR__.'/en.php', [ 'formats' => [ 'LT' => 'HH:mm', 'LTS' => 'HH:mm:ss', 'L' => 'YYYY-MM-dd', 'LL' => 'YYYY MMM D', 'LLL' => 'YYYY MMMM D HH:mm', 'LLLL' => 'dddd, YYYY MMMM DD HH:mm', ], 'first_day_of_week' => 0, ]);
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/vai_Vaii.php
src/Carbon/Lang/vai_Vaii.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ return require __DIR__.'/vai.php';
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/ar_SA.php
src/Carbon/Lang/ar_SA.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * Authors: * - Josh Soref * - JD Isaacks * - Atef Ben Ali (atefBB) * - Mohamed Sabil (mohamedsabil83) * - Abdullah-Alhariri */ $months = [ 'يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر', ]; return [ 'year' => implode('|', ['{0}:count سنة', '{1}سنة', '{2}سنتين', ']2,11[:count سنوات', ']10,Inf[:count سنة']), 'a_year' => implode('|', ['{0}:count سنة', '{1}سنة', '{2}سنتين', ']2,11[:count سنوات', ']10,Inf[:count سنة']), 'month' => implode('|', ['{0}:count شهر', '{1}شهر', '{2}شهرين', ']2,11[:count أشهر', ']10,Inf[:count شهر']), 'a_month' => implode('|', ['{0}:count شهر', '{1}شهر', '{2}شهرين', ']2,11[:count أشهر', ']10,Inf[:count شهر']), 'week' => implode('|', ['{0}:count أسبوع', '{1}أسبوع', '{2}أسبوعين', ']2,11[:count أسابيع', ']10,Inf[:count أسبوع']), 'a_week' => implode('|', ['{0}:count أسبوع', '{1}أسبوع', '{2}أسبوعين', ']2,11[:count أسابيع', ']10,Inf[:count أسبوع']), 'day' => implode('|', ['{0}:count يوم', '{1}يوم', '{2}يومين', ']2,11[:count أيام', ']10,Inf[:count يوم']), 'a_day' => implode('|', ['{0}:count يوم', '{1}يوم', '{2}يومين', ']2,11[:count أيام', ']10,Inf[:count يوم']), 'hour' => implode('|', ['{0}:count ساعة', '{1}ساعة', '{2}ساعتين', ']2,11[:count ساعات', ']10,Inf[:count ساعة']), 'a_hour' => implode('|', ['{0}:count ساعة', '{1}ساعة', '{2}ساعتين', ']2,11[:count ساعات', ']10,Inf[:count ساعة']), 'minute' => implode('|', ['{0}:count دقيقة', '{1}دقيقة', '{2}دقيقتين', ']2,11[:count دقائق', ']10,Inf[:count دقيقة']), 'a_minute' => implode('|', ['{0}:count دقيقة', '{1}دقيقة', '{2}دقيقتين', ']2,11[:count دقائق', ']10,Inf[:count دقيقة']), 'second' => implode('|', ['{0}:count ثانية', '{1}ثانية', '{2}ثانيتين', ']2,11[:count ثواني', ']10,Inf[:count ثانية']), 'a_second' => implode('|', ['{0}:count ثانية', '{1}ثانية', '{2}ثانيتين', ']2,11[:count ثواني', ']10,Inf[:count ثانية']), 'ago' => 'منذ :time', 'from_now' => 'في :time', 'after' => 'بعد :time', 'before' => 'قبل :time', 'diff_now' => 'الآن', 'diff_today' => 'اليوم', 'diff_today_regexp' => 'اليوم(?:\\s+على)?(?:\\s+الساعة)?', 'diff_yesterday' => 'أمس', 'diff_yesterday_regexp' => 'أمس(?:\\s+على)?(?:\\s+الساعة)?', 'diff_tomorrow' => 'غداً', 'diff_tomorrow_regexp' => 'غدا(?:\\s+على)?(?:\\s+الساعة)?', 'diff_before_yesterday' => 'قبل الأمس', 'diff_after_tomorrow' => 'بعد غد', 'period_recurrences' => implode('|', ['{0}مرة', '{1}مرة', '{2}:count مرتين', ']2,11[:count مرات', ']10,Inf[:count مرة']), 'period_interval' => 'كل :interval', 'period_start_date' => 'من :date', 'period_end_date' => 'إلى :date', 'months' => $months, 'months_short' => $months, 'weekdays' => ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'], 'weekdays_short' => ['أحد', 'اثنين', 'ثلاثاء', 'أربعاء', 'خميس', 'جمعة', 'سبت'], 'weekdays_min' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], 'list' => ['، ', ' و '], 'first_day_of_week' => 6, 'day_of_first_week_of_year' => 1, 'formats' => [ 'LT' => 'HH:mm', 'LTS' => 'HH:mm:ss', 'L' => 'DD/MM/YYYY', 'LL' => 'D MMMM YYYY', 'LLL' => 'D MMMM YYYY HH:mm', 'LLLL' => 'dddd D MMMM YYYY HH:mm', ], 'calendar' => [ 'sameDay' => '[اليوم على الساعة] LT', 'nextDay' => '[غدا على الساعة] LT', 'nextWeek' => 'dddd [على الساعة] LT', 'lastDay' => '[أمس على الساعة] LT', 'lastWeek' => 'dddd [على الساعة] LT', 'sameElse' => 'L', ], 'meridiem' => ['ص', 'م'], 'weekend' => [5, 6], 'alt_numbers' => ['۰۰', '۰۱', '۰۲', '۰۳', '۰٤', '۰٥', '۰٦', '۰۷', '۰۸', '۰۹', '۱۰', '۱۱', '۱۲', '۱۳', '۱٤', '۱٥', '۱٦', '۱۷', '۱۸', '۱۹', '۲۰', '۲۱', '۲۲', '۲۳', '۲٤', '۲٥', '۲٦', '۲۷', '۲۸', '۲۹', '۳۰', '۳۱', '۳۲', '۳۳', '۳٤', '۳٥', '۳٦', '۳۷', '۳۸', '۳۹', '٤۰', '٤۱', '٤۲', '٤۳', '٤٤', '٤٥', '٤٦', '٤۷', '٤۸', '٤۹', '٥۰', '٥۱', '٥۲', '٥۳', '٥٤', '٥٥', '٥٦', '٥۷', '٥۸', '٥۹', '٦۰', '٦۱', '٦۲', '٦۳', '٦٤', '٦٥', '٦٦', '٦۷', '٦۸', '٦۹', '۷۰', '۷۱', '۷۲', '۷۳', '۷٤', '۷٥', '۷٦', '۷۷', '۷۸', '۷۹', '۸۰', '۸۱', '۸۲', '۸۳', '۸٤', '۸٥', '۸٦', '۸۷', '۸۸', '۸۹', '۹۰', '۹۱', '۹۲', '۹۳', '۹٤', '۹٥', '۹٦', '۹۷', '۹۸', '۹۹'], ];
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/fil_PH.php
src/Carbon/Lang/fil_PH.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* * Authors: * - Rene Torres Rene Torres, Pablo Saratxaga rgtorre@rocketmail.com, pablo@mandrakesoft.com * - Jaycee Mariano (alohajaycee) */ return array_replace_recursive(require __DIR__.'/en.php', [ 'formats' => [ 'L' => 'MM/DD/YY', ], 'months' => ['Enero', 'Pebrero', 'Marso', 'Abril', 'Mayo', 'Hunyo', 'Hulyo', 'Agosto', 'Setyembre', 'Oktubre', 'Nobyembre', 'Disyembre'], 'months_short' => ['Ene', 'Peb', 'Mar', 'Abr', 'May', 'Hun', 'Hul', 'Ago', 'Set', 'Okt', 'Nob', 'Dis'], 'weekdays' => ['Linggo', 'Lunes', 'Martes', 'Miyerkoles', 'Huwebes', 'Biyernes', 'Sabado'], 'weekdays_short' => ['Lin', 'Lun', 'Mar', 'Miy', 'Huw', 'Biy', 'Sab'], 'weekdays_min' => ['Lin', 'Lun', 'Mar', 'Miy', 'Huw', 'Biy', 'Sab'], 'first_day_of_week' => 0, 'day_of_first_week_of_year' => 1, 'meridiem' => ['N.U.', 'N.H.'], 'before' => ':time bago', 'after' => ':time pagkatapos', 'year' => ':count taon', 'y' => ':count taon', 'a_year' => ':count taon', 'month' => ':count buwan', 'm' => ':count buwan', 'a_month' => ':count buwan', 'week' => ':count linggo', 'w' => ':count linggo', 'a_week' => ':count linggo', 'day' => ':count araw', 'd' => ':count araw', 'a_day' => ':count araw', 'hour' => ':count oras', 'h' => ':count oras', 'a_hour' => ':count oras', 'minute' => ':count minuto', 'min' => ':count minuto', 'a_minute' => ':count minuto', 'second' => ':count segundo', 's' => ':count segundo', 'a_second' => ':count segundo', 'ago' => ':time ang nakalipas', 'from_now' => 'sa :time', ]);
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/pt_LU.php
src/Carbon/Lang/pt_LU.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ return require __DIR__.'/pt.php';
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/bi.php
src/Carbon/Lang/bi.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* * Unknown default region, use the first alphabetically. */ return require __DIR__.'/bi_VU.php';
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/an_ES.php
src/Carbon/Lang/an_ES.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* * Authors: * - Softaragones Jordi Mallach Pérez, Juan Pablo Martínez bug-glibc-locales@gnu.org, softaragones@softaragones.org */ return array_replace_recursive(require __DIR__.'/en.php', [ 'formats' => [ 'L' => 'DD/MM/YYYY', ], 'months' => ['chinero', 'febrero', 'marzo', 'abril', 'mayo', 'chunyo', 'chuliol', 'agosto', 'setiembre', 'octubre', 'noviembre', 'aviento'], 'months_short' => ['chi', 'feb', 'mar', 'abr', 'may', 'chn', 'chl', 'ago', 'set', 'oct', 'nov', 'avi'], 'weekdays' => ['domingo', 'luns', 'martes', 'mierques', 'chueves', 'viernes', 'sabado'], 'weekdays_short' => ['dom', 'lun', 'mar', 'mie', 'chu', 'vie', 'sab'], 'weekdays_min' => ['dom', 'lun', 'mar', 'mie', 'chu', 'vie', 'sab'], 'first_day_of_week' => 1, 'day_of_first_week_of_year' => 4, 'year' => ':count año', 'y' => ':count año', 'a_year' => ':count año', 'month' => ':count mes', 'm' => ':count mes', 'a_month' => ':count mes', 'week' => ':count semana', 'w' => ':count semana', 'a_week' => ':count semana', 'day' => ':count día', 'd' => ':count día', 'a_day' => ':count día', 'hour' => ':count reloch', // less reliable 'h' => ':count reloch', // less reliable 'a_hour' => ':count reloch', // less reliable 'minute' => ':count minuto', 'min' => ':count minuto', 'a_minute' => ':count minuto', 'second' => ':count segundo', 's' => ':count segundo', 'a_second' => ':count segundo', ]);
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/kl.php
src/Carbon/Lang/kl.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* * Unknown default region, use the first alphabetically. */ return require __DIR__.'/kl_GL.php';
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/kk.php
src/Carbon/Lang/kk.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* * Authors: * - Josh Soref * - François B * - Talat Uspanov * - Нурлан Рахимжанов * - Toleugazy Kali */ return [ 'year' => ':count жыл', 'a_year' => '{1}бір жыл|:count жыл', 'y' => ':count ж.', 'month' => ':count ай', 'a_month' => '{1}бір ай|:count ай', 'm' => ':count ай', 'week' => ':count апта', 'a_week' => '{1}бір апта', 'w' => ':count ап.', 'day' => ':count күн', 'a_day' => '{1}бір күн|:count күн', 'd' => ':count к.', 'hour' => ':count сағат', 'a_hour' => '{1}бір сағат|:count сағат', 'h' => ':count са.', 'minute' => ':count минут', 'a_minute' => '{1}бір минут|:count минут', 'min' => ':count м.', 'second' => ':count секунд', 'a_second' => '{1}бірнеше секунд|:count секунд', 's' => ':count се.', 'ago' => ':time бұрын', 'from_now' => ':time ішінде', 'after' => ':time кейін', 'before' => ':time бұрын', 'diff_now' => 'қазір', 'diff_today' => 'Бүгін', 'diff_today_regexp' => 'Бүгін(?:\\s+сағат)?', 'diff_yesterday' => 'кеше', 'diff_yesterday_regexp' => 'Кеше(?:\\s+сағат)?', 'diff_tomorrow' => 'ертең', 'diff_tomorrow_regexp' => 'Ертең(?:\\s+сағат)?', 'formats' => [ 'LT' => 'HH:mm', 'LTS' => 'HH:mm:ss', 'L' => 'DD.MM.YYYY', 'LL' => 'D MMMM YYYY', 'LLL' => 'D MMMM YYYY HH:mm', 'LLLL' => 'dddd, D MMMM YYYY HH:mm', ], 'calendar' => [ 'sameDay' => '[Бүгін сағат] LT', 'nextDay' => '[Ертең сағат] LT', 'nextWeek' => 'dddd [сағат] LT', 'lastDay' => '[Кеше сағат] LT', 'lastWeek' => '[Өткен аптаның] dddd [сағат] LT', 'sameElse' => 'L', ], 'ordinal' => static function ($number) { static $suffixes = [ 0 => '-ші', 1 => '-ші', 2 => '-ші', 3 => '-ші', 4 => '-ші', 5 => '-ші', 6 => '-шы', 7 => '-ші', 8 => '-ші', 9 => '-шы', 10 => '-шы', 20 => '-шы', 30 => '-шы', 40 => '-шы', 50 => '-ші', 60 => '-шы', 70 => '-ші', 80 => '-ші', 90 => '-шы', 100 => '-ші', ]; return $number.($suffixes[$number] ?? $suffixes[$number % 10] ?? $suffixes[$number >= 100 ? 100 : -1] ?? ''); }, 'months' => ['қаңтар', 'ақпан', 'наурыз', 'сәуір', 'мамыр', 'маусым', 'шілде', 'тамыз', 'қыркүйек', 'қазан', 'қараша', 'желтоқсан'], 'months_short' => ['қаң', 'ақп', 'нау', 'сәу', 'мам', 'мау', 'шіл', 'там', 'қыр', 'қаз', 'қар', 'жел'], 'weekdays' => ['жексенбі', 'дүйсенбі', 'сейсенбі', 'сәрсенбі', 'бейсенбі', 'жұма', 'сенбі'], 'weekdays_short' => ['жек', 'дүй', 'сей', 'сәр', 'бей', 'жұм', 'сен'], 'weekdays_min' => ['жк', 'дй', 'сй', 'ср', 'бй', 'жм', 'сн'], 'first_day_of_week' => 1, 'day_of_first_week_of_year' => 1, 'list' => [', ', ' және '], ];
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/sa_IN.php
src/Carbon/Lang/sa_IN.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* * Authors: * - The Debian project Christian Perrier bubulle@debian.org */ return array_replace_recursive(require __DIR__.'/en.php', [ 'formats' => [ 'L' => 'D-MM-YY', ], 'months' => ['जनवरी', 'फ़रवरी', 'मार्च', 'अप्रेल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितम्बर', 'अक्टूबर', 'नवम्बर', 'दिसम्बर'], 'months_short' => ['जनवरी', 'फ़रवरी', 'मार्च', 'अप्रेल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितम्बर', 'अक्टूबर', 'नवम्बर', 'दिसम्बर'], 'weekdays' => ['रविवासर:', 'सोमवासर:', 'मंगलवासर:', 'बुधवासर:', 'बृहस्पतिवासरः', 'शुक्रवासर', 'शनिवासर:'], 'weekdays_short' => ['रविः', 'सोम:', 'मंगल:', 'बुध:', 'बृहस्पतिः', 'शुक्र', 'शनि:'], 'weekdays_min' => ['रविः', 'सोम:', 'मंगल:', 'बुध:', 'बृहस्पतिः', 'शुक्र', 'शनि:'], 'first_day_of_week' => 0, 'day_of_first_week_of_year' => 1, 'meridiem' => ['पूर्वाह्न', 'अपराह्न'], 'minute' => ':count होरा', // less reliable 'min' => ':count होरा', // less reliable 'a_minute' => ':count होरा', // less reliable 'year' => ':count वर्ष', 'y' => ':count वर्ष', 'a_year' => ':count वर्ष', 'month' => ':count मास', 'm' => ':count मास', 'a_month' => ':count मास', 'week' => ':count सप्ताहः saptahaĥ', 'w' => ':count सप्ताहः saptahaĥ', 'a_week' => ':count सप्ताहः saptahaĥ', 'day' => ':count दिन', 'd' => ':count दिन', 'a_day' => ':count दिन', 'hour' => ':count घण्टा', 'h' => ':count घण्टा', 'a_hour' => ':count घण्टा', 'second' => ':count द्वितीयः', 's' => ':count द्वितीयः', 'a_second' => ':count द्वितीयः', ]);
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/en_KE.php
src/Carbon/Lang/en_KE.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ return array_replace_recursive(require __DIR__.'/en.php', [ 'first_day_of_week' => 0, ]);
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/ru_MD.php
src/Carbon/Lang/ru_MD.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ return require __DIR__.'/ru.php';
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/ar_QA.php
src/Carbon/Lang/ar_QA.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* * Authors: * - IBM Globalization Center of Competency, Yamato Software Laboratory bug-glibc-locales@gnu.org * - Abdullah-Alhariri */ return array_replace_recursive(require __DIR__.'/ar.php', [ 'formats' => [ 'L' => 'DD MMM, YYYY', ], 'months' => ['يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر'], 'months_short' => ['ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس'], 'weekdays' => ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'], 'weekdays_short' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], 'weekdays_min' => ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], 'first_day_of_week' => 6, 'day_of_first_week_of_year' => 1, 'alt_numbers' => ['۰۰', '۰۱', '۰۲', '۰۳', '۰٤', '۰٥', '۰٦', '۰۷', '۰۸', '۰۹', '۱۰', '۱۱', '۱۲', '۱۳', '۱٤', '۱٥', '۱٦', '۱۷', '۱۸', '۱۹', '۲۰', '۲۱', '۲۲', '۲۳', '۲٤', '۲٥', '۲٦', '۲۷', '۲۸', '۲۹', '۳۰', '۳۱', '۳۲', '۳۳', '۳٤', '۳٥', '۳٦', '۳۷', '۳۸', '۳۹', '٤۰', '٤۱', '٤۲', '٤۳', '٤٤', '٤٥', '٤٦', '٤۷', '٤۸', '٤۹', '٥۰', '٥۱', '٥۲', '٥۳', '٥٤', '٥٥', '٥٦', '٥۷', '٥۸', '٥۹', '٦۰', '٦۱', '٦۲', '٦۳', '٦٤', '٦٥', '٦٦', '٦۷', '٦۸', '٦۹', '۷۰', '۷۱', '۷۲', '۷۳', '۷٤', '۷٥', '۷٦', '۷۷', '۷۸', '۷۹', '۸۰', '۸۱', '۸۲', '۸۳', '۸٤', '۸٥', '۸٦', '۸۷', '۸۸', '۸۹', '۹۰', '۹۱', '۹۲', '۹۳', '۹٤', '۹٥', '۹٦', '۹۷', '۹۸', '۹۹'], ]);
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/sr_Cyrl_BA.php
src/Carbon/Lang/sr_Cyrl_BA.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Symfony\Component\Translation\PluralizationRules; // @codeCoverageIgnoreStart if (class_exists(PluralizationRules::class)) { PluralizationRules::set(static function ($number) { return PluralizationRules::get($number, 'sr'); }, 'sr_Cyrl_BA'); } // @codeCoverageIgnoreEnd return array_replace_recursive(require __DIR__.'/sr_Cyrl.php', [ 'formats' => [ 'LT' => 'HH:mm', 'LTS' => 'HH:mm:ss', 'L' => 'D.M.yy.', 'LL' => 'DD.MM.YYYY.', 'LLL' => 'DD. MMMM YYYY. HH:mm', 'LLLL' => 'dddd, DD. MMMM YYYY. HH:mm', ], 'weekdays' => ['недјеља', 'понедељак', 'уторак', 'сриједа', 'четвртак', 'петак', 'субота'], 'weekdays_short' => ['нед.', 'пон.', 'ут.', 'ср.', 'чет.', 'пет.', 'суб.'], ]);
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/en_VI.php
src/Carbon/Lang/en_VI.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ return array_replace_recursive(require __DIR__.'/en.php', [ 'first_day_of_week' => 0, ]);
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/om_ET.php
src/Carbon/Lang/om_ET.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ return require __DIR__.'/om.php';
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/mhr_RU.php
src/Carbon/Lang/mhr_RU.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* * Authors: * - PeshSajSoft Ltd. Vyacheslav Kileev slavakileev@yandex.ru */ return array_replace_recursive(require __DIR__.'/en.php', [ 'formats' => [ 'L' => 'YYYY.MM.DD', ], 'months' => ['Шорыкйол', 'Пургыж', 'Ӱярня', 'Вӱдшор', 'Ага', 'Пеледыш', 'Сӱрем', 'Сорла', 'Идым', 'Шыжа', 'Кылме', 'Теле'], 'months_short' => ['Шрк', 'Пгж', 'Ӱрн', 'Вшр', 'Ага', 'Пдш', 'Срм', 'Срл', 'Идм', 'Шыж', 'Клм', 'Тел'], 'weekdays' => ['Рушарня', 'Шочмо', 'Кушкыжмо', 'Вӱргече', 'Изарня', 'Кугарня', 'Шуматкече'], 'weekdays_short' => ['Ршр', 'Шчм', 'Кжм', 'Вгч', 'Изр', 'Кгр', 'Шмт'], 'weekdays_min' => ['Ршр', 'Шчм', 'Кжм', 'Вгч', 'Изр', 'Кгр', 'Шмт'], 'first_day_of_week' => 1, 'day_of_first_week_of_year' => 1, 'year' => ':count идалык', 'y' => ':count идалык', 'a_year' => ':count идалык', 'month' => ':count Тылзе', 'm' => ':count Тылзе', 'a_month' => ':count Тылзе', 'week' => ':count арня', 'w' => ':count арня', 'a_week' => ':count арня', 'day' => ':count кече', 'd' => ':count кече', 'a_day' => ':count кече', 'hour' => ':count час', 'h' => ':count час', 'a_hour' => ':count час', 'minute' => ':count минут', 'min' => ':count минут', 'a_minute' => ':count минут', 'second' => ':count кокымшан', 's' => ':count кокымшан', 'a_second' => ':count кокымшан', ]);
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/ig_NG.php
src/Carbon/Lang/ig_NG.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* * Authors: * - pablo@mandriva.com */ return array_replace_recursive(require __DIR__.'/en.php', [ 'formats' => [ 'L' => 'DD/MM/YY', ], 'months' => ['Jenụwarị', 'Febrụwarị', 'Maachị', 'Eprel', 'Mee', 'Juun', 'Julaị', 'Ọgọọst', 'Septemba', 'Ọktoba', 'Novemba', 'Disemba'], 'months_short' => ['Jen', 'Feb', 'Maa', 'Epr', 'Mee', 'Juu', 'Jul', 'Ọgọ', 'Sep', 'Ọkt', 'Nov', 'Dis'], 'weekdays' => ['sọnde', 'mọnde', 'tuzde', 'wenzde', 'tọsde', 'fraịde', 'satọde'], 'weekdays_short' => ['sọn', 'mọn', 'tuz', 'wen', 'tọs', 'fra', 'sat'], 'weekdays_min' => ['sọn', 'mọn', 'tuz', 'wen', 'tọs', 'fra', 'sat'], 'first_day_of_week' => 1, 'day_of_first_week_of_year' => 1, 'year' => 'afo :count', 'y' => 'afo :count', 'a_year' => 'afo :count', 'month' => 'önwa :count', 'm' => 'önwa :count', 'a_month' => 'önwa :count', 'week' => 'izu :count', 'w' => 'izu :count', 'a_week' => 'izu :count', 'day' => 'ụbọchị :count', 'd' => 'ụbọchị :count', 'a_day' => 'ụbọchị :count', 'hour' => 'awa :count', 'h' => 'awa :count', 'a_hour' => 'awa :count', 'minute' => 'minit :count', 'min' => 'minit :count', 'a_minute' => 'minit :count', 'second' => 'sekọnd :count', 's' => 'sekọnd :count', 'a_second' => 'sekọnd :count', ]);
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/pt_BR.php
src/Carbon/Lang/pt_BR.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* * Authors: * - Cassiano Montanari * - Eduardo Dalla Vecchia * - David Rodrigues * - Matt Pope * - François B * - Prodis * - Marlon Maxwel * - JD Isaacks * - Raphael Amorim * - Rafael Raupp * - felipeleite1 * - swalker * - Lucas Macedo * - Paulo Freitas * - Sebastian Thierer */ return array_replace_recursive(require __DIR__.'/pt.php', [ 'period_recurrences' => 'uma|:count vez', 'period_interval' => 'toda :interval', 'formats' => [ 'LLL' => 'D [de] MMMM [de] YYYY [às] HH:mm', 'LLLL' => 'dddd, D [de] MMMM [de] YYYY [às] HH:mm', ], 'first_day_of_week' => 0, 'day_of_first_week_of_year' => 1, ]);
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/en_PK.php
src/Carbon/Lang/en_PK.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ return array_replace_recursive(require __DIR__.'/en.php', [ 'first_day_of_week' => 0, ]);
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/pt_GW.php
src/Carbon/Lang/pt_GW.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ return require __DIR__.'/pt.php';
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/el_CY.php
src/Carbon/Lang/el_CY.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* * Authors: * - Greek Debian Translation Team bug-glibc@gnu.org */ return array_replace_recursive(require __DIR__.'/el.php', [ 'first_day_of_week' => 1, 'day_of_first_week_of_year' => 1, ]);
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/fr_CH.php
src/Carbon/Lang/fr_CH.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* * Authors: * - Dieter Sting * - François B * - Gaspard Bucher * - Maxime VALY * - JD Isaacks */ return array_replace_recursive(require __DIR__.'/fr.php', [ 'formats' => [ 'L' => 'DD.MM.YYYY', ], ]);
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/luo.php
src/Carbon/Lang/luo.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ return array_replace_recursive(require __DIR__.'/en.php', [ 'first_day_of_week' => 0, 'meridiem' => ['OD', 'OT'], 'weekdays' => ['Jumapil', 'Wuok Tich', 'Tich Ariyo', 'Tich Adek', 'Tich Ang’wen', 'Tich Abich', 'Ngeso'], 'weekdays_short' => ['JMP', 'WUT', 'TAR', 'TAD', 'TAN', 'TAB', 'NGS'], 'weekdays_min' => ['JMP', 'WUT', 'TAR', 'TAD', 'TAN', 'TAB', 'NGS'], 'months' => ['Dwe mar Achiel', 'Dwe mar Ariyo', 'Dwe mar Adek', 'Dwe mar Ang’wen', 'Dwe mar Abich', 'Dwe mar Auchiel', 'Dwe mar Abiriyo', 'Dwe mar Aboro', 'Dwe mar Ochiko', 'Dwe mar Apar', 'Dwe mar gi achiel', 'Dwe mar Apar gi ariyo'], 'months_short' => ['DAC', 'DAR', 'DAD', 'DAN', 'DAH', 'DAU', 'DAO', 'DAB', 'DOC', 'DAP', 'DGI', 'DAG'], 'formats' => [ 'LT' => 'HH:mm', 'LTS' => 'HH:mm:ss', 'L' => 'DD/MM/YYYY', 'LL' => 'D MMM YYYY', 'LLL' => 'D MMMM YYYY HH:mm', 'LLLL' => 'dddd, D MMMM YYYY HH:mm', ], 'year' => 'higni :count', 'y' => 'higni :count', 'a_year' => ':higni :count', 'month' => 'dweche :count', 'm' => 'dweche :count', 'a_month' => 'dweche :count', 'week' => 'jumbe :count', 'w' => 'jumbe :count', 'a_week' => 'jumbe :count', 'day' => 'ndalo :count', 'd' => 'ndalo :count', 'a_day' => 'ndalo :count', 'hour' => 'seche :count', 'h' => 'seche :count', 'a_hour' => 'seche :count', 'minute' => 'dakika :count', 'min' => 'dakika :count', 'a_minute' => 'dakika :count', 'second' => 'nus dakika :count', 's' => 'nus dakika :count', 'a_second' => 'nus dakika :count', ]);
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/fr_MQ.php
src/Carbon/Lang/fr_MQ.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ return require __DIR__.'/fr.php';
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/yo_BJ.php
src/Carbon/Lang/yo_BJ.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ return array_replace_recursive(require __DIR__.'/yo.php', [ 'meridiem' => ['Àárɔ̀', 'Ɔ̀sán'], 'weekdays' => ['Ɔjɔ́ Àìkú', 'Ɔjɔ́ Ajé', 'Ɔjɔ́ Ìsɛ́gun', 'Ɔjɔ́rú', 'Ɔjɔ́bɔ', 'Ɔjɔ́ Ɛtì', 'Ɔjɔ́ Àbámɛ́ta'], 'weekdays_short' => ['Àìkú', 'Ajé', 'Ìsɛ́gun', 'Ɔjɔ́rú', 'Ɔjɔ́bɔ', 'Ɛtì', 'Àbámɛ́ta'], 'weekdays_min' => ['Àìkú', 'Ajé', 'Ìsɛ́gun', 'Ɔjɔ́rú', 'Ɔjɔ́bɔ', 'Ɛtì', 'Àbámɛ́ta'], 'months' => ['Oshù Shɛ́rɛ́', 'Oshù Èrèlè', 'Oshù Ɛrɛ̀nà', 'Oshù Ìgbé', 'Oshù Ɛ̀bibi', 'Oshù Òkúdu', 'Oshù Agɛmɔ', 'Oshù Ògún', 'Oshù Owewe', 'Oshù Ɔ̀wàrà', 'Oshù Bélú', 'Oshù Ɔ̀pɛ̀'], 'months_short' => ['Shɛ́rɛ́', 'Èrèlè', 'Ɛrɛ̀nà', 'Ìgbé', 'Ɛ̀bibi', 'Òkúdu', 'Agɛmɔ', 'Ògún', 'Owewe', 'Ɔ̀wàrà', 'Bélú', 'Ɔ̀pɛ̀'], 'first_day_of_week' => 1, 'formats' => [ 'LT' => 'HH:mm', 'LTS' => 'HH:mm:ss', 'L' => 'DD/MM/YYYY', 'LL' => 'D MMM YYYY', 'LLL' => 'D MMMM YYYY HH:mm', 'LLLL' => 'dddd, D MMMM YYYY HH:mm', ], ]);
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/hne_IN.php
src/Carbon/Lang/hne_IN.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* * Authors: * - Red Hat, Pune bug-glibc-locales@gnu.org */ return array_replace_recursive(require __DIR__.'/en.php', [ 'formats' => [ 'L' => 'D/M/YY', ], 'months' => ['जनवरी', 'फरवरी', 'मार्च', 'अपरेल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितमबर', 'अकटूबर', 'नवमबर', 'दिसमबर'], 'months_short' => ['जन', 'फर', 'मार्च', 'अप', 'मई', 'जून', 'जुला', 'अग', 'सित', 'अकटू', 'नव', 'दिस'], 'weekdays' => ['इतवार', 'सोमवार', 'मंगलवार', 'बुधवार', 'बिरसपत', 'सुकरवार', 'सनिवार'], 'weekdays_short' => ['इत', 'सोम', 'मंग', 'बुध', 'बिर', 'सुक', 'सनि'], 'weekdays_min' => ['इत', 'सोम', 'मंग', 'बुध', 'बिर', 'सुक', 'सनि'], 'first_day_of_week' => 0, 'day_of_first_week_of_year' => 1, 'meridiem' => ['बिहिनियाँ', 'मंझनियाँ'], ]);
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/seh.php
src/Carbon/Lang/seh.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ return array_replace_recursive(require __DIR__.'/en.php', [ 'first_day_of_week' => 0, 'weekdays' => ['Dimingu', 'Chiposi', 'Chipiri', 'Chitatu', 'Chinai', 'Chishanu', 'Sabudu'], 'weekdays_short' => ['Dim', 'Pos', 'Pir', 'Tat', 'Nai', 'Sha', 'Sab'], 'weekdays_min' => ['Dim', 'Pos', 'Pir', 'Tat', 'Nai', 'Sha', 'Sab'], 'months' => ['Janeiro', 'Fevreiro', 'Marco', 'Abril', 'Maio', 'Junho', 'Julho', 'Augusto', 'Setembro', 'Otubro', 'Novembro', 'Decembro'], 'months_short' => ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Aug', 'Set', 'Otu', 'Nov', 'Dec'], 'formats' => [ 'LT' => 'HH:mm', 'LTS' => 'HH:mm:ss', 'L' => 'D/M/YYYY', 'LL' => 'd [de] MMM [de] YYYY', 'LLL' => 'd [de] MMMM [de] YYYY HH:mm', 'LLLL' => 'dddd, d [de] MMMM [de] YYYY HH:mm', ], ]);
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/os_RU.php
src/Carbon/Lang/os_RU.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* * Authors: * - bug-glibc-locales@gnu.org */ return array_replace_recursive(require __DIR__.'/en.php', [ 'formats' => [ 'L' => 'DD.MM.YYYY', ], 'months' => ['январы', 'февралы', 'мартъийы', 'апрелы', 'майы', 'июны', 'июлы', 'августы', 'сентябры', 'октябры', 'ноябры', 'декабры'], 'months_short' => ['Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн', 'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек'], 'weekdays' => ['Хуыцаубон', 'Къуырисæр', 'Дыццæг', 'Æртыццæг', 'Цыппæрæм', 'Майрæмбон', 'Сабат'], 'weekdays_short' => ['Хцб', 'Крс', 'Дцг', 'Æрт', 'Цпр', 'Мрб', 'Сбт'], 'weekdays_min' => ['Хцб', 'Крс', 'Дцг', 'Æрт', 'Цпр', 'Мрб', 'Сбт'], 'first_day_of_week' => 1, 'day_of_first_week_of_year' => 1, 'minute' => ':count гыццыл', // less reliable 'min' => ':count гыццыл', // less reliable 'a_minute' => ':count гыццыл', // less reliable 'second' => ':count æндæр', // less reliable 's' => ':count æндæр', // less reliable 'a_second' => ':count æндæр', // less reliable 'year' => ':count аз', 'y' => ':count аз', 'a_year' => ':count аз', 'month' => ':count мӕй', 'm' => ':count мӕй', 'a_month' => ':count мӕй', 'week' => ':count къуыри', 'w' => ':count къуыри', 'a_week' => ':count къуыри', 'day' => ':count бон', 'd' => ':count бон', 'a_day' => ':count бон', 'hour' => ':count сахат', 'h' => ':count сахат', 'a_hour' => ':count сахат', ]);
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/es_NI.php
src/Carbon/Lang/es_NI.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* * Authors: * - Free Software Foundation, Inc. bug-glibc-locales@gnu.org */ return array_replace_recursive(require __DIR__.'/es.php', [ 'first_day_of_week' => 0, 'day_of_first_week_of_year' => 1, ]);
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/fr_MR.php
src/Carbon/Lang/fr_MR.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ return array_replace_recursive(require __DIR__.'/fr.php', [ 'formats' => [ 'LT' => 'h:mm a', 'LTS' => 'h:mm:ss a', 'L' => 'DD/MM/YYYY', 'LL' => 'D MMM YYYY', 'LLL' => 'D MMMM YYYY h:mm a', 'LLLL' => 'dddd D MMMM YYYY h:mm a', ], ]);
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/en_BE.php
src/Carbon/Lang/en_BE.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ return require __DIR__.'/en.php';
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/en_DM.php
src/Carbon/Lang/en_DM.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ return array_replace_recursive(require __DIR__.'/en.php', [ 'first_day_of_week' => 0, ]);
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Lang/naq.php
src/Carbon/Lang/naq.php
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ return array_replace_recursive(require __DIR__.'/en.php', [ 'meridiem' => ['ǁgoagas', 'ǃuias'], 'weekdays' => ['Sontaxtsees', 'Mantaxtsees', 'Denstaxtsees', 'Wunstaxtsees', 'Dondertaxtsees', 'Fraitaxtsees', 'Satertaxtsees'], 'weekdays_short' => ['Son', 'Ma', 'De', 'Wu', 'Do', 'Fr', 'Sat'], 'weekdays_min' => ['Son', 'Ma', 'De', 'Wu', 'Do', 'Fr', 'Sat'], 'months' => ['ǃKhanni', 'ǃKhanǀgôab', 'ǀKhuuǁkhâb', 'ǃHôaǂkhaib', 'ǃKhaitsâb', 'Gamaǀaeb', 'ǂKhoesaob', 'Aoǁkhuumûǁkhâb', 'Taraǀkhuumûǁkhâb', 'ǂNûǁnâiseb', 'ǀHooǂgaeb', 'Hôasoreǁkhâb'], 'months_short' => ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], 'first_day_of_week' => 1, 'formats' => [ 'LT' => 'h:mm a', 'LTS' => 'h:mm:ss a', 'L' => 'DD/MM/YYYY', 'LL' => 'D MMM YYYY', 'LLL' => 'D MMMM YYYY h:mm a', 'LLLL' => 'dddd, D MMMM YYYY h:mm a', ], 'year' => ':count kurigu', 'y' => ':count kurigu', 'a_year' => ':count kurigu', 'month' => ':count ǁaub', // less reliable 'm' => ':count ǁaub', // less reliable 'a_month' => ':count ǁaub', // less reliable 'week' => ':count hû', // less reliable 'w' => ':count hû', // less reliable 'a_week' => ':count hû', // less reliable 'day' => ':count ǀhobas', // less reliable 'd' => ':count ǀhobas', // less reliable 'a_day' => ':count ǀhobas', // less reliable 'hour' => ':count ǂgaes', // less reliable 'h' => ':count ǂgaes', // less reliable 'a_hour' => ':count ǂgaes', // less reliable 'minute' => ':count minutga', // less reliable 'min' => ':count minutga', // less reliable 'a_minute' => ':count minutga', // less reliable ]);
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/PHPStan/MacroExtension.php
src/Carbon/PHPStan/MacroExtension.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\PHPStan; use Carbon\CarbonInterface; use Carbon\FactoryImmutable; use Closure; use InvalidArgumentException; use PHPStan\Reflection\ClassReflection; use PHPStan\Reflection\MethodReflection; use PHPStan\Reflection\MethodsClassReflectionExtension; use PHPStan\Reflection\ReflectionProvider; use PHPStan\Type\ClosureTypeFactory; use ReflectionFunction; use ReflectionMethod; use stdClass; use Throwable; /** * Class MacroExtension. * * @codeCoverageIgnore Pure PHPStan wrapper. */ final class MacroExtension implements MethodsClassReflectionExtension { /** * @var ReflectionProvider */ protected $reflectionProvider; /** * @var ClosureTypeFactory */ protected $closureTypeFactory; /** * Extension constructor. * * @param ReflectionProvider $reflectionProvider * @param ClosureTypeFactory $closureTypeFactory */ public function __construct( ReflectionProvider $reflectionProvider, ClosureTypeFactory $closureTypeFactory ) { $this->reflectionProvider = $reflectionProvider; $this->closureTypeFactory = $closureTypeFactory; } /** * {@inheritdoc} */ public function hasMethod(ClassReflection $classReflection, string $methodName): bool { if ( $classReflection->getName() !== CarbonInterface::class && !$classReflection->isSubclassOf(CarbonInterface::class) ) { return false; } $className = $classReflection->getName(); return \is_callable([$className, 'hasMacro']) && $className::hasMacro($methodName); } /** * {@inheritdoc} */ public function getMethod(ClassReflection $classReflection, string $methodName): MethodReflection { $macros = FactoryImmutable::getDefaultInstance()->getSettings()['macros'] ?? []; $macro = $macros[$methodName] ?? throw new InvalidArgumentException("Macro '$methodName' not found"); $static = false; $final = false; $deprecated = false; $docComment = null; if (\is_array($macro) && \count($macro) === 2 && \is_string($macro[1])) { \assert($macro[1] !== ''); $reflection = new ReflectionMethod($macro[0], $macro[1]); $closure = \is_object($macro[0]) ? $reflection->getClosure($macro[0]) : $reflection->getClosure(); $static = $reflection->isStatic(); $final = $reflection->isFinal(); $deprecated = $reflection->isDeprecated(); $docComment = $reflection->getDocComment() ?: null; } elseif (\is_string($macro)) { $reflection = new ReflectionFunction($macro); $closure = $reflection->getClosure(); $deprecated = $reflection->isDeprecated(); $docComment = $reflection->getDocComment() ?: null; } elseif ($macro instanceof Closure) { $closure = $macro; try { $boundClosure = Closure::bind($closure, new stdClass()); $static = (!$boundClosure || (new ReflectionFunction($boundClosure))->getClosureThis() === null); } catch (Throwable) { $static = true; } $reflection = new ReflectionFunction($macro); $deprecated = $reflection->isDeprecated(); $docComment = $reflection->getDocComment() ?: null; } if (!isset($closure)) { throw new InvalidArgumentException('Could not create reflection from the spec given'); // @codeCoverageIgnore } $closureType = $this->closureTypeFactory->fromClosureObject($closure); return new MacroMethodReflection( $classReflection, $methodName, $closureType, $static, $final, $deprecated, $docComment, ); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/PHPStan/MacroMethodReflection.php
src/Carbon/PHPStan/MacroMethodReflection.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\PHPStan; use PHPStan\Reflection\ClassReflection; use PHPStan\Reflection\MethodReflection; use PHPStan\Reflection\ParametersAcceptor; use PHPStan\TrinaryLogic; use PHPStan\Type\Type; use function preg_match; class MacroMethodReflection implements MethodReflection { private ClassReflection $declaringClass; private string $methodName; private ParametersAcceptor $macroClosureType; private bool $static; private bool $final; private bool $deprecated; private ?string $docComment; public function __construct( ClassReflection $declaringClass, string $methodName, ParametersAcceptor $macroClosureType, bool $static, bool $final, bool $deprecated, ?string $docComment ) { $this->declaringClass = $declaringClass; $this->methodName = $methodName; $this->macroClosureType = $macroClosureType; $this->static = $static; $this->final = $final; $this->deprecated = $deprecated; $this->docComment = $docComment; } public function getDeclaringClass(): ClassReflection { return $this->declaringClass; } public function isStatic(): bool { return $this->static; } public function isPrivate(): bool { return false; } public function isPublic(): bool { return true; } public function getDocComment(): ?string { return $this->docComment; } public function getName(): string { return $this->methodName; } public function getPrototype(): \PHPStan\Reflection\ClassMemberReflection { return $this; } public function getVariants(): array { return [$this->macroClosureType]; } public function isDeprecated(): TrinaryLogic { return TrinaryLogic::createFromBoolean( $this->deprecated || preg_match('/@deprecated/i', $this->getDocComment() ?: '') ); } public function getDeprecatedDescription(): ?string { return null; } public function isFinal(): TrinaryLogic { return TrinaryLogic::createFromBoolean($this->final); } public function isInternal(): TrinaryLogic { return TrinaryLogic::createNo(); } public function getThrowType(): ?Type { return null; } public function hasSideEffects(): TrinaryLogic { return TrinaryLogic::createMaybe(); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Cli/Invoker.php
src/Carbon/Cli/Invoker.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Cli; class Invoker { public const CLI_CLASS_NAME = 'Carbon\\Cli'; protected function runWithCli(string $className, array $parameters): bool { $cli = new $className(); return $cli(...$parameters); } public function __invoke(...$parameters): bool { if (class_exists(self::CLI_CLASS_NAME)) { return $this->runWithCli(self::CLI_CLASS_NAME, $parameters); } $function = (($parameters[1] ?? '') === 'install' ? ($parameters[2] ?? null) : null) ?: 'shell_exec'; $function('composer require carbon-cli/carbon-cli --no-interaction'); echo 'Installation succeeded.'; return true; } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Laravel/ServiceProvider.php
src/Carbon/Laravel/ServiceProvider.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Laravel; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterval; use Carbon\CarbonPeriod; use Illuminate\Contracts\Events\Dispatcher as DispatcherContract; use Illuminate\Events\Dispatcher; use Illuminate\Events\EventDispatcher; use Illuminate\Support\Carbon as IlluminateCarbon; use Illuminate\Support\Facades\Date; use Throwable; class ServiceProvider extends \Illuminate\Support\ServiceProvider { /** @var callable|null */ protected $appGetter = null; /** @var callable|null */ protected $localeGetter = null; /** @var callable|null */ protected $fallbackLocaleGetter = null; public function setAppGetter(?callable $appGetter): void { $this->appGetter = $appGetter; } public function setLocaleGetter(?callable $localeGetter): void { $this->localeGetter = $localeGetter; } public function setFallbackLocaleGetter(?callable $fallbackLocaleGetter): void { $this->fallbackLocaleGetter = $fallbackLocaleGetter; } public function boot() { $this->updateLocale(); $this->updateFallbackLocale(); if (!$this->app->bound('events')) { return; } $service = $this; $events = $this->app['events']; if ($this->isEventDispatcher($events)) { $events->listen(class_exists('Illuminate\Foundation\Events\LocaleUpdated') ? 'Illuminate\Foundation\Events\LocaleUpdated' : 'locale.changed', function () use ($service) { $service->updateLocale(); }); } } public function updateLocale() { $locale = $this->getLocale(); if ($locale === null) { return; } Carbon::setLocale($locale); CarbonImmutable::setLocale($locale); CarbonPeriod::setLocale($locale); CarbonInterval::setLocale($locale); if (class_exists(IlluminateCarbon::class)) { IlluminateCarbon::setLocale($locale); } if (class_exists(Date::class)) { try { $root = Date::getFacadeRoot(); $root->setLocale($locale); } catch (Throwable) { // Non Carbon class in use in Date facade } } } public function updateFallbackLocale() { $locale = $this->getFallbackLocale(); if ($locale === null) { return; } Carbon::setFallbackLocale($locale); CarbonImmutable::setFallbackLocale($locale); CarbonPeriod::setFallbackLocale($locale); CarbonInterval::setFallbackLocale($locale); if (class_exists(IlluminateCarbon::class) && method_exists(IlluminateCarbon::class, 'setFallbackLocale')) { IlluminateCarbon::setFallbackLocale($locale); } if (class_exists(Date::class)) { try { $root = Date::getFacadeRoot(); $root->setFallbackLocale($locale); } catch (Throwable) { // @codeCoverageIgnore // Non Carbon class in use in Date facade } } } public function register() { // Needed for Laravel < 5.3 compatibility } protected function getLocale() { if ($this->localeGetter) { return ($this->localeGetter)(); } $app = $this->getApp(); $app = $app && method_exists($app, 'getLocale') ? $app : $this->getGlobalApp('translator'); return $app ? $app->getLocale() : null; } protected function getFallbackLocale() { if ($this->fallbackLocaleGetter) { return ($this->fallbackLocaleGetter)(); } $app = $this->getApp(); return $app && method_exists($app, 'getFallbackLocale') ? $app->getFallbackLocale() : $this->getGlobalApp('translator')?->getFallback(); } protected function getApp() { if ($this->appGetter) { return ($this->appGetter)(); } return $this->app ?? $this->getGlobalApp(); } protected function getGlobalApp(...$args) { return \function_exists('app') ? \app(...$args) : null; } protected function isEventDispatcher($instance) { return $instance instanceof EventDispatcher || $instance instanceof Dispatcher || $instance instanceof DispatcherContract; } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Constants/TranslationOptions.php
src/Carbon/Constants/TranslationOptions.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Constants; interface TranslationOptions { /** * Translate string options. */ public const TRANSLATE_MONTHS = 1; public const TRANSLATE_DAYS = 2; public const TRANSLATE_UNITS = 4; public const TRANSLATE_MERIDIEM = 8; public const TRANSLATE_DIFF = 0x10; public const TRANSLATE_ALL = self::TRANSLATE_MONTHS | self::TRANSLATE_DAYS | self::TRANSLATE_UNITS | self::TRANSLATE_MERIDIEM | self::TRANSLATE_DIFF; /** * Special settings to get the start of week from current locale culture. */ public const WEEK_DAY_AUTO = 'auto'; /** * Default locale (language and region). * * @var string */ public const DEFAULT_LOCALE = 'en'; }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Constants/DiffOptions.php
src/Carbon/Constants/DiffOptions.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Constants; interface DiffOptions { /** * Diff wording options(expressed in octal). */ public const NO_ZERO_DIFF = 01; public const JUST_NOW = 02; public const ONE_DAY_WORDS = 04; public const TWO_DAY_WORDS = 010; public const SEQUENTIAL_PARTS_ONLY = 020; public const ROUND = 040; public const FLOOR = 0100; public const CEIL = 0200; /** * Diff syntax options. */ public const DIFF_ABSOLUTE = 1; // backward compatibility with true public const DIFF_RELATIVE_AUTO = 0; // backward compatibility with false public const DIFF_RELATIVE_TO_NOW = 2; public const DIFF_RELATIVE_TO_OTHER = 3; }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Constants/UnitValue.php
src/Carbon/Constants/UnitValue.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Constants; interface UnitValue { /** * The day constants. */ public const SUNDAY = 0; public const MONDAY = 1; public const TUESDAY = 2; public const WEDNESDAY = 3; public const THURSDAY = 4; public const FRIDAY = 5; public const SATURDAY = 6; /** * The month constants. * These aren't used by Carbon itself but exist for * convenience's sake alone. */ public const JANUARY = 1; public const FEBRUARY = 2; public const MARCH = 3; public const APRIL = 4; public const MAY = 5; public const JUNE = 6; public const JULY = 7; public const AUGUST = 8; public const SEPTEMBER = 9; public const OCTOBER = 10; public const NOVEMBER = 11; public const DECEMBER = 12; /** * Number of X in Y. */ public const YEARS_PER_MILLENNIUM = 1_000; public const YEARS_PER_CENTURY = 100; public const YEARS_PER_DECADE = 10; public const MONTHS_PER_YEAR = 12; public const MONTHS_PER_QUARTER = 3; public const QUARTERS_PER_YEAR = 4; public const WEEKS_PER_YEAR = 52; public const WEEKS_PER_MONTH = 4; public const DAYS_PER_YEAR = 365; public const DAYS_PER_WEEK = 7; public const HOURS_PER_DAY = 24; public const MINUTES_PER_HOUR = 60; public const SECONDS_PER_MINUTE = 60; public const MILLISECONDS_PER_SECOND = 1_000; public const MICROSECONDS_PER_MILLISECOND = 1_000; public const MICROSECONDS_PER_SECOND = 1_000_000; }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/src/Carbon/Constants/Format.php
src/Carbon/Constants/Format.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Constants; interface Format { /** * RFC7231 DateTime format. * * @var string */ public const RFC7231_FORMAT = 'D, d M Y H:i:s \G\M\T'; /** * Default format to use for __toString method when type juggling occurs. * * @var string */ public const DEFAULT_TO_STRING_FORMAT = 'Y-m-d H:i:s'; /** * Format for converting mocked time, includes microseconds. * * @var string */ public const MOCK_DATETIME_FORMAT = 'Y-m-d H:i:s.u'; /** * Pattern detection for ->isoFormat and ::createFromIsoFormat. * * @var string */ public const ISO_FORMAT_REGEXP = '(O[YMDHhms]|[Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY?|g{1,5}|G{1,5}|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?)'; }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/AbstractTestCase.php
tests/AbstractTestCase.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use Carbon\CarbonInterval; use Carbon\CarbonPeriod; use Carbon\CarbonPeriodImmutable; use Carbon\CarbonTimeZone; use Carbon\Translator; use Closure; use DateTime; use ErrorException; use LogicException; use PHPUnit\Framework\TestCase; use PHPUnit\Runner\Version; use RecursiveDirectoryIterator; use RecursiveIteratorIterator; use ReflectionProperty; use Tests\PHPUnit\AssertObjectHasPropertyTrait; use Throwable; /** * @SuppressWarnings(NumberOfChildren) */ abstract class AbstractTestCase extends TestCase { use AssertObjectHasPropertyTrait; private ?string $saveTz = null; protected ?Carbon $now = null; protected ?CarbonImmutable $immutableNow = null; protected bool $oldNow = false; protected bool $oldImmutableNow = false; /** @var class-string<CarbonPeriod> */ protected static string $periodClass = CarbonPeriod::class; protected int $initialOptions = 0; protected function getTimestamp(): int { return (new DateTime())->getTimestamp(); } protected function setUp(): void { $this->initialOptions = static::$periodClass === CarbonPeriodImmutable::class ? CarbonPeriod::IMMUTABLE : 0; //save current timezone $this->saveTz = date_default_timezone_get(); date_default_timezone_set('America/Toronto'); /** @var Carbon $now */ $now = $this->oldNow ? Carbon::create(2017, 6, 27, 13, 14, 15, 'UTC') : Carbon::now(); /** @var CarbonImmutable $immutableNow */ $immutableNow = $this->oldImmutableNow ? CarbonImmutable::create(2017, 6, 27, 13, 14, 15, 'UTC') : CarbonImmutable::now(); Carbon::setTestNowAndTimezone($this->now = $now); CarbonImmutable::setTestNowAndTimezone($this->immutableNow = $immutableNow); Carbon::useStrictMode(true); CarbonImmutable::useStrictMode(true); } protected function tearDown(): void { date_default_timezone_set($this->saveTz); Carbon::setTestNow(); Carbon::resetToStringFormat(); Carbon::resetMonthsOverflow(); Carbon::setTranslator(new Translator('en')); Carbon::setLocale('en'); /** @var Translator $translator */ $translator = Carbon::getTranslator(); $translator->resetMessages(); CarbonImmutable::setTestNow(); CarbonImmutable::resetToStringFormat(); CarbonImmutable::resetMonthsOverflow(); CarbonImmutable::setTranslator(new Translator('en')); CarbonImmutable::setLocale('en'); /** @var Translator $translator */ $translator = CarbonImmutable::getTranslator(); $translator->resetMessages(); } public function assertCarbon(CarbonInterface $d, $year, $month, $day, $hour = null, $minute = null, $second = null, $micro = null): void { $expected = [ 'years' => $year, 'months' => $month, 'day' => $day, ]; $actual = [ 'years' => $d->year, 'months' => $d->month, 'day' => $d->day, ]; if ($hour !== null) { $actual['hours'] = $d->hour; $expected['hours'] = $hour; } if ($minute !== null) { $actual['minutes'] = $d->minute; $expected['minutes'] = $minute; } if ($second !== null) { $actual['seconds'] = $d->second; $expected['seconds'] = $second; } if ($micro !== null) { $actual['micro'] = $d->micro; $expected['micro'] = $micro; } $this->assertSame($expected, $actual); } public function assertCarbonTime(CarbonInterface $d, $hour = null, $minute = null, $second = null, $micro = null): void { $actual = []; $expected = []; if ($hour !== null) { $actual['hours'] = $d->hour; $expected['hours'] = $hour; } if ($minute !== null) { $actual['minutes'] = $d->minute; $expected['minutes'] = $minute; } if ($second !== null) { $actual['seconds'] = $d->second; $expected['seconds'] = $second; } if ($micro !== null) { $actual['micro'] = $d->micro; $expected['micro'] = $micro; } $this->assertSame($expected, $actual); } /** * @phpstan-assert CarbonInterface $d */ public function assertInstanceOfCarbon($d): void { $this->assertInstanceOf(CarbonInterface::class, $d); } public function assertCarbonInterval(CarbonInterval $ci, $years, $months = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null, $inverted = null): void { $actual = ['years' => $ci->years]; $expected = ['years' => $years]; if ($months !== null) { $actual['months'] = $ci->months; $expected['months'] = $months; } if ($days !== null) { $actual['days'] = $ci->dayz; $expected['days'] = $days; } if ($hours !== null) { $actual['hours'] = $ci->hours; $expected['hours'] = $hours; } if ($minutes !== null) { $actual['minutes'] = $ci->minutes; $expected['minutes'] = $minutes; } if ($seconds !== null) { $actual['seconds'] = $ci->seconds; $expected['seconds'] = $seconds; } if ($microseconds !== null) { $actual['microseconds'] = $ci->microseconds; $expected['microseconds'] = $microseconds; } $this->assertSame($expected, $actual); if ($inverted !== null) { $this->assertSame((bool) $inverted, (bool) $ci->invert); } } /** * @phpstan-assert CarbonInterval $d */ public function assertInstanceOfCarbonInterval($d): void { $this->assertInstanceOf(CarbonInterval::class, $d); } public function wrapWithTestNow(Closure $func, ?CarbonInterface $dt = null): void { $test = Carbon::getTestNow(); $immutableTest = CarbonImmutable::getTestNow(); $dt = $dt ?: Carbon::now(); Carbon::setTestNowAndTimezone($dt); CarbonImmutable::setTestNowAndTimezone($dt); $func(); Carbon::setTestNowAndTimezone($test); CarbonImmutable::setTestNowAndTimezone($immutableTest); } public function wrapWithNonDstDate(Closure $func): void { $this->wrapWithTestNow($func, Carbon::now()->startOfYear()); } public function wrapWithUtf8LcTimeLocale($locale, Closure $func): void { $currentLocale = setlocale(LC_TIME, '0'); $locales = ["$locale.UTF-8", "$locale.utf8"]; $mapping = [ 'fr_FR' => 'French_France', ]; $windowsLocale = $mapping[$locale] ?? null; if ($windowsLocale) { $locales[] = "$windowsLocale.UTF8"; } if (setlocale(LC_TIME, ...$locales) === false) { $this->markTestSkipped("UTF-8 test need $locale.UTF-8 (a locale with accents)."); } try { $func(); } finally { setlocale(LC_TIME, $currentLocale); } } public function withErrorAsException(Closure $func): void { $previous = set_error_handler(static function (int $code, string $message, string $file, int $line) { throw new ErrorException($message, $code, $code, $file, $line); }); $errorReporting = error_reporting(); try { error_reporting(E_ALL); $func(); } finally { error_reporting($errorReporting); restore_error_handler(); } } /** * Standardize given set of dates (or period) before assertion. * * @param array|\DatePeriod $dates * * @return array */ public function standardizeDates($dates) { $result = []; foreach ($dates as $date) { if ($date instanceof DateTime) { $date = Carbon::instance($date); } elseif (\is_string($date)) { $date = Carbon::parse($date); } $result[] = $date->format('Y-m-d H:i:s P'); } return $result; } protected function areSameLocales($a, $b): bool { static $aliases = null; if ($aliases === null) { $property = new ReflectionProperty(Translator::class, 'aliases'); $aliases = $property->getValue(Translator::get()); } $a = $aliases[$a] ?? $a; $b = $aliases[$b] ?? $b; return $a === $b; } protected function firstValidTimezoneAmong(array $timezones): CarbonTimeZone { $firstError = null; foreach ($timezones as $timezone) { try { return new CarbonTimeZone($timezone); } catch (Throwable $exception) { $firstError = $firstError ?? $exception; } } throw $firstError; } protected function assertPeriodOptions(int $options, CarbonPeriod $period): void { $this->assertSame($this->initialOptions | $options, $period->getOptions()); } protected function assertVeryClose(mixed $expected, mixed $actual, string $message = ''): void { $this->assertEqualsWithDelta( $expected, $actual, 0.000000000000001, $message, ); } protected function assertSameIntervals(CarbonInterval $expected, CarbonInterval $actual, int $microsecondApproximation = 0): void { if ( $expected->microseconds !== $actual->microseconds && $microsecondApproximation > 0 && $actual->microseconds >= $expected->microseconds - $microsecondApproximation && $actual->microseconds <= $expected->microseconds + $microsecondApproximation ) { $actual->optimize(); $expected->optimize(); $expected->microseconds = $actual->microseconds; } $expectedProperties = $this->fetchProperties($expected); $actualProperties = $this->fetchProperties($actual); if ( isset($expectedProperties['f'], $actualProperties['f']) && $expectedProperties['f'] !== $actualProperties['f'] && (abs($expectedProperties['f'] - $actualProperties['f']) * 1_000_000) < ($microsecondApproximation * 1.2) ) { $expectedProperties['f'] = $actualProperties['f']; } if (PHP_VERSION < 8.2) { unset($expectedProperties['days']); unset($actualProperties['days']); } if ( isset($expectedProperties['rawInterval'], $actualProperties['rawInterval']) && $expectedProperties['rawInterval']->f !== $actualProperties['rawInterval']->f && $microsecondApproximation > 0 && $actualProperties['rawInterval']->f >= $expectedProperties['rawInterval']->f - $microsecondApproximation && $actualProperties['rawInterval']->f <= $expectedProperties['rawInterval']->f + $microsecondApproximation ) { unset($expectedProperties['rawInterval']); unset($expectedProperties['originalInput']); unset($actualProperties['rawInterval']); unset($actualProperties['originalInput']); } if (Version::id() >= 12 && isset($expectedProperties['localTranslator'])) { /** @var Translator $expectedTranslator */ $expectedTranslator = $expectedProperties['localTranslator']; /** @var Translator $actualTranslator */ $actualTranslator = $actualProperties['localTranslator'] ?? null; $this->assertInstanceOf(Translator::class, $actualTranslator); $this->assertSame($expectedTranslator->getLocale(), $actualTranslator->getLocale()); $this->assertSameWithClosures($expectedTranslator->getMessages(), $actualTranslator->getMessages()); unset($expectedProperties['localTranslator'], $actualProperties['localTranslator']); } $this->assertEquals($expectedProperties, $actualProperties); } protected function assertSameWithClosures(array $expected, array $actual): void { $expected = $this->acceptClosuresFrom($expected, $actual); $this->assertSame($expected, $actual); } protected function setLocaleOrSkip(string ...$locales): void { if (setlocale(LC_ALL, ...$locales) === false) { $this->markTestSkipped("testSetLocaleToAuto test need $locales[0]."); } $currentLocale = setlocale(LC_TIME, '0'); if (!\in_array($currentLocale, $locales, true)) { throw new LogicException( 'setlocale(LC_ALL, "'.implode('", "', $locales).'") failed, '. 'current locale is unexpected: '.$currentLocale, ); } } protected function remove(string $path): void { if (is_file($path)) { unlink($path); return; } $files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST ); foreach ($files as $fileinfo) { ($fileinfo->isDir() ? rmdir(...) : unlink(...))($fileinfo->getRealPath()); } rmdir($path); } private function acceptClosuresFrom(array $destination, array $source): array { foreach ($source as $key => $value) { if (\is_array($value) && \is_array($destination[$key])) { $destination[$key] = $this->acceptClosuresFrom($destination[$key], $value); continue; } if (($value instanceof Closure) && ($destination[$key] instanceof Closure)) { if ($destination[$key] !== $value && $this->captureVarDump($value) === $this->captureVarDump($destination[$key])) { $destination[$key] = $value; } } } return $destination; } /** @SuppressWarnings(DevelopmentCodeFragment) */ private function captureVarDump(mixed $value): string { ob_start(); var_dump($value); $content = ob_get_contents(); ob_end_clean(); return preg_replace('/(Closure.*)#\d+(\s)/', '$1$2', "$content"); } private function fetchProperties(object $object): array { $properties = (array) $object; return array_combine( array_map( static fn (string $property): string => preg_replace('/^\0\*\0/', '', $property), array_keys($properties), ), $properties, ); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/bootstrap.php
tests/bootstrap.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ require_once __DIR__.'/../vendor/autoload.php'; require_once __DIR__.'/PHPUnit/AssertObjectHasPropertyTrait.php'; set_error_handler(static function ( int $errno, string $errstr, string $errfile = '', int $errline = 0, array $errcontext = [] ): bool { if (!(error_reporting() & $errno)) { return false; } throw new ErrorException($errstr, $errno, $errno, $errfile, $errline); });
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/remove-comments-in-switch.php
tests/remove-comments-in-switch.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ $files = [ __DIR__.'/../src/Carbon/Traits/Date.php', __DIR__.'/../src/Carbon/Traits/Units.php', __DIR__.'/../src/Carbon/Lang/fr.php', ]; $comments = [ '// @--property', '// @property', '// @call ', '// Words with feminine grammatical gender: semaine', ]; foreach ($files as $file) { $contents = str_replace("\r", '', file_get_contents($file)); $newContents = implode("\n", array_filter(explode("\n", $contents), static function ($line) use ($comments) { $code = trim($line); foreach ($comments as $comment) { if (str_starts_with($code, $comment)) { return false; } } return true; })); if ($newContents !== $contents) { file_put_contents($file, $newContents); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/AbstractTestCaseWithOldNow.php
tests/AbstractTestCaseWithOldNow.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests; use Carbon\Carbon; use Carbon\CarbonImmutable; abstract class AbstractTestCaseWithOldNow extends AbstractTestCase { protected bool $oldNow = true; protected bool $oldImmutableNow = true; protected function tearDown(): void { Carbon::resetMacros(); Carbon::serializeUsing(null); CarbonImmutable::resetMacros(); CarbonImmutable::serializeUsing(null); parent::tearDown(); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CommonTraits/MacroContextNestingTest.php
tests/CommonTraits/MacroContextNestingTest.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CommonTraits; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterval; use Carbon\CarbonPeriod; use PHPUnit\Framework\Attributes\DataProvider; use Tests\AbstractTestCaseWithOldNow; class MacroContextNestingTest extends AbstractTestCaseWithOldNow { public static function dataForMacroableClassesWithReference(): array { return [ [Carbon::class, Carbon::parse('2010-05-23'), null], [CarbonImmutable::class, CarbonImmutable::parse('2010-05-23'), null], [CarbonInterval::class, CarbonInterval::make('P1M6D'), (string) (CarbonInterval::seconds(0))], [CarbonPeriod::class, CarbonPeriod::create('2010-08-23', '2010-10-02'), null], ]; } public static function dataForMacroableClasses(): array { return array_map( static fn (array $arguments) => \array_slice($arguments, 0, 2), self::dataForMacroableClassesWithReference(), ); } #[DataProvider('dataForMacroableClassesWithReference')] public function testMacroContextNesting(string $class, mixed $sample, ?string $reference): void { $macro1 = 'macro'.(mt_rand(100, 999999) * 2); $class::macro($macro1, static function () { return self::this()->__toString(); }); $macro2 = 'macro'.(mt_rand(100, 999999) * 2 + 1); $class::macro($macro2, static function () use ($macro1, $sample) { $dates = [self::this()->$macro1()]; $dates[] = $sample->$macro1(); $dates[] = self::this()->$macro1(); return $dates; }); $dates = $class::$macro2(); $this->assertSame([ $reference ?: (string) (new $class()), (string) $sample, $reference ?: (string) (new $class()), ], $dates); } /** * @param class-string $class */ #[DataProvider('dataForMacroableClasses')] public function testMacroContextDetectionNesting(string $class, mixed $sample) { $macro1 = 'macro'.(mt_rand(100, 999999) * 2); $class::macro($macro1, static function () { $context = self::context(); return $context ? \get_class($context) : 'null'; }); $macro2 = 'macro'.(mt_rand(100, 999999) * 2 + 1); $class::macro($macro2, static function () use ($macro1, $sample) { $dump = [self::$macro1(), self::this()->$macro1()]; $dump[] = $sample->$macro1(); $dump[] = self::$macro1(); return $dump; }); $dump = $class::$macro2(); $this->assertSame([ 'null', $class, $class, 'null', ], $dump); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriod/StrictModeTest.php
tests/CarbonPeriod/StrictModeTest.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonPeriod; use BadMethodCallException; use Carbon\Carbon; use Tests\AbstractTestCase; class StrictModeTest extends AbstractTestCase { public function testCallWithStrictMode() { $this->expectExceptionObject(new BadMethodCallException( 'Method foobar does not exist.', )); $periodClass = static::$periodClass; /** @var mixed $period */ $period = $periodClass::create(); $period->foobar(); } public function testCallWithoutStrictMode() { Carbon::useStrictMode(false); $periodClass = static::$periodClass; /** @var mixed $period */ $period = $periodClass::create(); $this->assertSame($period, $period->foobar()); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriod/CloneTest.php
tests/CarbonPeriod/CloneTest.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonPeriod; use Tests\AbstractTestCase; class CloneTest extends AbstractTestCase { public function testClone() { $periodClass = static::$periodClass; $period = $periodClass::create('R4/2012-07-01T00:00:00/P7D'); $clone = $period->clone(); $this->assertSame((string) $period, (string) $clone); $this->assertNotSame($period, $clone); $this->assertEquals($period, $clone); } public function testCopy() { $periodClass = static::$periodClass; $period = $periodClass::create('R4/2012-07-01T00:00:00/P7D'); $clone = $period->copy(); $this->assertSame((string) $period, (string) $clone); $this->assertNotSame($period, $clone); $this->assertEquals($period, $clone); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriod/AliasTest.php
tests/CarbonPeriod/AliasTest.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonPeriod; use BadMethodCallException; use Carbon\Carbon; use Carbon\CarbonInterval; use Carbon\CarbonPeriod; use InvalidArgumentException; use Tests\AbstractTestCase; class AliasTest extends AbstractTestCase { public function testSetStartDate() { $periodClass = static::$periodClass; $period = $periodClass::start($date = '2017-09-13 12:30:45', false); $this->assertEquals(Carbon::parse($date), $period->getStartDate()); $this->assertEquals(Carbon::parse($date), $period->start()); if (PHP_VERSION < 8.2) { $this->assertEquals(Carbon::parse($date), $period->start); } $this->assertPeriodOptions($periodClass::EXCLUDE_START_DATE, $period); $period = $period->since($date = '2014-10-12 15:42:34', true); $this->assertEquals(Carbon::parse($date), $period->getStartDate()); $this->assertPeriodOptions(0, $period); $period = $period->sinceNow(false); $this->assertEquals(Carbon::now(), $period->getStartDate()); $this->assertPeriodOptions($periodClass::EXCLUDE_START_DATE, $period); } public function testSetStartDateWithNamedParameters() { $periodClass = static::$periodClass; $date = '2017-09-13 12:30:45'; /** @var CarbonPeriod $period */ $period = $periodClass::start(date: $date, inclusive: false); $this->assertEquals(Carbon::parse($date), $period->getStartDate()); $this->assertEquals(Carbon::parse($date), $period->start()); if (PHP_VERSION < 8.2) { $this->assertEquals(Carbon::parse($date), $period->start); } $this->assertPeriodOptions(CarbonPeriod::EXCLUDE_START_DATE, $period); /** @var CarbonPeriod $period */ $period = $periodClass::start(date: $date); $this->assertEquals(Carbon::parse($date), $period->getStartDate()); $this->assertEquals(Carbon::parse($date), $period->start()); if (PHP_VERSION < 8.2) { $this->assertEquals(Carbon::parse($date), $period->start); } $this->assertPeriodOptions(0, $period); $date = '2014-10-12 15:42:34'; $period = $period->since(date: $date, inclusive: true); $this->assertEquals(Carbon::parse($date), $period->getStartDate()); $this->assertPeriodOptions(0, $period); $period = $period->sinceNow(inclusive: false); $this->assertEquals(Carbon::now(), $period->getStartDate()); $this->assertPeriodOptions($periodClass::EXCLUDE_START_DATE, $period); $period = $periodClass::sinceNow(); $this->assertEquals(Carbon::now(), $period->getStartDate()); $this->assertPeriodOptions(0, $period); } public function testSetEndDate() { $periodClass = static::$periodClass; $period = $periodClass::end($date = '2017-09-13 12:30:45', false); $this->assertEquals(Carbon::parse($date), $period->getEndDate()); $this->assertEquals(Carbon::parse($date), $period->end()); if (PHP_VERSION < 8.2) { $this->assertEquals(Carbon::parse($date), $period->end); } $this->assertPeriodOptions(CarbonPeriod::EXCLUDE_END_DATE, $period); $period = $period->until($date = '2014-10-12 15:42:34', true); $this->assertEquals(Carbon::parse($date), $period->getEndDate()); $this->assertPeriodOptions(0, $period); $period = $period->untilNow(false); $this->assertEquals(Carbon::now(), $period->getEndDate()); $this->assertPeriodOptions($periodClass::EXCLUDE_END_DATE, $period); $period = $period->end(null); $this->assertNull($period->getEndDate()); } public function testSetEndDateWithNamedParameters() { $periodClass = static::$periodClass; $date = '2017-09-13 12:30:45'; /** @var CarbonPeriod $period */ $period = $periodClass::end(date: $date, inclusive: false); $this->assertEquals(Carbon::parse($date), $period->getEndDate()); $this->assertEquals(Carbon::parse($date), $period->end()); if (PHP_VERSION < 8.2) { $this->assertEquals(Carbon::parse($date), $period->end); } $this->assertPeriodOptions(CarbonPeriod::EXCLUDE_END_DATE, $period); $date = '2014-10-12 15:42:34'; $period = $period->until(date: $date, inclusive: true); $this->assertEquals(Carbon::parse($date), $period->getEndDate()); $this->assertPeriodOptions(0, $period); $period = $period->untilNow(inclusive: false); $this->assertEquals(Carbon::now(), $period->getEndDate()); $this->assertPeriodOptions($periodClass::EXCLUDE_END_DATE, $period); } public function testManageFilters() { $filter = function () { return true; }; $periodClass = static::$periodClass; $period = $periodClass::filter($filter, 'foo'); $this->assertSame([[$filter, 'foo']], $period->getFilters()); $this->assertSame([[$filter, 'foo']], $period->filters()); $period = $period->push($filter, 'bar'); $this->assertSame([[$filter, 'foo'], [$filter, 'bar']], $period->getFilters()); $period = $period->prepend($filter, 'pre'); $this->assertSame([[$filter, 'pre'], [$filter, 'foo'], [$filter, 'bar']], $period->getFilters()); $period = $period->filters([]); $this->assertSame([], $period->getFilters()); $period = $period->filters($filters = [[$filter, null]]); $this->assertSame($filters, $period->getFilters()); } public function testSetRecurrences() { $periodClass = static::$periodClass; $period = $periodClass::recurrences(5); $this->assertSame(5, $period->getRecurrences()); $this->assertSame(5, $period->recurrences()); if (PHP_VERSION < 8.2) { $this->assertSame(5, $period->recurrences); } $period = $period->times(3); $this->assertSame(3, $period->getRecurrences()); $period = $period->recurrences(null); $this->assertNull($period->getRecurrences()); } public function testManageOptions() { $periodClass = static::$periodClass; $start = $periodClass::EXCLUDE_START_DATE; $end = $periodClass::EXCLUDE_END_DATE; $period = $periodClass::options($start); $this->assertSame($start, $period->getOptions()); $period = $period->toggle($start | $end); $this->assertSame($start | $end, $period->getOptions()); $period = $period->toggle($end, false); $this->assertSame($start, $period->getOptions()); $this->assertSame($start, $period->options()); $period = $period->options(null); $this->assertSame(0, $period->getOptions()); } public function testSetDates() { $periodClass = static::$periodClass; $period = $periodClass::dates($start = '2014-10-12 15:42:34', $end = '2017-09-13 12:30:45'); $this->assertEquals(Carbon::parse($start), $period->getStartDate()); $this->assertEquals(Carbon::parse($end), $period->getEndDate()); $period = $period->dates(Carbon::now()); $this->assertEquals(Carbon::now(), $period->getStartDate()); $this->assertNull($period->getEndDate()); } public function testManageInterval() { $periodClass = static::$periodClass; $period = $periodClass::interval('PT6H'); $this->assertEquals(CarbonInterval::create('PT6H')->optimize(), $period->getDateInterval()->optimize()); $this->assertEquals(CarbonInterval::create('PT6H')->optimize(), $period->interval()->optimize()); if (PHP_VERSION < 8.2) { $this->assertEquals(CarbonInterval::create('PT6H')->optimize(), $period->interval->optimize()); } } public function testInvertInterval() { $periodClass = static::$periodClass; $period = $periodClass::invert(); $this->assertEquals( CarbonInterval::create('P1D')->invert()->optimize(), $period->getDateInterval()->optimize(), ); } public function testModifyIntervalPlural() { $periodClass = static::$periodClass; $period = $periodClass::weeks(2); $this->assertSame('P14D', $period->getDateInterval()->spec()); $period = $period->years(2)->months(3)->days(4)->hours(5)->minutes(30)->seconds(15); $this->assertSame('P2Y3M4DT5H30M15S', $period->getDateInterval()->spec()); $period = $period->years(0)->months(0)->dayz(0)->hours(0)->minutes(0)->seconds(1); $this->assertSame('PT1S', $period->getDateInterval()->spec()); $period = $periodClass::create(); $this->assertSame('P1D', $period->getDateInterval()->spec()); $period = $periodClass::create()->hours(12); $this->assertSame('PT12H', $period->getDateInterval()->spec()); $period = $periodClass::day()->hours(12); $this->assertSame('P1DT12H', $period->getDateInterval()->spec()); $period = $periodClass::day()->resetDateInterval()->hours(12); $this->assertSame('PT12H', $period->getDateInterval()->spec()); } public function testModifyIntervalSingular() { $periodClass = static::$periodClass; $period = $periodClass::week(); $this->assertSame('P7D', $period->getDateInterval()->spec()); $period = $period->year()->month()->day()->hour()->minute()->second(); $this->assertSame('P1Y1M1DT1H1M1S', $period->getDateInterval()->spec()); $period = $period->year(2)->month(3)->day(4)->hour(5)->minute(6)->second(7); $this->assertSame('P2Y3M4DT5H6M7S', $period->getDateInterval()->spec()); } public function testChainAliases() { $periodClass = static::$periodClass; Carbon::setTestNow('2018-05-15'); $period = $periodClass::days(3)->hours(5)->invert() ->sinceNow()->until(Carbon::now()->subDays(10)) ->options($periodClass::EXCLUDE_START_DATE) ->times(2); $this->assertSame( $this->standardizeDates([ Carbon::now()->subDays(3)->subHours(5), Carbon::now()->subDays(6)->subHours(10), ]), $this->standardizeDates($period), ); } public function testCallInvalidAlias() { $this->expectExceptionObject(new BadMethodCallException( 'Method foobar does not exist.', )); $periodClass = static::$periodClass; $periodClass::foobar(); } public function testOverrideDefaultInterval() { $periodClass = static::$periodClass; $period = $periodClass::hours(5); $this->assertSame('PT5H', $period->getDateInterval()->spec()); $period = $periodClass::create()->hours(5); $this->assertSame('PT5H', $period->getDateInterval()->spec()); $period = $periodClass::create('P1D')->hours(5); $this->assertSame('P1DT5H', $period->getDateInterval()->spec()); } public function testModifyIntoEmptyDateInterval() { $this->expectExceptionObject(new InvalidArgumentException( 'Empty interval is not accepted.', )); $periodClass = static::$periodClass; $periodClass::days(0); } public function testNamedParameters() { $periodClass = static::$periodClass; $period = $periodClass::between(start: '2022-09-13', end: '2022-10-12'); $this->assertEquals('2022-09-13', $period->getStartDate()->format('Y-m-d')); $this->assertEquals('2022-10-12', $period->getEndDate()->format('Y-m-d')); $period = $period->years(years: 5); $this->assertEquals('5 years', (string) $period->getDateInterval()); $period = $period->interval(interval: \Carbon\CarbonInterval::year(years: 3)); $this->assertEquals('3 years', (string) $period->getDateInterval()); $period = $periodClass::between(start: '2022-09-13', end: '2022-10-12')->months(months: 5); $this->assertEquals('5 months', (string) $period->getDateInterval()); $period = $periodClass::between(start: '2022-09-13', end: '2022-10-12')->weeks(weeks: 5); $this->assertEquals('5 weeks', (string) $period->getDateInterval()); $period = $periodClass::between(start: '2022-09-13', end: '2022-10-12')->days(days: 5); $this->assertEquals('5 days', (string) $period->getDateInterval()); $period = $periodClass::between(start: '2022-09-13', end: '2022-10-12')->hours(hours: 5); $this->assertEquals('5 hours', (string) $period->getDateInterval()); $period = $periodClass::between(start: '2022-09-13', end: '2022-10-12')->minutes(minutes: 5); $this->assertEquals('5 minutes', (string) $period->getDateInterval()); $period = $periodClass::between(start: '2022-09-13', end: '2022-10-12')->seconds(seconds: 5); $this->assertEquals('5 seconds', (string) $period->getDateInterval()); $period = $periodClass::between(start: '2022-09-13', end: '2022-10-12') ->days(days: 5) ->floorDays(precision: 2); $this->assertEquals('4 days', (string) $period->getDateInterval()); $period = $periodClass::between(start: '2022-09-13', end: '2022-10-12') ->days(days: 5) ->roundDays(precision: 7); $this->assertEquals('1 week', (string) $period->getDateInterval()); $period = $periodClass::between(start: '2022-09-13', end: '2022-10-12') ->days(days: 5) ->ceilDays(precision: 2); $this->assertEquals('6 days', (string) $period->getDateInterval()); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriod/IterationMethodsTest.php
tests/CarbonPeriod/IterationMethodsTest.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonPeriod; use Carbon\Carbon; use Tests\AbstractTestCase; class IterationMethodsTest extends AbstractTestCase { public function testForEach() { $result = ''; Carbon::create('2020-12-22')->daysUntil('2020-12-24')->forEach(function (Carbon $date) use (&$result) { $result .= $date->diffInDays('2020-12-25')." days before Christmas!\n"; }); $this->assertSame("3 days before Christmas!\n". "2 days before Christmas!\n". "1 days before Christmas!\n", $result, ); } public function testMap() { $result = iterator_to_array(Carbon::create('2020-12-22')->daysUntil('2020-12-24')->map(function (Carbon $date) { return $date->diffInDays('2020-12-25').' days before Christmas!'; })); $this->assertSame([ '3 days before Christmas!', '2 days before Christmas!', '1 days before Christmas!', ], $result); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriod/GettersTest.php
tests/CarbonPeriod/GettersTest.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonPeriod; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterval; use Carbon\CarbonPeriod; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnreachableException; use DateTime; use Tests\AbstractTestCase; use Tests\CarbonPeriod\Fixtures\CarbonPeriodFactory; class GettersTest extends AbstractTestCase { public function testGetStartDate() { $period = CarbonPeriodFactory::withStartIntervalEnd(static::$periodClass); $date = $period->getStartDate(); $this->assertInstanceOfCarbon($date); $this->assertSame('2012-07-01 17:30:00', $date->format('Y-m-d H:i:s')); } public function testGetEndDate() { $period = CarbonPeriodFactory::withStartIntervalEnd(static::$periodClass); $date = $period->getEndDate(); $this->assertInstanceOfCarbon($date); $this->assertSame('2012-07-15 11:15:00', $date->format('Y-m-d H:i:s')); } public function testGetDateInterval() { $period = CarbonPeriodFactory::withStartIntervalEnd(static::$periodClass); $interval = $period->getDateInterval(); $this->assertInstanceOfCarbonInterval($interval); $this->assertSame('P3DT5H', $interval->spec()); } public function testGetRecurrences() { $periodClass = static::$periodClass; $recurrences = $periodClass::create(new DateTime(), 5)->getRecurrences(); $this->assertSame(5, $recurrences); $period = $periodClass::create('2024-09-01/3 days/2024-09-30'); $this->assertNull($period->get('recurrences')); $period = $periodClass::create('R3/2024-09-01/3 days'); $this->assertSame(3, $period->get('recurrences')); } public function testGetDefaultDateInterval() { $periodClass = static::$periodClass; $period = $periodClass::create(Carbon::parse('2015-09-30'), Carbon::parse('2015-10-03')); $this->assertInstanceOfCarbonInterval($period->getDateInterval()); $this->assertSame('P1D', $period->getDateInterval()->spec()); } public function testModifyStartDate() { $period = CarbonPeriodFactory::withStartIntervalEnd(static::$periodClass); $period->getStartDate()->subDays(3); $this->assertSame('2012-07-01', $period->getStartDate()->format('Y-m-d')); } public function testModifyEndDate() { $period = CarbonPeriodFactory::withStartIntervalEnd(static::$periodClass); $period->getEndDate()->addDays(3); $this->assertSame('2012-07-15', $period->getEndDate()->format('Y-m-d')); } public function testModifyDateInterval() { $period = CarbonPeriodFactory::withStartIntervalEnd(static::$periodClass); $period->getDateInterval()->days(5)->hours(0); $this->assertSame('P3DT5H', $period->getDateInterval()->spec()); } public function testGetOptions() { $periodClass = static::$periodClass; $period = new $periodClass(); $this->assertPeriodOptions(0, $period); $this->assertTrue($period->isStartIncluded()); $this->assertTrue($period->isEndIncluded()); if (PHP_VERSION < 8.2) { $this->assertTrue($period->include_start_date); $this->assertTrue($period->include_end_date); } $period = new $periodClass(new DateTime(), new DateTime(), $options = $periodClass::EXCLUDE_START_DATE | $periodClass::EXCLUDE_END_DATE); $this->assertPeriodOptions($options, $period); $this->assertFalse($period->isStartIncluded()); $this->assertFalse($period->isEndIncluded()); if (PHP_VERSION < 8.2) { $this->assertFalse($period->include_start_date); $this->assertFalse($period->include_end_date); } } public function testOverlaps() { $periodClass = static::$periodClass; $range1 = $periodClass::create('2019-01-26', '2019-03-03'); $range2 = $periodClass::create('2019-02-15', '2019-04-01'); $this->assertTrue($range1->overlaps($range2)); $this->assertTrue($range2->overlaps($range1)); $range1 = $periodClass::create('2019-01-26', '2019-02-13'); $range2 = $periodClass::create('2019-02-15', '2019-04-01'); $this->assertFalse($range1->overlaps($range2)); $this->assertFalse($range2->overlaps($range1)); $range1 = $periodClass::create('2019-01-26', '2019-02-15'); $range2 = $periodClass::create('2019-02-15', '2019-04-01'); $this->assertFalse($range1->overlaps($range2)); $this->assertFalse($range2->overlaps($range1)); $range1 = $periodClass::create('2019-01-26', '2019-02-15 00:00:01'); $range2 = $periodClass::create('2019-02-15', '2019-04-01'); $this->assertTrue($range1->overlaps($range2)); $this->assertTrue($range2->overlaps($range1)); $range1 = $periodClass::create('2019-01-26', '2019-02-15 00:00:01'); $range2 = $periodClass::create('2019-02-15 00:00:01', '2019-04-01'); $this->assertFalse($range1->overlaps($range2)); $this->assertFalse($range2->overlaps($range1)); $range1 = $periodClass::create('2019-01-26 10:30:12', '2019-01-26 13:30:12'); $range2 = $periodClass::create('2019-01-26 10:30:05', '2019-01-26 13:32:12'); $this->assertTrue($range1->overlaps($range2)); $this->assertTrue($range2->overlaps($range1)); $range1 = $periodClass::create('2019-01-26 10:30:12', INF); $range2 = $periodClass::create('2999-01-26 10:30:05', '2999-01-26 13:32:12'); $this->assertFalse($range1->calculateEnd()->isStartOfTime()); $this->assertTrue($range1->calculateEnd()->isEndOfTime()); $this->assertFalse($range2->calculateEnd()->isStartOfTime()); $this->assertFalse($range2->calculateEnd()->isEndOfTime()); $this->assertTrue($range1->overlaps($range2)); $this->assertTrue($range2->overlaps($range1)); $range1 = $periodClass::create('2019-01-26 10:30:12', CarbonInterval::day(-1), INF); $range2 = $periodClass::create('2999-01-26 10:30:05', '2999-01-26 13:32:12'); $this->assertTrue($range1->calculateEnd()->isStartOfTime()); $this->assertFalse($range1->calculateEnd()->isEndOfTime()); $this->assertFalse($range2->calculateEnd()->isStartOfTime()); $this->assertFalse($range2->calculateEnd()->isEndOfTime()); $this->assertFalse($range1->overlaps($range2)); $this->assertFalse($range2->overlaps($range1)); $range1 = $periodClass::create('2019-01-26 10:30:12', INF); $range2 = $periodClass::create('1975-01-26 10:30:05', '1975-01-26 13:32:12'); $this->assertFalse($range1->overlaps($range2)); $this->assertFalse($range2->overlaps($range1)); $range1 = $periodClass::create('2019-01-26 10:30:12', CarbonInterval::day(-1), INF); $range2 = $periodClass::create('1975-01-26 10:30:05', '1975-01-26 13:32:12'); $this->assertTrue($range1->overlaps($range2)); $this->assertTrue($range2->overlaps($range1)); $range1 = $periodClass::create('2019-01-26 10:30:12', INF); $range2 = $periodClass::create('2999-01-26 10:30:05', INF); $this->assertTrue($range1->overlaps($range2)); $this->assertTrue($range2->overlaps($range1)); $range1 = $periodClass::create('2019-01-26 10:30:12', CarbonInterval::day(-1), INF); $range2 = $periodClass::create('2999-01-26 10:30:05', INF); $this->assertFalse($range1->overlaps($range2)); $this->assertFalse($range2->overlaps($range1)); $range1 = $periodClass::create('2019-01-26 10:30:12', INF); $range2 = $periodClass::create('1975-01-26 10:30:05', INF); $this->assertTrue($range1->overlaps($range2)); $this->assertTrue($range2->overlaps($range1)); $range1 = $periodClass::create('2019-01-26 10:30:12', INF); $range2 = $periodClass::create('1975-01-26 10:30:05', CarbonInterval::day(-1), INF); $this->assertFalse($range1->overlaps($range2)); $this->assertFalse($range2->overlaps($range1)); $range1 = $periodClass::create('2019-01-26 10:30:12', CarbonInterval::day(-1), INF); $range2 = $periodClass::create('1975-01-26 10:30:05', INF); $this->assertTrue($range1->overlaps($range2)); $this->assertTrue($range2->overlaps($range1)); $range1 = $periodClass::create('2019-01-26 10:30:12', CarbonInterval::day(), 365, $periodClass::EXCLUDE_START_DATE); $range2 = $periodClass::create('2020-01-26 10:30:05', '2020-01-27 10:30:05'); $this->assertTrue($range1->overlaps($range2)); $this->assertTrue($range2->overlaps($range1)); $range1 = $periodClass::create('2019-01-26 10:30:12', CarbonInterval::day(), 365, $periodClass::EXCLUDE_START_DATE); $range2 = $periodClass::create('2020-01-26 10:30:20', '2020-01-27 10:30:20'); $this->assertFalse($range1->overlaps($range2)); $this->assertFalse($range2->overlaps($range1)); $range1 = $periodClass::create('2019-01-26 10:30:12', CarbonInterval::day(), 365); $range2 = $periodClass::create('2020-01-27 10:30:20', '2020-01-28 10:30:20'); $this->assertFalse($range1->overlaps($range2)); $this->assertFalse($range2->overlaps($range1)); $range1 = $periodClass::create('2019-01-26 10:30:12', CarbonInterval::day(), INF); (function () { $this->dateInterval->subDays(1); })->call($range1); $range2 = $periodClass::create('2999-01-26 10:30:05', '2999-01-26 13:32:12'); $this->assertFalse($range1->overlaps($range2)); $this->assertFalse($range2->overlaps($range1)); $range1 = $periodClass::create('2019-01-26 10:30:12', CarbonInterval::day(), INF); (function () { $this->dateInterval->subDays(1); })->call($range1); $range2 = $periodClass::create('2018-01-26 10:30:05', '2019-01-26 13:32:12'); $this->assertTrue($range1->overlaps($range2)); $this->assertTrue($range2->overlaps($range1)); } public function testOverlapsErrorForNullEnd() { $periodClass = static::$periodClass; $this->expectExceptionObject(new UnreachableException( "Could not calculate period end without either explicit end or recurrences.\n". "If you're looking for a forever-period, use ->setRecurrences(INF).", )); $periodClass::create('2019-01-26 10:30:12', null)->overlaps('R2/2019-01-31T10:30:45Z/P2D'); } public function testOverlapsErrorForMaxAttempts() { $periodClass = static::$periodClass; $this->expectExceptionObject(new UnreachableException( 'Could not calculate period end after iterating 10000 times.', )); $period = $periodClass::create('2019-01-26 10:30:12', CarbonInterval::minute(), 98282828); $period = $period->addFilter(function ($date) { return $date->minute % 2; }); $period->overlaps('R2/2019-01-31T10:30:45Z/P2D'); } public function testOverlapsCalculated() { $periodClass = static::$periodClass; $this->assertTrue($periodClass::create('2019-01-27', '2019-02-02')->overlaps('R2/2019-01-31T10:30:45Z/P2D')); $this->assertTrue($periodClass::create('2019-01-27', '2019-02-02')->overlaps('2018-12-31/2019-02-01')); $this->assertFalse($periodClass::create('2019-01-27', '2019-02-02')->overlaps('R6/2018-12-31/P3D')); $this->assertTrue($periodClass::create('2019-01-27', '2019-02-02')->overlaps('R6/2018-12-31/P6D')); $this->assertFalse($periodClass::create('R6/2018-12-31/P1D')->overlaps('R3/2019-01-05/PT3H')); $this->assertTrue($periodClass::create('R7/2018-12-31/P1D')->overlaps('R3/2019-01-05/PT3H')); } public function testOverlapsWithDatesCouple() { $periodClass = static::$periodClass; $carbonClass = $periodClass === CarbonPeriod::class ? Carbon::class : CarbonImmutable::class; $this->assertTrue($carbonClass::parse('2019-01-26')->toPeriod('2019-03-03')->overlaps('2019-02-15', '2019-04-01')); $this->assertTrue($carbonClass::parse('2019-02-15')->toPeriod('2019-04-01')->overlaps('2019-02-15', '2019-04-01')); $this->assertTrue($periodClass::create('2019-01-26', '2019-03-03')->overlaps('2019-02-15', '2019-04-01')); $this->assertTrue($periodClass::create('2019-01-26', '2019-03-03')->overlaps($carbonClass::parse('2019-02-15')->toPeriod('2019-04-01'))); $this->assertTrue($carbonClass::parse('2019-01-26')->toPeriod('2019-03-03')->overlaps($carbonClass::parse('2019-02-15'), '2019-04-01')); $this->assertTrue(Carbon::parse('2019-02-15')->toPeriod('2019-04-01')->overlaps('2019-02-15', CarbonImmutable::parse('2019-04-01'))); $this->assertTrue(CarbonImmutable::parse('2019-02-15')->toPeriod('2019-04-01')->overlaps('2019-02-15', Carbon::parse('2019-04-01'))); $this->assertTrue($periodClass::create('2019-01-26', '2019-03-03')->overlaps(new DateTime('2019-02-15'), new DateTime('2019-04-01'))); $this->assertFalse($carbonClass::parse('2018-01-26')->toPeriod('2018-03-03')->overlaps('2019-02-15', '2019-04-01')); $this->assertFalse($carbonClass::parse('2018-02-15')->toPeriod('2018-04-01')->overlaps('2019-02-15', '2019-04-01')); $this->assertFalse($periodClass::create('2018-01-26', '2018-02-13')->overlaps('2019-02-15', '2019-04-01')); $this->assertFalse($periodClass::create('2018-01-26', '2018-02-13')->overlaps($carbonClass::parse('2019-02-15')->toPeriod('2019-04-01'))); $this->assertFalse($carbonClass::parse('2018-01-26')->toPeriod('2018-03-03')->overlaps($carbonClass::parse('2019-02-15'), '2019-04-01')); $this->assertFalse(Carbon::parse('2018-02-15')->toPeriod('2018-04-01')->overlaps('2019-02-15', CarbonImmutable::parse('2019-04-01'))); $this->assertFalse($periodClass::create('2018-01-26', '2018-02-13')->overlaps(new DateTime('2019-02-15'), new DateTime('2019-04-01'))); } public function testIsStarted() { $periodClass = static::$periodClass; Carbon::setTestNow('2019-08-03 11:47:00'); $this->assertFalse($periodClass::create('2019-08-03 11:47:01', '2019-08-03 12:00:00')->isStarted()); $this->assertFalse($periodClass::create('2020-01-01', '2020-07-01')->isStarted()); $this->assertTrue($periodClass::create('2019-08-03 01:00:00', '2019-08-03 09:00:00')->isStarted()); $this->assertTrue($periodClass::create('2019-01-01', '2019-07-01')->isStarted()); $this->assertTrue($periodClass::create('2019-08-01', '2019-08-15')->isStarted()); $this->assertTrue($periodClass::create('2019-08-03 11:47:00', '2019-08-15 11:47:00')->isStarted()); } public function testIsEnded() { $periodClass = static::$periodClass; Carbon::setTestNow('2019-08-03 11:47:00'); $this->assertFalse($periodClass::create('2019-08-03 11:47:01', '2019-08-03 12:00:00')->isEnded()); $this->assertFalse($periodClass::create('2020-01-01', '2020-07-01')->isEnded()); $this->assertFalse($periodClass::create('2019-08-01', '2019-08-15')->isEnded()); $this->assertFalse($periodClass::create('2019-08-03 11:47:00', '2019-08-15 11:47:00')->isEnded()); $this->assertTrue($periodClass::create('2019-08-03 01:00:00', '2019-08-03 09:00:00')->isEnded()); $this->assertTrue($periodClass::create('2019-01-01', '2019-07-01')->isEnded()); $this->assertTrue($periodClass::create('2019-08-02 11:47:00', '2019-08-03 11:47:00')->isEnded()); } public function testIsInProgress() { $periodClass = static::$periodClass; Carbon::setTestNow('2019-08-03 11:47:00'); $this->assertFalse($periodClass::create('2019-08-03 11:47:01', '2019-08-03 12:00:00')->isInProgress()); $this->assertFalse($periodClass::create('2020-01-01', '2020-07-01')->isInProgress()); $this->assertFalse($periodClass::create('2019-08-03 01:00:00', '2019-08-03 09:00:00')->isInProgress()); $this->assertFalse($periodClass::create('2019-01-01', '2019-07-01')->isInProgress()); $this->assertFalse($periodClass::create('2019-08-02 11:47:00', '2019-08-03 11:47:00')->isInProgress()); $this->assertTrue($periodClass::create('2019-08-03 11:47:00', '2019-08-15 11:47:00')->isInProgress()); $this->assertTrue($periodClass::create('2019-08-01', '2019-08-15')->isInProgress()); } public function testIsset() { $periodClass = static::$periodClass; $this->assertTrue(isset($periodClass::create('2019-08-01', '2019-08-15')->startDate)); $this->assertFalse(isset($periodClass::create('2019-08-01', '2019-08-15')->middleDate)); } public function testMagicGet() { $periodClass = static::$periodClass; $this->assertSame( '2019-08-01', $periodClass::create('2019-08-01', '2019-08-15')->startDate->format('Y-m-d'), ); $this->assertSame( 'en', $periodClass::create('2019-08-01', '2019-08-15')->locale, ); $this->assertSame( 'fi', $periodClass::create('2019-08-01', '2019-08-15')->locale('fi')->locale, ); } public function testGet() { $periodClass = static::$periodClass; $this->assertSame( '2019-08-01', $periodClass::create('2019-08-01', '2019-08-15')->get('start')->format('Y-m-d'), ); } public function testUnknownGetter() { $periodClass = static::$periodClass; $this->expectExceptionObject(new UnknownGetterException('middle')); $periodClass::create('2019-08-01', '2019-08-15')->get('middle'); } public function testGetEnd() { $periodClass = static::$periodClass; $period = $periodClass::create('2024-09-01/3 days/2024-09-30'); $this->assertSame('2024-09-30 00:00:00', $period->end->format('Y-m-d H:i:s')); $this->assertSame('2024-09-30 00:00:00', $period->endDate->format('Y-m-d H:i:s')); } public function testGetCurrent() { $periodClass = static::$periodClass; $period = $periodClass::create('2024-09-01/3 days/2024-09-30'); $this->assertSame('2024-09-01 00:00:00', $period->get('current')->format('Y-m-d H:i:s')); $period->next(); $this->assertSame('2024-09-04 00:00:00', $period->get('current')->format('Y-m-d H:i:s')); } public function testGetInclude() { $periodClass = static::$periodClass; $period = $periodClass::create('2024-09-01/3 days/2024-09-30'); $this->assertTrue($period->includeStartDate); $this->assertTrue($period->includeEndDate); $period = $periodClass::create('2024-09-01/3 days/2024-09-30')->excludeStartDate()->excludeEndDate(); $this->assertFalse($period->includeStartDate); $this->assertFalse($period->includeEndDate); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriod/FilterTest.php
tests/CarbonPeriod/FilterTest.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonPeriod; use Carbon\Carbon; use Carbon\CarbonInterval; use Carbon\CarbonPeriod; use Carbon\CarbonPeriodImmutable; use DateInterval; use DateTime; use RuntimeException; use Tests\AbstractTestCase; use Tests\CarbonPeriod\Fixtures\CarbonPeriodFactory; use Tests\CarbonPeriod\Fixtures\FooFilters; class FilterTest extends AbstractTestCase { public function dummyFilter() { return function () { return true; }; } public function testGetAndSetFilters() { $periodClass = static::$periodClass; $period = new $periodClass(); $this->assertSame([], $period->getFilters()); $result = $period->setFilters($filters = [ [$this->dummyFilter(), null], ]); $this->assertSame($filters, $result->getFilters()); $this->assertMutatorResult($period, $result); } public function testUpdateInternalStateWhenBuiltInFiltersAreRemoved() { $periodClass = static::$periodClass; $period = new $periodClass( $start = new DateTime('2018-04-16'), $end = new DateTime('2018-07-15'), ); $result = $period->setRecurrences($recurrences = 3); $this->assertMutatorResult($period, $result); $result = $result->setFilters($result->getFilters()); $this->assertMutatorResult($result, $period); $this->assertEquals($end, $result->getEndDate()); $this->assertSame($recurrences, $result->getRecurrences()); $result = $result->setFilters([]); $this->assertMutatorResult($result, $period); $this->assertNull($result->getEndDate()); $this->assertNull($result->getRecurrences()); } public function testResetFilters() { $periodClass = static::$periodClass; $period = new $periodClass( $start = new DateTime('2018-04-16'), $end = new DateTime('2018-07-15'), ); $result = $period->addFilter($this->dummyFilter()) ->prependFilter($this->dummyFilter()); $this->assertMutatorResult($period, $result); $result2 = $result->resetFilters(); $this->assertMutatorResult($result2, $result); $this->assertSame([ [$periodClass::END_DATE_FILTER, null], ], $period->getFilters()); } public function testAddAndPrependFilters() { $periodClass = static::$periodClass; $period = new $periodClass(); $result = $period->addFilter($filter1 = $this->dummyFilter()) ->addFilter($filter2 = $this->dummyFilter()) ->prependFilter($filter3 = $this->dummyFilter()); $this->assertMutatorResult($result, $period); $this->assertSame([ [$filter3, null], [$filter1, null], [$filter2, null], ], $result->getFilters()); } public function testRemoveFilterByInstance() { $periodClass = static::$periodClass; $period = new $periodClass(); $result = $period->addFilter($filter1 = $this->dummyFilter()) ->addFilter($filter2 = $this->dummyFilter()) ->addFilter($filter3 = $this->dummyFilter()); $this->assertMutatorResult($result, $period); $this->assertSame([ [$filter1, null], [$filter2, null], [$filter3, null], ], $result->getFilters()); $result = $result->removeFilter($filter2); $this->assertMutatorResult($result, $period); $this->assertSame([ [$filter1, null], [$filter3, null], ], $result->getFilters()); } public function testRemoveFilterByName() { $periodClass = static::$periodClass; $period = new $periodClass(); $result = $period->addFilter($filter1 = $this->dummyFilter()) ->addFilter($filter2 = $this->dummyFilter(), 'foo') ->addFilter($filter3 = $this->dummyFilter()) ->addFilter($filter4 = $this->dummyFilter(), 'foo') ->addFilter($filter5 = $this->dummyFilter()); $this->assertSame([ [$filter1, null], [$filter2, 'foo'], [$filter3, null], [$filter4, 'foo'], [$filter5, null], ], $result->getFilters()); $result = $result->removeFilter('foo'); $this->assertMutatorResult($result, $period); $this->assertSame([ [$filter1, null], [$filter3, null], [$filter5, null], ], $result->getFilters()); } public function testAcceptOnlyWeekdays() { $periodClass = static::$periodClass; Carbon::setWeekendDays([ Carbon::SATURDAY, Carbon::SUNDAY, ]); $period = $periodClass::create('R4/2018-04-14T00:00:00/P4D'); $result = $period->addFilter(function ($date) { return $date->isWeekday(); }); $this->assertMutatorResult($result, $period); $this->assertSame( $this->standardizeDates(['2018-04-18', '2018-04-26', '2018-04-30', '2018-05-04']), $this->standardizeDates($result), ); } /** * @throws \Exception */ public function testAcceptOnlySingleYear() { $periodClass = static::$periodClass; $period = new $periodClass( new DateTime('2017-04-16'), new DateInterval('P5M'), new DateTime('2019-07-15'), ); $result = $period->addFilter(function ($date) { return $date->year === 2018; }); $this->assertMutatorResult($result, $period); $this->assertSame( $this->standardizeDates(['2018-02-16', '2018-07-16', '2018-12-16']), $this->standardizeDates($result), ); } /** * @throws \Exception */ public function testEndIteration() { $periodClass = static::$periodClass; $period = new $periodClass( new DateTime('2018-04-16'), new DateInterval('P3D'), new DateTime('2018-07-15'), ); $result = $period->addFilter(function ($date) use ($periodClass) { return $date->month === 5 ? $periodClass::END_ITERATION : true; }); $this->assertMutatorResult($result, $period); $this->assertSame( $this->standardizeDates(['2018-04-16', '2018-04-19', '2018-04-22', '2018-04-25', '2018-04-28']), $this->standardizeDates($result), ); } public function testRecurrences() { $periodClass = static::$periodClass; $period = new $periodClass( new DateTime('2018-04-16'), new DateTime('2018-07-15'), ); $period = $period->setRecurrences(2); $this->assertSame( $this->standardizeDates(['2018-04-16', '2018-04-17']), $this->standardizeDates($period), ); $result = $period->setOptions($periodClass::EXCLUDE_START_DATE); $this->assertMutatorResult($result, $period); $this->assertSame( $this->standardizeDates(['2018-04-17', '2018-04-18']), $this->standardizeDates($result), ); $result = $result->setOptions($periodClass::EXCLUDE_END_DATE); $this->assertMutatorResult($result, $period); $this->assertSame( $this->standardizeDates(['2018-04-16', '2018-04-17']), $this->standardizeDates($result), ); } public function testChangeNumberOfRecurrences() { $periodClass = static::$periodClass; $period = new $periodClass( new DateTime('2018-04-16'), new DateTime('2018-07-15'), ); $period = $period->setRecurrences(7) ->setRecurrences(1) ->setRecurrences(3); $this->assertSame( $this->standardizeDates(['2018-04-16', '2018-04-17', '2018-04-18']), $this->standardizeDates($period), ); } public function testCallbackArguments() { $periodClass = static::$periodClass; $period = new $periodClass( new DateTime('2018-04-16'), 1, ); $wasCalled = false; $test = $this; $period = $period->addFilter(function ($current, $key, $iterator) use (&$wasCalled, $period, $test) { $test->assertInstanceOfCarbon($current); $test->assertIsInt($key); $test->assertMutatorResult($period, $iterator); return $wasCalled = true; }); iterator_to_array($period); $this->assertTrue($wasCalled); } public function testThrowExceptionWhenNextValidDateCannotBeFound() { $this->expectExceptionObject(new RuntimeException( 'Could not find next valid date.', )); $periodClass = static::$periodClass; $period = $periodClass::create( new Carbon('2000-01-01'), new CarbonInterval('PT1S'), new Carbon('2000-12-31'), ); $period = $period->addFilter(function () { return false; }); iterator_to_array($period); } public function testRemoveBuildInFilters() { $periodClass = static::$periodClass; $period = $periodClass::create(new DateTime('2018-04-16'), new DateTime('2018-07-15'))->setRecurrences(3); $result = $period->setEndDate(null)->setRecurrences(null); $this->assertMutatorResult($result, $period); $this->assertSame([], $result->getFilters()); } public function testAcceptEveryOther() { $periodClass = static::$periodClass; $period = new $periodClass( new DateTime('2018-04-16'), new DateTime('2018-04-20'), ); // Note: Without caching validation results the dates would be unpredictable // as we cannot know how many calls to the filter will occur per iteration. $result = $period->addFilter(static function () { static $accept; return $accept = !$accept; }); $this->assertMutatorResult($result, $period); $this->assertSame( $this->standardizeDates(['2018-04-16', '2018-04-18', '2018-04-20']), $this->standardizeDates($result), ); } public function testEndIterationFilter() { $periodClass = static::$periodClass; $period = new $periodClass('2018-04-16', 5); $result = $period->addFilter($periodClass::END_ITERATION); $this->assertMutatorResult($result, $period); $this->assertSame([], $this->standardizeDates($result)); } public function testAcceptOnlyEvenDays() { $period = CarbonPeriodFactory::withEvenDaysFilter(static::$periodClass); $this->assertSame( $this->standardizeDates(['2012-07-04', '2012-07-10', '2012-07-16']), $this->standardizeDates($period), ); } public function testAddFilterFromCarbonMethod() { $periodClass = static::$periodClass; $period = $periodClass::create('2018-01-01', '2018-06-01'); $result = $period->addFilter('isLastOfMonth'); $this->assertMutatorResult($result, $period); $this->assertSame( $this->standardizeDates(['2018-01-31', '2018-02-28', '2018-03-31', '2018-04-30', '2018-05-31']), $this->standardizeDates($result), ); } public function testAddFilterFromCarbonMacro() { $periodClass = static::$periodClass; $period = $periodClass::create('2018-01-01', '2018-06-01'); Carbon::macro('isTenDay', function () { /** @var Carbon $date */ $date = $this; return $date->day === 10; }); $result = $period->addFilter('isTenDay'); $this->assertMutatorResult($result, $period); $this->assertSame( $this->standardizeDates(['2018-01-10', '2018-02-10', '2018-03-10', '2018-04-10', '2018-05-10']), $this->standardizeDates($result), ); } public function testAddFilterFromCarbonMethodWithArguments() { $periodClass = static::$periodClass; $period = $periodClass::create('2017-01-01', 'P2M16D', '2018-12-31'); $result = $period->addFilter('isSameAs', 'm', new Carbon('2018-06-01')); $this->assertMutatorResult($result, $period); $this->assertSame( $this->standardizeDates(['2017-06-02', '2018-06-20']), $this->standardizeDates($result), ); } public function testRemoveFilterFromCarbonMethod() { $periodClass = static::$periodClass; $period = $periodClass::create('1970-01-01', '1970-01-03')->addFilter('isFuture'); $result = $period->removeFilter('isFuture'); $this->assertMutatorResult($result, $period); $this->assertSame( $this->standardizeDates(['1970-01-01', '1970-01-02', '1970-01-03']), $this->standardizeDates($result), ); } public function testInvalidCarbonMethodShouldNotBeConvertedToCallback() { $periodClass = static::$periodClass; $period = new $periodClass(); $result = $period->addFilter('toDateTimeString'); $this->assertMutatorResult($result, $period); $this->assertSame([ ['toDateTimeString', null], ], $result->getFilters()); } public function testAddCallableFilters() { $periodClass = static::$periodClass; $period = new $periodClass(); $result = $period->addFilter($string = 'date_offset_get') ->addFilter($array = [new DateTime(), 'getOffset']); $this->assertMutatorResult($result, $period); $this->assertSame([ [$string, null], [$array, null], ], $result->getFilters()); } public function testRemoveCallableFilters() { $periodClass = static::$periodClass; $period = new $periodClass(); $result = $period->setFilters([ [$string = 'date_offset_get', null], [$array = [new DateTime(), 'getOffset'], null], ]); $this->assertMutatorResult($result, $period); $result = $period->removeFilter($string)->removeFilter($array); $this->assertMutatorResult($result, $period); $this->assertSame([], $result->getFilters()); } public function testRunCallableFilters() { include_once 'Fixtures/filters.php'; $periodClass = static::$periodClass; $period = new $periodClass('2017-03-10', '2017-03-19'); $callable = [new FooFilters(), 'bar']; $this->assertFalse($period->hasFilter($callable)); $this->assertFalse($period->hasFilter('foobar_filter')); $this->assertFalse($period->hasFilter('not_callable')); $result = $period->addFilter($callable)->addFilter('foobar_filter'); $this->assertMutatorResult($result, $period); $this->assertTrue($result->hasFilter($callable)); $this->assertTrue($result->hasFilter('foobar_filter')); $this->assertFalse($result->hasFilter('not_callable')); $this->assertSame( $this->standardizeDates(['2017-03-10', '2017-03-12', '2017-03-16', '2017-03-18']), $this->standardizeDates($result), ); } protected function assertMutatorResult(CarbonPeriod $a, CarbonPeriod $b): void { if (static::$periodClass === CarbonPeriodImmutable::class) { $this->assertNotSame($a, $b); return; } $this->assertSame($a, $b); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriod/CreateTest.php
tests/CarbonPeriod/CreateTest.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonPeriod; use BadMethodCallException; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use Carbon\CarbonInterval; use Carbon\CarbonPeriod; use Carbon\CarbonPeriodImmutable; use Carbon\Exceptions\InvalidPeriodParameterException; use Carbon\Exceptions\NotAPeriodException; use Carbon\Month; use Carbon\Unit; use DateInterval; use DatePeriod; use DateTime; use Generator; use InvalidArgumentException; use PHPUnit\Framework\Attributes\DataProvider; use stdClass; use Tests\AbstractTestCase; class CreateTest extends AbstractTestCase { #[DataProvider('dataForIso8601String')] public function testCreateFromIso8601String($arguments, $expected) { $periodClass = static::$periodClass; [$iso, $options] = array_pad($arguments, 2, null); $period = $periodClass::create($iso, $options); $this->assertInstanceOf(CarbonPeriod::class, $period); $this->assertInstanceOf(DatePeriod::class, $period); $this->assertSame( $this->standardizeDates($expected), $this->standardizeDates($period), ); } public static function dataForIso8601String(): Generator { yield [ ['R4/2012-07-01T00:00:00/P7D'], ['2012-07-01', '2012-07-08', '2012-07-15', '2012-07-22'], ]; yield [ ['R4/2012-07-01T00:00:00/P7D', CarbonPeriod::EXCLUDE_START_DATE], ['2012-07-08', '2012-07-15', '2012-07-22', '2012-07-29'], ]; yield [ ['2012-07-01/P2D/2012-07-07'], ['2012-07-01', '2012-07-03', '2012-07-05', '2012-07-07'], ]; yield [ ['2012-07-01/2012-07-04', CarbonPeriod::EXCLUDE_END_DATE], ['2012-07-01', '2012-07-02', '2012-07-03'], ]; yield [ ['R2/2012-07-01T10:30:45Z/P2D'], ['2012-07-01 10:30:45 UTC', '2012-07-03 10:30:45 UTC'], ]; } public function testCreateFromIso8601StringWithUnboundedRecurrences() { $periodClass = static::$periodClass; $period = $periodClass::create('R/2012-07-01T00:00:00/P7D'); $this->assertSame('2012-07-01', $period->getStartDate()->toDateString()); $this->assertSame('P7D', $period->getDateInterval()->spec()); $this->assertNull($period->getEndDate()); $this->assertNull($period->getRecurrences()); } public function testCreateFromIso8601StringWithInfiniteRecurrences() { $periodClass = static::$periodClass; $period = $periodClass::create('RINF/2012-07-01T00:00:00/P7D'); $this->assertSame('2012-07-01', $period->getStartDate()->toDateString()); $this->assertSame('P7D', $period->getDateInterval()->spec()); $this->assertNull($period->getEndDate()); $this->assertInfinite($period->getRecurrences()); } #[DataProvider('dataForPartialIso8601String')] public function testCreateFromPartialIso8601String($iso, $from, $to) { $periodClass = static::$periodClass; $period = $periodClass::create($iso); $this->assertSame( $this->standardizeDates([$from, $to]), $this->standardizeDates([$period->getStartDate(), $period->getEndDate()]), ); $period = new $periodClass($iso); $this->assertSame( $this->standardizeDates([$from, $to]), $this->standardizeDates([$period->getStartDate(), $period->getEndDate()]), ); } public static function dataForPartialIso8601String(): Generator { yield ['2008-02-15/03-14', '2008-02-15', '2008-03-14']; yield ['2007-12-14T13:30/15:30', '2007-12-14 13:30', '2007-12-14 15:30']; } #[DataProvider('dataForInvalidIso8601String')] public function testCreateFromInvalidIso8601String($iso) { $this->expectExceptionObject(new InvalidArgumentException( "Invalid ISO 8601 specification: $iso", )); $periodClass = static::$periodClass; $periodClass::create($iso); } public static function dataForInvalidIso8601String(): Generator { yield ['R2/R4']; yield ['2008-02-15/2008-02-16/2008-02-17']; yield ['P1D/2008-02-15/P2D']; yield ['2008-02-15/R5']; yield ['P2D/R2']; yield ['/']; } #[DataProvider('dataForStartDateAndEndDate')] public function testCreateFromStartDateAndEndDate($arguments, $expected) { $periodClass = static::$periodClass; [$start, $end, $options] = array_pad($arguments, 3, null); $start = Carbon::parse($start); $end = Carbon::parse($end); $period = $periodClass::create($start, $end, $options); $this->assertSame( $this->standardizeDates($expected), $this->standardizeDates($period), ); } public static function dataForStartDateAndEndDate(): Generator { yield [ ['2015-09-30', '2015-10-03'], ['2015-09-30', '2015-10-01', '2015-10-02', '2015-10-03'], ]; yield [ ['2015-09-30', '2015-10-03', CarbonPeriod::EXCLUDE_START_DATE], ['2015-10-01', '2015-10-02', '2015-10-03'], ]; yield [ ['2015-09-30', '2015-10-03', CarbonPeriod::EXCLUDE_END_DATE], ['2015-09-30', '2015-10-01', '2015-10-02'], ]; yield [ ['2015-09-30', '2015-10-03', CarbonPeriod::EXCLUDE_START_DATE | CarbonPeriod::EXCLUDE_END_DATE], ['2015-10-01', '2015-10-02'], ]; yield [ ['2015-10-02', '2015-10-03', CarbonPeriod::EXCLUDE_START_DATE | CarbonPeriod::EXCLUDE_END_DATE], [], ]; yield [ ['2015-10-02', '2015-10-02'], ['2015-10-02'], ]; yield [ ['2015-10-02', '2015-10-02', CarbonPeriod::EXCLUDE_START_DATE], [], ]; yield [ ['2015-10-02', '2015-10-02', CarbonPeriod::EXCLUDE_END_DATE], [], ]; } #[DataProvider('dataForStartDateAndIntervalAndEndDate')] public function testCreateFromStartDateAndIntervalAndEndDate($arguments, $expected) { $periodClass = static::$periodClass; [$start, $interval, $end, $options] = array_pad($arguments, 4, null); $start = Carbon::parse($start); $interval = CarbonInterval::create($interval); $end = Carbon::parse($end); $period = $periodClass::create($start, $interval, $end, $options); $this->assertSame( $this->standardizeDates($expected), $this->standardizeDates($period), ); } public static function dataForStartDateAndIntervalAndEndDate(): Generator { yield [ ['2018-04-21', 'P3D', '2018-04-26'], ['2018-04-21', '2018-04-24'], ]; yield [ ['2018-04-21 16:15', 'PT15M', '2018-04-21 16:59:59'], ['2018-04-21 16:15', '2018-04-21 16:30', '2018-04-21 16:45'], ]; yield [ ['2018-04-21 16:15', 'PT15M', '2018-04-21 17:00'], ['2018-04-21 16:15', '2018-04-21 16:30', '2018-04-21 16:45', '2018-04-21 17:00'], ]; yield [ ['2018-04-21 17:00', 'PT45S', '2018-04-21 17:02', CarbonPeriod::EXCLUDE_START_DATE], ['2018-04-21 17:00:45', '2018-04-21 17:01:30'], ]; yield [ ['2017-12-31 22:00', 'PT2H', '2018-01-01 4:00', CarbonPeriod::EXCLUDE_END_DATE], ['2017-12-31 22:00', '2018-01-01 0:00', '2018-01-01 2:00'], ]; yield [ [ '2017-12-31 23:59', 'PT30S', '2018-01-01 0:01', CarbonPeriod::EXCLUDE_START_DATE | CarbonPeriod::EXCLUDE_END_DATE, ], ['2017-12-31 23:59:30', '2018-01-01 0:00', '2018-01-01 0:00:30'], ]; yield [ ['2018-04-21', 'P1D', '2018-04-21'], ['2018-04-21'], ]; yield [ ['2018-04-21', 'P1D', '2018-04-20 23:59:59'], [], ]; } #[DataProvider('dataForStartDateAndIntervalAndRecurrences')] public function testCreateFromStartDateAndIntervalAndRecurrences($arguments, $expected) { $periodClass = static::$periodClass; [$start, $interval, $recurrences, $options] = array_pad($arguments, 4, null); $start = Carbon::parse($start); $interval = CarbonInterval::create($interval); $period = $periodClass::create($start, $interval, $recurrences, $options); $this->assertSame( $this->standardizeDates($expected), $this->standardizeDates($period), ); } public static function dataForStartDateAndIntervalAndRecurrences(): Generator { yield [ ['2018-04-16', 'P2D', 3], ['2018-04-16', '2018-04-18', '2018-04-20'], ]; yield [ ['2018-04-30', 'P2M', 2, CarbonPeriod::EXCLUDE_START_DATE], ['2018-06-30', '2018-08-30'], ]; } #[DataProvider('dataForStartDateAndRecurrences')] public function testCreateFromStartDateAndRecurrences($arguments, $expected) { $periodClass = static::$periodClass; [$start, $recurrences, $options] = array_pad($arguments, 4, null); $start = Carbon::parse($start); $period = $periodClass::create($start, $recurrences, $options); $this->assertSame( $this->standardizeDates($expected), $this->standardizeDates($period), ); } public static function dataForStartDateAndRecurrences(): Generator { yield [ ['2018-04-16', 2], ['2018-04-16', '2018-04-17'], ]; yield [ ['2018-04-30', 1], ['2018-04-30'], ]; yield [ ['2018-04-30', 1, CarbonPeriod::EXCLUDE_START_DATE], ['2018-05-01'], ]; yield [ ['2018-05-17', 0], [], ]; } public function testCreateFromBaseClasses() { $periodClass = static::$periodClass; $period = $periodClass::create( new DateTime('2018-04-16'), new DateInterval('P1M'), new DateTime('2018-07-15'), ); $this->assertSame( [ '2018-04-16 00:00:00 -04:00', '2018-05-16 00:00:00 -04:00', '2018-06-16 00:00:00 -04:00', ], $this->standardizeDates($period), ); } #[DataProvider('dataForInvalidParameters')] public function testCreateFromInvalidParameters(...$arguments) { $this->expectExceptionObject(new InvalidArgumentException( 'Invalid constructor parameters.', )); $periodClass = static::$periodClass; $periodClass::create(...$arguments); } public static function dataForInvalidParameters(): Generator { yield [new stdClass(), CarbonInterval::days(1), Carbon::tomorrow()]; yield [Carbon::now(), new stdClass(), Carbon::tomorrow()]; yield [Carbon::now(), CarbonInterval::days(1), new stdClass()]; yield [Carbon::yesterday(), Carbon::now(), Carbon::tomorrow()]; yield [CarbonInterval::day(), CarbonInterval::hour()]; yield [5, CarbonPeriod::EXCLUDE_START_DATE, CarbonPeriod::EXCLUDE_END_DATE]; yield ['2017-10-15/P3D', CarbonInterval::hour()]; } public function testCreateOnDstForwardChange() { $periodClass = static::$periodClass; $period = $periodClass::create( '2018-03-25 1:30 Europe/Oslo', 'PT30M', '2018-03-25 3:30 Europe/Oslo', ); $this->assertSame( [ '2018-03-25 01:30:00 +01:00', '2018-03-25 03:00:00 +02:00', '2018-03-25 03:30:00 +02:00', ], $this->standardizeDates($period), ); } /** * Incorrect behaviour is caused by a bug in DateTime handling of DST backward change. * It was fixed by incrementing date casted to UTC, but offsets are still kind of wrong. * * @see https://bugs.php.net/bug.php?id=72255 * @see https://bugs.php.net/bug.php?id=74274 * @see https://wiki.php.net/rfc/datetime_and_daylight_saving_time */ public function testCreateOnDstBackwardChange() { $periodClass = static::$periodClass; $period = $periodClass::create( '2018-10-28 1:30 Europe/Oslo', 'PT30M', '2018-10-28 3:30 Europe/Oslo', ); $this->assertSame( [ '2018-10-28 01:30:00 +02:00', '2018-10-28 02:00:00 +02:00', '2018-10-28 02:30:00 +02:00', '2018-10-28 02:00:00 +01:00', '2018-10-28 02:30:00 +01:00', '2018-10-28 03:00:00 +01:00', '2018-10-28 03:30:00 +01:00', ], $this->standardizeDates($period), ); } public function testInternalVariablesCannotBeIndirectlyModified() { $periodClass = static::$periodClass; $period = $periodClass::create( $start = new DateTime('2018-04-16'), $interval = new DateInterval('P1M'), $end = new DateTime('2018-07-15'), ); $start->modify('-5 days'); $interval->d = 15; $end->modify('+5 days'); $this->assertSame('2018-04-16', $period->getStartDate()->toDateString()); $this->assertSame('P1M', $period->getDateInterval()->spec()); $this->assertSame('2018-07-15', $period->getEndDate()->toDateString()); $period = $periodClass::create( $start = new Carbon('2018-04-16'), $interval = new CarbonInterval('P1M'), $end = new Carbon('2018-07-15'), ); $start->subDays(5); $interval->days(15); $end->addDays(5); $this->assertSame('2018-04-16', $period->getStartDate()->toDateString()); $this->assertSame('P1M', $period->getDateInterval()->spec()); $this->assertSame('2018-07-15', $period->getEndDate()->toDateString()); } public function testCreateFromArray() { $periodClass = static::$periodClass; $period = $periodClass::createFromArray([ '2018-03-25', 'P2D', '2018-04-01', $periodClass::EXCLUDE_END_DATE, ]); $this->assertSame('2018-03-25', $period->getStartDate()->toDateString()); $this->assertSame('P2D', $period->getDateInterval()->spec()); $this->assertSame('2018-04-01', $period->getEndDate()->toDateString()); $this->assertPeriodOptions($periodClass::EXCLUDE_END_DATE, $period); } public function testCreateFromIso() { $periodClass = static::$periodClass; $period = $periodClass::createFromIso('R3/2018-03-25/P2D/2018-04-01', $periodClass::EXCLUDE_END_DATE); $this->assertSame('2018-03-25', $period->getStartDate()->toDateString()); $this->assertSame('P2D', $period->getDateInterval()->spec()); $this->assertSame('2018-04-01', $period->getEndDate()->toDateString()); $this->assertSame(3, $period->getRecurrences()); $this->assertPeriodOptions($periodClass::EXCLUDE_END_DATE, $period); } public function testCreateEmpty() { $periodClass = static::$periodClass; $period = new $periodClass(); $this->assertEquals(new Carbon(), $period->getStartDate()); $this->assertSame('P1D', $period->getDateInterval()->spec()); $this->assertNull($period->getEndDate()); $this->assertNull($period->getRecurrences()); $this->assertPeriodOptions(0, $period); } public function testCreateFromDateStringsWithTimezones() { $periodClass = static::$periodClass; $periodClass = \Carbon\CarbonPeriodImmutable::class; $period = $periodClass::create( $start = '2018-03-25 10:15:30 Europe/Oslo', $end = '2018-03-28 17:25:30 Asia/Kamchatka', ); $this->assertSame('2018-03-25 10:15:30 Europe/Oslo', $period->first()->format('Y-m-d H:i:s e')); $this->assertSame('2018-03-27 10:15:30 Europe/Oslo', $period->last()->format('Y-m-d H:i:s e')); $this->assertSame($start, $period->getStartDate()->format('Y-m-d H:i:s e')); $this->assertSame($end, $period->getEndDate()->format('Y-m-d H:i:s e')); $period = $periodClass::create( '2024-01-01', '2024-01-05', \Carbon\CarbonTimeZone::create('Australia/Melbourne'), ); $this->assertSame('Australia/Melbourne', $period->first()->timezone->getName()); $this->assertSame('Australia/Melbourne', $period->last()->timezone->getName()); $this->assertSame('Australia/Melbourne', $period->getStartDate()->timezone->getName()); $this->assertSame('Australia/Melbourne', $period->getEndDate()->timezone->getName()); $this->assertSame('2024-01-01 00:00:00 Australia/Melbourne', $period->first()->format('Y-m-d H:i:s e')); $this->assertSame('2024-01-05 00:00:00 Australia/Melbourne', $period->last()->format('Y-m-d H:i:s e')); $this->assertSame('2024-01-01 00:00:00 Australia/Melbourne', $period->getStartDate()->format('Y-m-d H:i:s e')); $this->assertSame('2024-01-05 00:00:00 Australia/Melbourne', $period->getEndDate()->format('Y-m-d H:i:s e')); $period = $periodClass::create( '2024-01-01', '2024-01-05', 'Australia/Melbourne', ); $this->assertSame('Australia/Melbourne', $period->first()->timezone->getName()); $this->assertSame('Australia/Melbourne', $period->last()->timezone->getName()); $this->assertSame('Australia/Melbourne', $period->getStartDate()->timezone->getName()); $this->assertSame('Australia/Melbourne', $period->getEndDate()->timezone->getName()); $this->assertSame('2024-01-01 00:00:00 Australia/Melbourne', $period->first()->format('Y-m-d H:i:s e')); $this->assertSame('2024-01-05 00:00:00 Australia/Melbourne', $period->last()->format('Y-m-d H:i:s e')); $this->assertSame('2024-01-01 00:00:00 Australia/Melbourne', $period->getStartDate()->format('Y-m-d H:i:s e')); $this->assertSame('2024-01-05 00:00:00 Australia/Melbourne', $period->getEndDate()->format('Y-m-d H:i:s e')); } public function testCreateWithIntervalInFromStringFormat() { $periodClass = static::$periodClass; $period = $periodClass::create( '2018-03-25 12:00', '2 days 10 hours', '2018-04-01 13:30', ); $this->assertSame( $this->standardizeDates(['2018-03-25 12:00', '2018-03-27 22:00', '2018-03-30 08:00']), $this->standardizeDates($period), ); $period = $periodClass::create( '2018-04-21', '3 days', '2018-04-27', ); $this->assertSame( $this->standardizeDates(['2018-04-21 00:00', '2018-04-24 00:00', '2018-04-27 00:00']), $this->standardizeDates($period), ); } public function testCreateFromRelativeDates() { $periodClass = static::$periodClass; $period = $periodClass::create( $start = 'previous friday', $end = '+6 days', ); $this->assertEquals(new Carbon($start), $period->getStartDate()); $this->assertEquals(new Carbon($end), $period->getEndDate()); } public function testCreateFromCarbonInstances() { $date1 = Carbon::parse('2018-06-01'); $date2 = Carbon::parse('2018-06-10'); $period = $date1->toPeriod($date2, 'P1D'); $this->assertSame(24.0, $period->getDateInterval()->totalHours); $this->assertInstanceOf(Carbon::class, $period->getStartDate()); $this->assertSame('2018-06-01', $period->getStartDate()->format('Y-m-d')); $this->assertInstanceOf(Carbon::class, $period->getEndDate()); $this->assertSame('2018-06-10', $period->getEndDate()->format('Y-m-d')); $period = Carbon::create('2019-01-02')->toPeriod(7); $this->assertSame(24.0, $period->getDateInterval()->totalHours); $this->assertInstanceOf(Carbon::class, $period->getStartDate()); $this->assertSame('2019-01-02', $period->getStartDate()->format('Y-m-d')); $this->assertNull($period->getEndDate()); $this->assertSame(7, $period->getRecurrences()); $end = $period->calculateEnd(); $this->assertInstanceOf(Carbon::class, $end); $this->assertSame('2019-01-08', $end->format('Y-m-d')); $period = Carbon::create('2019-01-02')->toPeriod('2019-02-05'); $this->assertNull($period->getRecurrences()); $this->assertSame(24.0, $period->getDateInterval()->totalHours); $this->assertInstanceOf(Carbon::class, $period->getStartDate()); $this->assertSame('2019-01-02', $period->getStartDate()->format('Y-m-d')); $this->assertInstanceOf(Carbon::class, $period->getEndDate()); $this->assertSame('2019-02-05', $period->getEndDate()->format('Y-m-d')); $period = Carbon::create('2019-01-02')->range('2019-02-05'); $this->assertInstanceOf(Carbon::class, $period->getStartDate()); $this->assertSame('2019-01-02', $period->getStartDate()->format('Y-m-d')); $this->assertInstanceOf(Carbon::class, $period->getEndDate()); $this->assertSame('2019-02-05', $period->getEndDate()->format('Y-m-d')); $period = Carbon::create('2019-01-02')->daysUntil('2019-02-05'); $this->assertSame(24.0, $period->getDateInterval()->totalHours); $this->assertInstanceOf(Carbon::class, $period->getStartDate()); $this->assertSame('2019-01-02', $period->getStartDate()->format('Y-m-d')); $this->assertInstanceOf(Carbon::class, $period->getEndDate()); $this->assertSame('2019-02-05', $period->getEndDate()->format('Y-m-d')); $period = CarbonImmutable::create('2019-01-02')->daysUntil('2019-02-05'); $this->assertInstanceOf(CarbonImmutable::class, $period->getStartDate()); $this->assertSame('2019-01-02', $period->getStartDate()->format('Y-m-d')); $this->assertInstanceOf(CarbonImmutable::class, $period->getEndDate()); $this->assertSame('2019-02-05', $period->getEndDate()->format('Y-m-d')); $period = CarbonImmutable::create('2019-01-02')->daysUntil(Carbon::parse('2019-02-05')); $this->assertSame(CarbonImmutable::class, $period->getDateClass()); $this->assertInstanceOf(CarbonImmutable::class, $period->getStartDate()); $this->assertSame('2019-01-02', $period->getStartDate()->format('Y-m-d')); $this->assertInstanceOf(CarbonImmutable::class, $period->getEndDate()); $this->assertSame('2019-02-05', $period->getEndDate()->format('Y-m-d')); $period = Carbon::create('2019-01-02')->hoursUntil('2019-02-05'); $this->assertSame(1.0, $period->getDateInterval()->totalHours); $this->assertSame('1 minute', Carbon::create('2019-01-02')->minutesUntil('2019-02-05')->getDateInterval()->forHumans()); $this->assertSame('3 minutes', Carbon::create('2019-01-02')->minutesUntil('2019-02-05', 3)->getDateInterval()->forHumans()); $this->assertSame('3 seconds', Carbon::create('2019-01-02')->range('2019-02-05', 3, 'seconds')->getDateInterval()->forHumans()); $this->assertSame('1 second', Carbon::create('2019-01-02')->secondsUntil('2019-02-05')->getDateInterval()->forHumans()); $this->assertSame(1.0, Carbon::create('2019-01-02')->millisecondsUntil('2019-02-05')->getDateInterval()->totalMilliseconds); $this->assertSame(1.0, Carbon::create('2019-01-02')->microsecondsUntil('2019-02-05')->getDateInterval()->totalMicroseconds); $this->assertSame('1 week', Carbon::create('2019-01-02')->weeksUntil('2019-02-05')->getDateInterval()->forHumans()); $this->assertSame('1 month', Carbon::create('2019-01-02')->monthsUntil('2019-02-05')->getDateInterval()->forHumans()); $this->assertSame('3 months', Carbon::create('2019-01-02')->quartersUntil('2019-02-05')->getDateInterval()->forHumans()); $this->assertSame('1 year', Carbon::create('2019-01-02')->yearsUntil('2019-02-05')->getDateInterval()->forHumans()); $this->assertSame('10 years', Carbon::create('2019-01-02')->decadesUntil('2019-02-05')->getDateInterval()->forHumans()); $this->assertSame('100 years', Carbon::create('2019-01-02')->centuriesUntil('2019-02-05')->getDateInterval()->forHumans()); $this->assertSame('1000 years', Carbon::create('2019-01-02')->millenniaUntil('2019-02-05')->getDateInterval()->forHumans()); } public function testCreateFromCarbonInstanceInvalidMethod() { $this->expectExceptionObject(new BadMethodCallException( 'Method unknownUnitsUntil does not exist.', )); /** @var object $date */ $date = Carbon::create('2019-01-02'); $date->unknownUnitsUntil('2019-02-05'); } public function testInstance() { $periodClass = static::$periodClass; $source = new DatePeriod( new DateTime('2012-07-01'), CarbonInterval::days(2), new DateTime('2012-07-07'), ); $period = $periodClass::instance($source); $this->assertInstanceOf($periodClass, $period); $this->assertSame('2012-07-01', $period->getStartDate()->format('Y-m-d')); $this->assertSame(2, $period->getDateInterval()->d); $this->assertSame('2012-07-07', $period->getEndDate()->format('Y-m-d')); $period2 = $periodClass::instance($period); $this->assertInstanceOf($periodClass, $period2); $this->assertSame('2012-07-01', $period2->getStartDate()->format('Y-m-d')); $this->assertSame(2, $period2->getDateInterval()->d); $this->assertSame('2012-07-07', $period2->getEndDate()->format('Y-m-d')); $this->assertNotSame($period, $period2); $period3 = new $periodClass($source); $this->assertInstanceOf($periodClass, $period3); $this->assertSame('2012-07-01', $period3->getStartDate()->format('Y-m-d')); $this->assertSame(2, $period3->getDateInterval()->d); $this->assertSame('2012-07-07', $period3->getEndDate()->format('Y-m-d')); $this->assertNotSame($period, $period3); $period4 = new $periodClass($period); $this->assertInstanceOf($periodClass, $period4); $this->assertSame('2012-07-01', $period4->getStartDate()->format('Y-m-d')); $this->assertSame(2, $period4->getDateInterval()->d); $this->assertSame('2012-07-07', $period4->getEndDate()->format('Y-m-d')); $this->assertNotSame($period, $period4); } public function testCreateFromCarbonInstancesNamedParameters() { $periodClass = static::$periodClass; $carbonClass = $periodClass === CarbonPeriodImmutable::class ? CarbonImmutable::class : Carbon::class; $period = $carbonClass::create('2019-01-02')->daysUntil(endDate: '2019-02-05'); $this->assertInstanceOf($periodClass, $period); $this->assertSame('2019-01-02', $period->getStartDate()->format('Y-m-d')); $this->assertSame('2019-02-05', $period->getEndDate()->format('Y-m-d')); $this->assertSame('1 day', (string) $period->getDateInterval()); $period = $carbonClass::create('2019-01-02')->hoursUntil(endDate: '2019-02-05', factor: 12); $this->assertInstanceOf($periodClass, $period); $this->assertSame('2019-01-02', $period->getStartDate()->format('Y-m-d')); $this->assertSame('2019-02-05', $period->getEndDate()->format('Y-m-d')); $this->assertSame('12 hours', (string) $period->getDateInterval()); } public function testCast() { $periodClass = static::$periodClass; $period = $periodClass === CarbonPeriodImmutable::class ? (new class('2012-07-01', CarbonInterval::days(2), '2012-07-07') extends CarbonPeriodImmutable { public function foo() { return $this->getStartDate()->format('j').' '. $this->getDateInterval()->format('%d').' '. $this->getEndDate()->format('j'); } }) : (new class('2012-07-01', CarbonInterval::days(2), '2012-07-07') extends CarbonPeriod { public function foo() { return $this->getStartDate()->format('j').' '. $this->getDateInterval()->format('%d').' '. $this->getEndDate()->format('j'); } }); $subClass = \get_class($period); $this->assertInstanceOf($periodClass, $period); $this->assertNotSame($periodClass, $subClass); $this->assertSame('1 2 7', $period->foo()); /** @var object $period */ $period = $periodClass::create('2010-08-24', CarbonInterval::weeks(2), '2012-07-19') ->cast($subClass); $this->assertInstanceOf($subClass, $period); $this->assertSame('24 14 19', $period->foo()); } public function testBadCast() { $this->expectExceptionObject(new InvalidArgumentException( 'DateTime has not the instance() method needed to cast the date.', )); $periodClass = static::$periodClass; $periodClass::create('2010-08-24', CarbonInterval::weeks(2), '2012-07-19') ->cast(DateTime::class); } public function testMake() { $periodClass = static::$periodClass; $period = $periodClass::make(new DatePeriod( new DateTime('2012-07-01'), CarbonInterval::days(2), new DateTime('2012-07-07'), )); $this->assertInstanceOf($periodClass, $period); $this->assertSame('2012-07-01', $period->getStartDate()->format('Y-m-d')); $this->assertSame(2, $period->getDateInterval()->d); $this->assertSame('2012-07-07', $period->getEndDate()->format('Y-m-d')); $period2 = $periodClass::make($period); $this->assertInstanceOf($periodClass, $period2); $this->assertSame('2012-07-01', $period2->getStartDate()->format('Y-m-d')); $this->assertSame(2, $period2->getDateInterval()->d); $this->assertSame('2012-07-07', $period2->getEndDate()->format('Y-m-d')); $this->assertNotSame($period, $period2); $period2 = $periodClass::make('2012-07-01/P2D/2012-07-07'); $this->assertInstanceOf($periodClass, $period2); $this->assertSame('2012-07-01', $period2->getStartDate()->format('Y-m-d')); $this->assertSame(2, $period2->getDateInterval()->d); $this->assertSame('2012-07-07', $period2->getEndDate()->format('Y-m-d')); } public function testInstanceInvalidType() { $this->expectExceptionObject(new NotAPeriodException( 'Argument 1 passed to '.static::$periodClass.'::instance() '. 'must be an instance of DatePeriod or '.static::$periodClass.', string given.', )); $periodClass = static::$periodClass; $periodClass::instance('hello'); } public function testInstanceInvalidInstance() { $this->expectExceptionObject(new NotAPeriodException( 'Argument 1 passed to '.static::$periodClass.'::instance() '. 'must be an instance of DatePeriod or '.static::$periodClass.', instance of Carbon\Carbon given.', )); $periodClass = static::$periodClass; $periodClass::instance(Carbon::now()); } public function testMutability() { $this->assertSame( [Carbon::class, Carbon::class, Carbon::class], iterator_to_array( CarbonPeriod::between(Carbon::today(), Carbon::today()->addDays(2))->map('get_class'), ), ); $this->assertSame( [Carbon::class, Carbon::class, Carbon::class], iterator_to_array(
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
true
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriod/MacroTest.php
tests/CarbonPeriod/MacroTest.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonPeriod; use BadMethodCallException; use Carbon\Carbon; use Carbon\CarbonPeriod; use Carbon\CarbonPeriodImmutable; use ReflectionClass; use Tests\AbstractTestCase; use Tests\CarbonPeriod\Fixtures\MacroableClass; use Tests\CarbonPeriod\Fixtures\Mixin; use Tests\CarbonPeriod\Fixtures\MixinTrait; class MacroTest extends AbstractTestCase { protected function tearDown(): void { (new ReflectionClass(static::$periodClass)) ->setStaticPropertyValue('macros', []); parent::tearDown(); } public function testCallMacro() { $periodClass = static::$periodClass; $periodClass::macro('onlyWeekdays', function () { /** @var CarbonPeriod $period */ $period = $this; return $period->addFilter(function ($date) { return !\in_array($date->dayOfWeek, [Carbon::SATURDAY, Carbon::SUNDAY], true); }); }); /** @var mixed $period */ $period = $periodClass::create('2018-05-10', '2018-05-14'); $result = $period->onlyWeekdays(); $this->assertSame( $periodClass === CarbonPeriod::class, $period === $result, 'Must be same object if mutable' ); $this->assertSame( $this->standardizeDates(['2018-05-10', '2018-05-11', '2018-05-14']), $this->standardizeDates($result), ); } public function testParameterOtherThanSelfIsNotGivenPeriodInstance() { $periodClass = static::$periodClass; $periodClass::macro('foobar', function ($param = 123) { return $param; }); /** @var mixed $period */ $period = $periodClass::create(); $this->assertSame(123, $period->foobar()); } public function testPassPeriodInstanceAfterOptionalParameters() { $periodClass = static::$periodClass; $periodClass::macro('formatStartDate', function ($format = 'l, j F Y') { /** @var CarbonPeriod $period */ $period = $this; return $period->getStartDate()->format($format); }); /** @var mixed $period */ $period = $periodClass::start('2016-09-11'); $this->assertSame( 'Sunday, 11 September 2016', $period->formatStartDate(), ); } public function testMacroIsBindedToDatePeriodInstance() { $periodClass = static::$periodClass; $periodClass::macro('myself', function () { return $this; }); /** @var mixed $period */ $period = new $periodClass(); $this->assertInstanceOf($periodClass, $period->myself()); $this->assertSame($period, $period->myself()); } public function testCallMacroStatically() { $periodClass = static::$periodClass; $periodClass::macro('countWeekdaysBetween', function ($from, $to) use ($periodClass) { return $periodClass::create($from, $to) ->addFilter(function ($date) { return !\in_array($date->dayOfWeek, [Carbon::SATURDAY, Carbon::SUNDAY], true); }) ->count(); }); $this->assertSame( 3, $periodClass::countWeekdaysBetween('2018-05-10', '2018-05-14'), ); } public function testMacroIsBoundToDatePeriodClass() { $periodClass = static::$periodClass; $periodClass::macro('newMyself', function () { return new static(); }); $this->assertInstanceOf($periodClass, $periodClass::newMyself()); } public function testRegisterNonClosureMacro() { $periodClass = static::$periodClass; $periodClass::macro('lower', 'strtolower'); /** @var mixed $period */ $period = new $periodClass(); $this->assertSame('abc', $period->lower('ABC')); $this->assertSame('abc', $periodClass::lower('ABC')); } public function testRegisterMixin() { $periodClass = static::$periodClass; $periodClass::mixin(new Mixin()); $this->assertNull($periodClass::getFoo()); $periodClass::setFoo('bar'); $this->assertSame('bar', $periodClass::getFoo()); } public function testCallNonExistingMacro() { $this->expectExceptionObject(new BadMethodCallException( 'Method nonExistingMacro does not exist.', )); $periodClass = static::$periodClass; /** @var mixed $period */ $period = $periodClass::create(); $period->nonExistingMacro(); } public function testCallNonExistingMacroStatically() { $this->expectExceptionObject(new BadMethodCallException( 'Method nonExistingMacro does not exist.', )); $periodClass = static::$periodClass; $periodClass::nonExistingMacro(); } public function testOverrideAlias() { $periodClass = static::$periodClass; $periodClass::macro('recurrences', function () { return 'foo'; }); $this->assertSame('foo', $periodClass::recurrences()); } public function testInstantiateViaStaticMacroCall() { $periodClass = static::$periodClass; $periodClass::macro('fromTomorrow', function () { /** @var CarbonPeriod $period */ $period = $this; return $period->setStartDate(Carbon::tomorrow()); }); $period = $periodClass::fromTomorrow(); $this->assertEquals(Carbon::tomorrow(), $period->getStartDate()); } public function testMixinInstance() { require_once __DIR__.'/Fixtures/MixinTrait.php'; require_once __DIR__.'/Fixtures/MacroableClass.php'; $periodClass = static::$periodClass; $periodClass::mixin(MixinTrait::class); $period = $periodClass::create('2023-06-10', '2023-06-12'); $copy = $period->copyOneMoreDay(); $this->assertSame('Every 1 day from 2023-06-10 to 2023-06-12', (string) $period); $this->assertSame('Every 1 day from 2023-06-10 to 2023-06-13', (string) $copy); $mutated = $period->oneMoreDay(); $immutable = (static::$periodClass === CarbonPeriodImmutable::class); $expectedEnd = $immutable ? '2023-06-12' : '2023-06-13'; $this->assertSame('Every 1 day from 2023-06-10 to 2023-06-13', (string) $mutated); $this->assertSame("Every 1 day from 2023-06-10 to $expectedEnd", (string) $period); $expectedResult = $immutable ? 'a new instance' : 'the same instance'; $this->assertSame( $immutable, ($mutated !== $period), "{static::$periodClass}::oneMoreDay() should return $expectedResult" ); $this->assertNotSame($copy, $period); $this->assertSame('2023-06-14', $mutated->endNextDay()->format('Y-m-d')); $this->assertSame(static::$periodClass === CarbonPeriodImmutable::class ? '2023-06-13' : '2023-06-14', $period->endNextDay()->format('Y-m-d')); MacroableClass::mixin(MixinTrait::class); $obj = new MacroableClass(); $result = $obj ->setEndDate(Carbon::parse('2023-06-01')) ->oneMoreDay(); $endDate = $result->getEndDate(); $this->assertInstanceOf(MacroableClass::class, $result); $this->assertNotSame(MacroableClass::class, \get_class($result)); $this->assertSame(Carbon::class, \get_class($endDate)); $this->assertSame('2023-06-02', $endDate->format('Y-m-d')); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriod/ToDatePeriodTest.php
tests/CarbonPeriod/ToDatePeriodTest.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonPeriod; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterval; use Carbon\Translator; use DatePeriod; use DateTime; use DateTimeImmutable; use ReflectionMethod; use Tests\AbstractTestCase; class ToDatePeriodTest extends AbstractTestCase { public function testToArrayIsNotEmptyArray() { $periodClass = static::$periodClass; $period = $periodClass::create('2021-01-05', '2021-02-15'); $result = $period->toDatePeriod(); $this->assertFalse($period->isEndExcluded()); $this->assertSame(DatePeriod::class, \get_class($result)); $this->assertSame('2021-01-05', $result->getStartDate()->format('Y-m-d')); $this->assertSame('2021-02-15', $result->getEndDate()->format('Y-m-d')); // CarbonPeriod includes end date by default while DatePeriod will always exclude it $dates = iterator_to_array($result); $this->assertSame('2021-02-14', end($dates)->format('Y-m-d')); $this->assertTrue($period->equalTo($periodClass::instance($result))); $period = $periodClass::create('2021-01-05', '2021-02-15', $periodClass::EXCLUDE_END_DATE); $result = $period->toDatePeriod(); $newInstance = $periodClass::instance($result); $this->assertTrue($period->isEndExcluded()); $this->assertSame(DatePeriod::class, \get_class($result)); $this->assertSame('2021-01-05', $result->getStartDate()->format('Y-m-d')); $this->assertSame('2021-02-14', $result->getEndDate()->format('Y-m-d')); $dates = iterator_to_array($result); $this->assertSame('2021-02-13', end($dates)->format('Y-m-d')); $this->assertSame('2021-01-05', $newInstance->getStartDate()->format('Y-m-d')); $this->assertSame('2021-02-14', $newInstance->getEndDate()->format('Y-m-d')); $period = $periodClass::create('2021-01-05', 3); $result = $period->toDatePeriod(); $newInstance = $periodClass::instance($result); $this->assertSame(DatePeriod::class, \get_class($result)); $this->assertSame('2021-01-05', $result->getStartDate()->format('Y-m-d')); $this->assertNull($result->getEndDate()); $dates = iterator_to_array($result); $this->assertSame('2021-01-08', end($dates)->format('Y-m-d')); $this->assertSame('2021-01-05', $newInstance->getStartDate()->format('Y-m-d')); $this->assertSame(3, $newInstance->getRecurrences()); } public function testWithIntervalLocalized() { CarbonInterval::setLocale('fr'); $periodClass = static::$periodClass; $period = $periodClass::create('2021-01-05', 3); $result = $period->floor()->toDatePeriod(); $this->assertSame(DatePeriod::class, \get_class($result)); $this->assertSame('2021-01-05', $result->getStartDate()->format('Y-m-d')); $this->assertNull($result->getEndDate()); if (method_exists($result, 'getRecurrences')) { $this->assertSame(3, $result->getRecurrences()); } CarbonInterval::setLocale('en'); } public function testWithModifiedEnglish() { $periodClass = static::$periodClass; $translator = Translator::get('en'); $translator->setTranslations([ 'day' => ':count boring day|:count boring days', ]); $period = $periodClass::create('2021-01-05', 3); $result = $period->floor()->toDatePeriod(); $this->assertSame(DatePeriod::class, \get_class($result)); $this->assertSame('2021-01-05', $result->getStartDate()->format('Y-m-d')); $this->assertNull($result->getEndDate()); if (method_exists($result, 'getRecurrences')) { $this->assertSame(3, $result->getRecurrences()); } $translator->resetMessages(); } public function testRawDate() { $periodClass = static::$periodClass; $period = new $periodClass(); $method = new ReflectionMethod($periodClass, 'rawDate'); $this->assertNull($method->invoke($period, false)); $this->assertNull($method->invoke($period, null)); $date = new DateTime(); $this->assertSame($date, $method->invoke($period, $date)); $date = new DateTimeImmutable(); $this->assertSame($date, $method->invoke($period, $date)); $date = new Carbon(); $raw = $method->invoke($period, $date); $this->assertInstanceOf(DateTime::class, $raw); $this->assertEquals($date, $raw); $date = new CarbonImmutable(); $raw = $method->invoke($period, $date); $this->assertInstanceOf(DateTimeImmutable::class, $raw); $this->assertEquals($date, $raw); $date = new class() extends DateTime { // void }; $raw = $method->invoke($period, $date); $this->assertInstanceOf(DateTime::class, $raw); $this->assertEquals($date, $raw); $date = new class() extends DateTimeImmutable { // void }; $raw = $method->invoke($period, $date); $this->assertInstanceOf(DateTimeImmutable::class, $raw); $this->assertEquals($date, $raw); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriod/RoundingTest.php
tests/CarbonPeriod/RoundingTest.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonPeriod; use Carbon\CarbonInterval; use InvalidArgumentException; use Tests\AbstractTestCase; class RoundingTest extends AbstractTestCase { public function testThrowsExceptionForCompositeInterval() { $this->expectExceptionObject(new InvalidArgumentException( 'Rounding is only possible with single unit intervals.', )); $periodClass = static::$periodClass; $periodClass::days(2)->round('2 hours 50 minutes'); } public function testFloor() { $periodClass = static::$periodClass; $period = $periodClass::create('2019-02-01 12:52:23', '2019-12-12 03:12:44.817')->floor(); $this->assertSame('01 00:00:00.000000', $period->getDateInterval()->format('%D %H:%I:%S.%F')); $this->assertSame('2019-02-01 00:00:00.000000', $period->getStartDate()->format('Y-m-d H:i:s.u')); $this->assertSame('2019-12-12 00:00:00.000000', $period->getEndDate()->format('Y-m-d H:i:s.u')); $period = $periodClass::create('2019-02-01 12:52:23', '2019-12-12 03:12:44.817', '1 hour')->floor(); $this->assertSame('2019-02-01 12:00:00.000000', $period->getStartDate()->format('Y-m-d H:i:s.u')); $this->assertSame('2019-12-12 03:00:00.000000', $period->getEndDate()->format('Y-m-d H:i:s.u')); $period = $periodClass::create('2019-02-01 12:52:23', '2019-12-12 03:12:44.817', '2 hours')->floor(); $this->assertSame('2019-02-01 12:00:00.000000', $period->getStartDate()->format('Y-m-d H:i:s.u')); $this->assertSame('2019-12-12 02:00:00.000000', $period->getEndDate()->format('Y-m-d H:i:s.u')); $period = $periodClass::create('2019-02-01 12:52:23', '2019-12-12 03:12:44.817')->floor('hour'); $this->assertSame('01 00:00:00.000000', $period->getDateInterval()->format('%D %H:%I:%S.%F')); $this->assertSame('2019-02-01 12:00:00.000000', $period->getStartDate()->format('Y-m-d H:i:s.u')); $this->assertSame('2019-12-12 03:00:00.000000', $period->getEndDate()->format('Y-m-d H:i:s.u')); $period = $periodClass::create('2019-02-01 12:52:23', '2019-12-12 03:12:44.817', '140 minutes')->floor('hour'); $this->assertSame('00 02:00:00.000000', $period->getDateInterval()->format('%D %H:%I:%S.%F')); $this->assertSame('2019-02-01 12:00:00.000000', $period->getStartDate()->format('Y-m-d H:i:s.u')); $this->assertSame('2019-12-12 03:00:00.000000', $period->getEndDate()->format('Y-m-d H:i:s.u')); $period = $periodClass::create('2019-02-01 12:52:23', '2019-12-12 03:12:44.817', '1 hour')->floor(CarbonInterval::minutes(15)); $this->assertSame('2019-02-01 12:45:00.000000', $period->getStartDate()->format('Y-m-d H:i:s.u')); $this->assertSame('2019-12-12 03:00:00.000000', $period->getEndDate()->format('Y-m-d H:i:s.u')); $period = $periodClass::create('2019-02-01 12:52:23', '2019-12-12 03:12:44.817', '2 hours')->floorUnit('minute', 10); $this->assertSame('2019-02-01 12:50:00.000000', $period->getStartDate()->format('Y-m-d H:i:s.u')); $this->assertSame('2019-12-12 03:10:00.000000', $period->getEndDate()->format('Y-m-d H:i:s.u')); $period = $periodClass::create('2019-02-01 12:52:23', '2019-12-12 03:12:44.817', '2 hours')->floorMinutes(10); $this->assertSame('2019-02-01 12:50:00.000000', $period->getStartDate()->format('Y-m-d H:i:s.u')); $this->assertSame('2019-12-12 03:10:00.000000', $period->getEndDate()->format('Y-m-d H:i:s.u')); } public function testCeil() { $periodClass = static::$periodClass; $period = $periodClass::create('2019-02-01 12:52:23', '2019-12-12 03:12:44.817')->ceil(); $this->assertSame('01 00:00:00.000000', $period->getDateInterval()->format('%D %H:%I:%S.%F')); $this->assertSame('2019-02-02 00:00:00.000000', $period->getStartDate()->format('Y-m-d H:i:s.u')); $this->assertSame('2019-12-13 00:00:00.000000', $period->getEndDate()->format('Y-m-d H:i:s.u')); $period = $periodClass::create('2019-02-01 12:52:23', '2019-12-12 03:12:44.817', '1 hour')->ceil(); $this->assertSame('2019-02-01 13:00:00.000000', $period->getStartDate()->format('Y-m-d H:i:s.u')); $this->assertSame('2019-12-12 04:00:00.000000', $period->getEndDate()->format('Y-m-d H:i:s.u')); $period = $periodClass::create('2019-02-01 12:52:23', '2019-12-12 03:12:44.817', '2 hours')->ceil(); $this->assertSame('2019-02-01 14:00:00.000000', $period->getStartDate()->format('Y-m-d H:i:s.u')); $this->assertSame('2019-12-12 04:00:00.000000', $period->getEndDate()->format('Y-m-d H:i:s.u')); $period = $periodClass::create('2019-02-01 12:52:23', '2019-12-12 03:12:44.817')->ceil('hour'); $this->assertSame('01 00:00:00.000000', $period->getDateInterval()->format('%D %H:%I:%S.%F')); $this->assertSame('2019-02-01 13:00:00.000000', $period->getStartDate()->format('Y-m-d H:i:s.u')); $this->assertSame('2019-12-12 04:00:00.000000', $period->getEndDate()->format('Y-m-d H:i:s.u')); $period = $periodClass::create('2019-02-01 12:52:23', '2019-12-12 03:12:44.817', '140 minutes')->ceil('hour'); $this->assertSame('00 03:00:00.000000', $period->getDateInterval()->format('%D %H:%I:%S.%F')); $this->assertSame('2019-02-01 13:00:00.000000', $period->getStartDate()->format('Y-m-d H:i:s.u')); $this->assertSame('2019-12-12 04:00:00.000000', $period->getEndDate()->format('Y-m-d H:i:s.u')); $period = $periodClass::create('2019-02-01 12:52:23', '2019-12-12 03:12:44.817', '1 hour')->ceil(CarbonInterval::minutes(15)); $this->assertSame('2019-02-01 13:00:00.000000', $period->getStartDate()->format('Y-m-d H:i:s.u')); $this->assertSame('2019-12-12 03:15:00.000000', $period->getEndDate()->format('Y-m-d H:i:s.u')); $period = $periodClass::create('2019-02-01 12:52:23', '2019-12-12 03:12:44.817', '2 hours')->ceilUnit('minute', 10); $this->assertSame('2019-02-01 13:00:00.000000', $period->getStartDate()->format('Y-m-d H:i:s.u')); $this->assertSame('2019-12-12 03:20:00.000000', $period->getEndDate()->format('Y-m-d H:i:s.u')); $period = $periodClass::create('2019-02-01 12:52:23', '2019-12-12 03:12:44.817', '2 hours')->ceilMinutes(10); $this->assertSame('2019-02-01 13:00:00.000000', $period->getStartDate()->format('Y-m-d H:i:s.u')); $this->assertSame('2019-12-12 03:20:00.000000', $period->getEndDate()->format('Y-m-d H:i:s.u')); } public function testRound() { $periodClass = static::$periodClass; $period = $periodClass::create('2019-02-01 12:52:23', '2019-12-12 03:12:44.817')->round(); $this->assertSame('01 00:00:00.000000', $period->getDateInterval()->format('%D %H:%I:%S.%F')); $this->assertSame('2019-02-02 00:00:00.000000', $period->getStartDate()->format('Y-m-d H:i:s.u')); $this->assertSame('2019-12-12 00:00:00.000000', $period->getEndDate()->format('Y-m-d H:i:s.u')); $period = $periodClass::create('2019-02-01 12:52:23', '2019-12-12 03:12:44.817', '1 hour')->round(); $this->assertSame('2019-02-01 13:00:00.000000', $period->getStartDate()->format('Y-m-d H:i:s.u')); $this->assertSame('2019-12-12 03:00:00.000000', $period->getEndDate()->format('Y-m-d H:i:s.u')); $period = $periodClass::create('2019-02-01 12:52:23', '2019-12-12 03:12:44.817', '2 hours')->round(); $this->assertSame('2019-02-01 12:00:00.000000', $period->getStartDate()->format('Y-m-d H:i:s.u')); $this->assertSame('2019-12-12 04:00:00.000000', $period->getEndDate()->format('Y-m-d H:i:s.u')); $period = $periodClass::create('2019-02-01 12:52:23', '2019-12-12 03:12:44.817')->round('hour'); $this->assertSame('01 00:00:00.000000', $period->getDateInterval()->format('%D %H:%I:%S.%F')); $this->assertSame('2019-02-01 13:00:00.000000', $period->getStartDate()->format('Y-m-d H:i:s.u')); $this->assertSame('2019-12-12 03:00:00.000000', $period->getEndDate()->format('Y-m-d H:i:s.u')); $period = $periodClass::create('2019-02-01 12:52:23', '2019-12-12 03:12:44.817', '140 minutes')->round('hour'); $this->assertSame('00 02:00:00.000000', $period->getDateInterval()->format('%D %H:%I:%S.%F')); $this->assertSame('2019-02-01 13:00:00.000000', $period->getStartDate()->format('Y-m-d H:i:s.u')); $this->assertSame('2019-12-12 03:00:00.000000', $period->getEndDate()->format('Y-m-d H:i:s.u')); $period = $periodClass::create('2019-02-01 12:52:23', '2019-12-12 03:12:44.817', '1 hour')->round(CarbonInterval::minutes(15)); $this->assertSame('2019-02-01 12:45:00.000000', $period->getStartDate()->format('Y-m-d H:i:s.u')); $this->assertSame('2019-12-12 03:15:00.000000', $period->getEndDate()->format('Y-m-d H:i:s.u')); $period = $periodClass::create('2019-02-01 12:52:23', '2019-12-12 03:12:44.817', '2 hours')->roundUnit('minute', 10); $this->assertSame('2019-02-01 12:50:00.000000', $period->getStartDate()->format('Y-m-d H:i:s.u')); $this->assertSame('2019-12-12 03:10:00.000000', $period->getEndDate()->format('Y-m-d H:i:s.u')); $period = $periodClass::create('2019-02-01 12:52:23', '2019-12-12 03:12:44.817', '2 hours')->roundMinutes(10); $this->assertSame('2019-02-01 12:50:00.000000', $period->getStartDate()->format('Y-m-d H:i:s.u')); $this->assertSame('2019-12-12 03:10:00.000000', $period->getEndDate()->format('Y-m-d H:i:s.u')); } public function testRoundCalculatedEnd() { $periodClass = static::$periodClass; $period = $periodClass::create('2019-02-01 12:52:23.123456', '3 hours')->setRecurrences(3); $this->assertSame('2019-02-01 18:00:00.000000', $period->calculateEnd('round')->format('Y-m-d H:i:s.u')); $this->assertSame('2019-02-01 18:52:23.123456', $period->calculateEnd()->format('Y-m-d H:i:s.u')); $period = $periodClass::create('2019-02-01 12:52:23.123456', '3 hours') ->setRecurrences(3) ->addFilter(function ($date) { return $date->hour % 2; }); $this->assertSame('2019-02-02 03:00:00.000000', $period->calculateEnd('round')->format('Y-m-d H:i:s.u')); $this->assertSame('2019-02-02 03:52:23.123456', $period->calculateEnd()->format('Y-m-d H:i:s.u')); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriod/ToStringTest.php
tests/CarbonPeriod/ToStringTest.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonPeriod; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterval; use Carbon\CarbonPeriod; use PHPUnit\Framework\Attributes\DataProvider; use Tests\AbstractTestCase; class ToStringTest extends AbstractTestCase { #[DataProvider('dataForToString')] public function testToString($period, $expected) { Carbon::setLocale('en'); Carbon::setTestNowAndTimezone(new Carbon('2015-09-01', 'America/Toronto')); $this->assertSame( $expected, $period->toString(), ); } public static function dataForToString(): array { $periodClass = static::$periodClass; Carbon::setTestNowAndTimezone(new Carbon('2015-09-01', 'America/Toronto')); $set = [ [ $periodClass::create('R4/2012-07-01T12:00:00/P7D'), '4 times every 1 week from 2012-07-01 12:00:00', ], [ $periodClass::create( Carbon::parse('2015-09-30'), Carbon::parse('2015-10-03'), ), 'Every 1 day from 2015-09-30 to 2015-10-03', ], [ $periodClass::create( Carbon::parse('2015-09-30 12:50'), CarbonInterval::days(3)->hours(5), Carbon::parse('2015-10-03 19:00'), ), 'Every 3 days and 5 hours from 2015-09-30 12:50:00 to 2015-10-03 19:00:00', ], [ $periodClass::create('2015-09-30 17:30'), 'Every 1 day from 2015-09-30 17:30:00', ], [ $periodClass::create('P1M14D'), 'Every 1 month and 2 weeks from 2015-09-01', ], [ $periodClass::create('2015-09-30 13:30', 'P17D')->setRecurrences(1), 'Once every 2 weeks and 3 days from 2015-09-30 13:30:00', ], [ $periodClass::create('2015-10-01', '2015-10-05', 'PT30M'), 'Every 30 minutes from 2015-10-01 to 2015-10-05', ], ]; Carbon::setTestNowAndTimezone(); return array_combine( array_column($set, 1), $set, ); } public function testMagicToString() { $periodClass = static::$periodClass; $period = $periodClass::create( Carbon::parse('2015-09-30 12:50'), CarbonInterval::days(3)->hours(5), Carbon::parse('2015-10-03 19:00'), ); $this->assertSame( 'Every 3 days and 5 hours from 2015-09-30 12:50:00 to 2015-10-03 19:00:00', (string) $period, ); } #[DataProvider('dataForToIso8601String')] public function testToIso8601String($period, $expected) { Carbon::setTestNowAndTimezone(new Carbon('2015-09-01', 'America/Toronto')); $this->assertSame( $expected, $period->toIso8601String(), ); } public static function dataForToIso8601String(): array { $periodClass = static::$periodClass; Carbon::setTestNowAndTimezone(new Carbon('2015-09-01', 'America/Toronto')); $set = [ [ $periodClass::create('R4/2012-07-01T00:00:00-04:00/P7D'), 'R4/2012-07-01T00:00:00-04:00/P7D', ], [ $periodClass::create( Carbon::parse('2015-09-30', 'America/Toronto'), CarbonInterval::day(), Carbon::parse('2015-10-03', 'America/Toronto'), ), '2015-09-30T00:00:00-04:00/P1D/2015-10-03T00:00:00-04:00', ], [ $periodClass::createFromIso( '2015-09-30T00:00:00-04:00/P1D/2015-10-03T00:00:00-04:00' ), '2015-09-30T00:00:00-04:00/P1D/2015-10-03T00:00:00-04:00', ], [ $periodClass::createFromIso( '2015-09-30T00:00:00-04:00/2015-10-03T00:00:00-04:00', ), '2015-09-30T00:00:00-04:00/2015-10-03T00:00:00-04:00', ], [ $periodClass::create( Carbon::parse('2015-09-30', 'America/Toronto'), Carbon::parse('2015-10-03', 'America/Toronto'), ), '2015-09-30T00:00:00-04:00/2015-10-03T00:00:00-04:00', ], [ $periodClass::create( Carbon::parse('2015-09-30', 'America/Toronto'), CarbonInterval::day(), Carbon::parse('2015-10-03', 'America/Toronto'), )->resetDateInterval(), '2015-09-30T00:00:00-04:00/2015-10-03T00:00:00-04:00', ], [ $periodClass::create( Carbon::parse('2015-09-30 12:50', 'America/Toronto'), CarbonInterval::days(3)->hours(5), Carbon::parse('2015-10-03 19:00', 'America/Toronto'), ), '2015-09-30T12:50:00-04:00/P3DT5H/2015-10-03T19:00:00-04:00', ], [ $periodClass::create( Carbon::parse('2015-09-30 12:50', 'America/Toronto'), CarbonInterval::days(3), ), '2015-09-30T12:50:00-04:00/P3D', ], [ $periodClass::create('1 day'), '2015-09-01T00:00:00-04:00/P1D', ], [ $periodClass::create(), '2015-09-01T00:00:00-04:00', ], ]; Carbon::setTestNowAndTimezone(); return array_combine( array_column($set, 1), $set, ); } public function testSpec() { $periodClass = static::$periodClass; $period = $periodClass::create( Carbon::parse('2015-09-30'), CarbonInterval::days(3)->hours(5), Carbon::parse('2015-10-03'), ); $this->assertSame( '2015-09-30T00:00:00-04:00/P3DT5H/2015-10-03T00:00:00-04:00', $period->spec(), ); } public function testStartOfWeekForPeriod() { $periodClass = static::$periodClass; $sunday = CarbonImmutable::parse('2019-12-01'); $period = $periodClass::create($sunday->startOfWeek(), '1 week', $sunday->endOfWeek())->toArray(); $formattedSunday = $sunday->startOfWeek()->format('Y-m-d H:i:s'); $this->assertSame( '2019-11-25 00:00:00', $formattedSunday, ); $this->assertSame( $formattedSunday, $period[0]->toImmutable()->startOfWeek()->format('Y-m-d H:i:s'), ); } public function testToStringCustomization() { $periodClass = static::$periodClass; $sunday = CarbonImmutable::parse('2019-12-01'); $period = $periodClass::create($sunday->startOfWeek(), '1 week', $sunday->endOfWeek()); $this->assertSame( 'Every 1 week from 2019-11-25 00:00:00 to 2019-12-01 23:59:59!!', $period.'!!' ); $periodClass::setToStringFormat('m/d'); $this->assertSame( 'Every 1 week from 11/25 to 12/01!!', $period.'!!' ); $period->settings(['toStringFormat' => static function (CarbonPeriod $period) { return $period->toIso8601String(); }]); $this->assertSame( '2019-11-25T00:00:00-05:00/P7D/2019-12-01T23:59:59-05:00!!', $period.'!!' ); $periodClass::resetToStringFormat(); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriod/DynamicIntervalTest.php
tests/CarbonPeriod/DynamicIntervalTest.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonPeriod; use Carbon\Carbon; use Tests\AbstractTestCase; class DynamicIntervalTest extends AbstractTestCase { public function testDynamicIntervalInPeriod() { $periodClass = static::$periodClass; $weekDayStep = function (Carbon $date, bool $negated = false): Carbon { if ($negated) { return $date->previousWeekDay(); } return $date->nextWeekDay(); }; $period = $periodClass::create('2020-06-01', $weekDayStep, '2020-06-14'); $dates = []; foreach ($period as $date) { $dates[] = $date->day; } $this->assertCount(10, $period); $this->assertSame(array_merge(range(1, 5), range(8, 12)), $dates); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriod/SettersTest.php
tests/CarbonPeriod/SettersTest.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonPeriod; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterval; use DateInterval; use DateTime; use InvalidArgumentException; use Tests\AbstractTestCase; use Tests\CarbonPeriod\Fixtures\AbstractCarbon; class SettersTest extends AbstractTestCase { public function testSetStartDate() { $periodClass = static::$periodClass; $period = new $periodClass(); $period = $period->setStartDate('2018-03-25'); $this->assertSame('2018-03-25', $period->getStartDate()->toDateString()); } public function testSetEndDate() { $periodClass = static::$periodClass; $period = new $periodClass(); $period = $period->setEndDate('2018-04-25'); $this->assertSame('2018-04-25', $period->getEndDate()->toDateString()); } public function testSetDateInterval() { $periodClass = static::$periodClass; $period = new $periodClass(); $period = $period->setDateInterval('P3D'); $this->assertSame('P3D', $period->getDateInterval()->spec()); } public function testSetDateIntervalFromStringFormat() { $periodClass = static::$periodClass; $period = new $periodClass(); $period = $period->setDateInterval('1w 3d 4h 32m 23s'); $this->assertSame('P10DT4H32M23S', $period->getDateInterval()->spec()); } public function testSetRecurrences() { $periodClass = static::$periodClass; $period = new $periodClass(); $period = $period->setRecurrences(5); $this->assertSame(5, $period->getRecurrences()); } public function testSetDates() { $periodClass = static::$periodClass; $period = new $periodClass(); $period = $period->setDates('2019-04-12', '2019-04-19'); $this->assertSame('2019-04-12', $period->getStartDate()->toDateString()); $this->assertSame('2019-04-19', $period->getEndDate()->toDateString()); } public function testSetOptions() { $periodClass = static::$periodClass; $period = new $periodClass(); $period = $period->setOptions($options = $periodClass::EXCLUDE_START_DATE | $periodClass::EXCLUDE_END_DATE); $this->assertSame($options, $period->getOptions()); } public function testSetDateClass() { $periodClass = static::$periodClass; $period = new $periodClass('2001-01-01', '2001-01-02'); $period = $period->setDateClass(CarbonImmutable::class); $this->assertSame($periodClass::IMMUTABLE, $period->getOptions()); $this->assertInstanceOf(CarbonImmutable::class, $period->toArray()[0]); $period = $period->setDateClass(Carbon::class); $this->assertSame(0, $period->getOptions()); $this->assertInstanceOf(Carbon::class, $period->toArray()[0]); $period = $period->toggleOptions($periodClass::IMMUTABLE, true); $this->assertSame(CarbonImmutable::class, $period->getDateClass()); $this->assertInstanceOf(CarbonImmutable::class, $period->toArray()[0]); $period = $period->toggleOptions($periodClass::IMMUTABLE, false); $this->assertSame(Carbon::class, $period->getDateClass()); $this->assertInstanceOf(Carbon::class, $period->toArray()[0]); if (PHP_VERSION < 8.4) { $period = $period->setDateClass(AbstractCarbon::class); $this->assertSame(AbstractCarbon::class, $period->getDateClass()); } } public function testSetDateClassInvalidArgumentException() { $this->expectExceptionObject(new InvalidArgumentException( 'Given class does not implement Carbon\CarbonInterface: Carbon\CarbonInterval', )); $periodClass = static::$periodClass; $period = new $periodClass('2001-01-01', '2001-01-02'); $period->setDateClass(CarbonInterval::class); } public function testInvalidInterval() { $this->expectExceptionObject(new InvalidArgumentException( 'Invalid interval.', )); $periodClass = static::$periodClass; $periodClass::create()->setDateInterval(new DateTime()); } public function testEmptyInterval() { $this->expectExceptionObject(new InvalidArgumentException( 'Empty interval is not accepted.', )); $periodClass = static::$periodClass; $periodClass::create()->setDateInterval(new DateInterval('P0D')); } public function testInvalidNegativeNumberOfRecurrences() { $this->expectExceptionObject(new InvalidArgumentException( 'Invalid number of recurrences.', )); $periodClass = static::$periodClass; $periodClass::create()->setRecurrences(-4); } public function testInvalidConstructorParameters() { $this->expectExceptionObject(new InvalidArgumentException( 'Invalid constructor parameters.', )); $periodClass = static::$periodClass; $periodClass::create([]); } public function testInvalidStartDate() { $this->expectExceptionObject(new InvalidArgumentException( 'Invalid start date.', )); $periodClass = static::$periodClass; $periodClass::create()->setStartDate(new DateInterval('P1D')); } public function testInvalidEndDate() { $this->expectExceptionObject(new InvalidArgumentException( 'Invalid end date.', )); $periodClass = static::$periodClass; $periodClass::create()->setEndDate(new DateInterval('P1D')); } public function testToggleOptions() { $periodClass = static::$periodClass; $start = $periodClass::EXCLUDE_START_DATE; $end = $periodClass::EXCLUDE_END_DATE; $period = new $periodClass(); $period = $period->toggleOptions($start, true); $this->assertPeriodOptions($start, $period); $period = $period->toggleOptions($end, true); $this->assertPeriodOptions($start | $end, $period); $period = $period->toggleOptions($start, false); $this->assertPeriodOptions($end, $period); $period = $period->toggleOptions($end, false); $this->assertPeriodOptions(0, $period); } public function testToggleOptionsOnAndOff() { $periodClass = static::$periodClass; $start = $periodClass::EXCLUDE_START_DATE; $end = $periodClass::EXCLUDE_END_DATE; $period = new $periodClass(); $period = $period->toggleOptions($start); $this->assertPeriodOptions($start, $period); $period = $period->toggleOptions($start); $this->assertPeriodOptions(0, $period); $period = $period->setOptions($start); $period = $period->toggleOptions($start | $end); $this->assertSame($start | $end, $period->getOptions()); $period = $period->toggleOptions($end); $this->assertSame($start, $period->getOptions()); $period = $period->toggleOptions($end); $this->assertSame($start | $end, $period->getOptions()); $period = $period->toggleOptions($start | $end); $this->assertSame(0, $period->getOptions()); } public function testSetStartDateInclusiveOrExclusive() { $periodClass = static::$periodClass; $period = new $periodClass(); $period = $period->setStartDate('2018-03-25'); $this->assertFalse($period->isStartExcluded()); $period = $period->setStartDate('2018-03-25', false); $this->assertTrue($period->isStartExcluded()); $period = $period->setStartDate('2018-03-25', true); $this->assertFalse($period->isStartExcluded()); } public function testSetEndDateInclusiveOrExclusive() { $periodClass = static::$periodClass; $period = new $periodClass(); $period = $period->setEndDate('2018-04-25'); $this->assertFalse($period->isEndExcluded()); $period = $period->setEndDate('2018-04-25', false); $this->assertTrue($period->isEndExcluded()); $period = $period->setEndDate('2018-04-25', true); $this->assertFalse($period->isEndExcluded()); } public function testInvertDateInterval() { $periodClass = static::$periodClass; $period = new $periodClass(); $period = $period->invertDateInterval(); $this->assertSame(1, $period->getDateInterval()->invert); $period = $period->invertDateInterval(); $this->assertSame(0, $period->getDateInterval()->invert); $period = $periodClass::create('2018-04-29', 7); $dates = []; foreach ($period as $key => $date) { if ($key === 3) { $period->invert()->start($date); } $dates[] = $date->format('m-d'); } $this->assertSame([ '04-29', '04-30', '05-01', '05-02', '05-01', '04-30', '04-29', ], $dates); } public function testExcludeStartDate() { $periodClass = static::$periodClass; $period = new $periodClass(); $period = $period->excludeStartDate(); $this->assertPeriodOptions($periodClass::EXCLUDE_START_DATE, $period); $period = $period->excludeStartDate(true); $this->assertPeriodOptions($periodClass::EXCLUDE_START_DATE, $period); $period = $period->excludeStartDate(false); $this->assertPeriodOptions(0, $period); } public function testExcludeEndDate() { $periodClass = static::$periodClass; $period = new $periodClass(); $period = $period->excludeEndDate(); $this->assertPeriodOptions($periodClass::EXCLUDE_END_DATE, $period); $period = $period->excludeEndDate(true); $this->assertPeriodOptions($periodClass::EXCLUDE_END_DATE, $period); $period = $period->excludeEndDate(false); $this->assertPeriodOptions(0, $period); } public function testSetRelativeDates() { $periodClass = static::$periodClass; $period = new $periodClass(); $period = $period->setDates('first monday of may 2018', 'last day of may 2018 noon'); $this->assertSame('2018-05-07 00:00:00', $period->getStartDate()->toDateTimeString()); $this->assertSame('2018-05-31 12:00:00', $period->getEndDate()->toDateTimeString()); } public function testFluentSetters() { $periodClass = static::$periodClass; Carbon::setTestNowAndTimezone(Carbon::now('UTC')); $period = CarbonInterval::days(3)->toPeriod()->since('2018-04-21')->until('2018-04-27'); $dates = []; foreach ($period as $date) { $dates[] = $date->format('m-d'); } $this->assertSame(['04-21', '04-24', '04-27'], $dates); $period = CarbonInterval::days(3)->toPeriod('2018-04-21', '2018-04-27'); $dates = []; foreach ($period as $date) { $dates[] = $date->format('m-d'); } $this->assertSame(['04-21', '04-24', '04-27'], $dates); $someDateTime = new DateTime('2010-05-06 02:00:00'); $someCarbon = new Carbon('2010-05-06 13:00:00'); $period = $periodClass::every('2 hours')->between($someDateTime, $someCarbon)->options($periodClass::EXCLUDE_START_DATE); $hours = []; foreach ($period as $date) { $hours[] = $date->format('H'); } $this->assertSame(['04', '06', '08', '10', '12'], $hours); $period = $periodClass::options($periodClass::EXCLUDE_START_DATE)->stepBy(CarbonInterval::hours(2))->since('yesterday 19:00')->until('tomorrow 03:30'); $hours = []; foreach ($period as $date) { $hours[] = $date->format('j H'); } $d1 = Carbon::yesterday()->day; $d2 = Carbon::today()->day; $d3 = Carbon::tomorrow()->day; $this->assertSame([ "$d1 21", "$d1 23", "$d2 01", "$d2 03", "$d2 05", "$d2 07", "$d2 09", "$d2 11", "$d2 13", "$d2 15", "$d2 17", "$d2 19", "$d2 21", "$d2 23", "$d3 01", "$d3 03", ], $hours); $period = $periodClass::between('first day of january this year', 'first day of next month')->interval('1 week'); $this->assertEquals(new Carbon('first day of january this year'), $period->getStartDate()); $this->assertEquals(new Carbon('first day of next month'), $period->getEndDate()); $this->assertSame('1 week', $period->getDateInterval()->forHumans()); $opt = $periodClass::EXCLUDE_START_DATE; $int = '20 days'; $start = '2000-01-03'; $end = '2000-03-15'; $inclusive = false; $period = $periodClass::options($opt)->setDateInterval($int)->setStartDate($start, $inclusive)->setEndDate($end, $inclusive); $this->assertSame($start, $period->getStartDate()->format('Y-m-d')); $this->assertSame($end, $period->getEndDate()->format('Y-m-d')); $this->assertSame(20, $period->getDateInterval()->dayz); $this->assertSame($periodClass::EXCLUDE_START_DATE | $periodClass::EXCLUDE_END_DATE, $period->getOptions()); $inclusive = true; $period = $periodClass::options($opt)->setDateInterval($int)->setStartDate($start, $inclusive)->setEndDate($end, $inclusive); $this->assertSame($start, $period->getStartDate()->format('Y-m-d')); $this->assertSame($end, $period->getEndDate()->format('Y-m-d')); $this->assertSame(20, $period->getDateInterval()->dayz); $this->assertSame(0, $period->getOptions()); $period = $periodClass::options($opt)->setDateInterval($int)->setDates($start, $end); $this->assertSame($start, $period->getStartDate()->format('Y-m-d')); $this->assertSame($end, $period->getEndDate()->format('Y-m-d')); $this->assertSame(20, $period->getDateInterval()->dayz); $this->assertSame($opt, $period->getOptions()); } public function testSetTimezone(): void { $periodClass = static::$periodClass; $period = $periodClass::create( '2018-03-25 00:00 America/Toronto', 'PT1H', '2018-03-25 12:00 Europe/London', )->setTimezone('Europe/Oslo'); $this->assertSame('2018-03-25 06:00 Europe/Oslo', $period->getStartDate()->format('Y-m-d H:i e')); $this->assertSame('2018-03-25 13:00 Europe/Oslo', $period->getEndDate()->format('Y-m-d H:i e')); $period = $periodClass::create( '2018-03-25 00:00 America/Toronto', 'PT1H', 5, )->setTimezone('Europe/Oslo'); $this->assertSame('2018-03-25 06:00 Europe/Oslo', $period->getStartDate()->format('Y-m-d H:i e')); $this->assertNull($period->getEndDate()); $this->assertSame('2018-03-25 10:00 Europe/Oslo', $period->calculateEnd()->format('Y-m-d H:i e')); } public function testShiftTimezone(): void { $periodClass = static::$periodClass; $period = $periodClass::create( '2018-03-25 00:00 America/Toronto', 'PT1H', '2018-03-25 12:00 Europe/London', )->shiftTimezone('Europe/Oslo'); $this->assertSame('2018-03-25 00:00 Europe/Oslo', $period->getStartDate()->format('Y-m-d H:i e')); $this->assertSame('2018-03-25 12:00 Europe/Oslo', $period->getEndDate()->format('Y-m-d H:i e')); $period = $periodClass::create( '2018-03-26 00:00 America/Toronto', 'PT1H', 5, )->shiftTimezone('Europe/Oslo'); $this->assertSame('2018-03-26 00:00 Europe/Oslo', $period->getStartDate()->format('Y-m-d H:i e')); $this->assertNull($period->getEndDate()); $this->assertSame('2018-03-26 04:00 Europe/Oslo', $period->calculateEnd()->format('Y-m-d H:i e')); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriod/ComparisonTest.php
tests/CarbonPeriod/ComparisonTest.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonPeriod; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterval; use DateInterval; use DatePeriod; use DateTime; use DateTimeImmutable; use Tests\AbstractTestCase; class ComparisonTest extends AbstractTestCase { public function testEqualToTrue() { $periodClass = static::$periodClass; $period = $periodClass::create('2010-01-01', '2010-02-01'); $this->assertTrue($period->equalTo($period)); $this->assertTrue($period->eq($period)); $this->assertTrue($period->eq($periodClass::create('2010-01-01', '2010-02-01'))); $this->assertTrue($period->eq($periodClass::create('R3/2010-01-01/P1D/2010-02-01'))); $this->assertTrue($period->eq(Carbon::parse('2010-01-01')->daysUntil('2010-02-01'))); $this->assertTrue($period->eq( new DatePeriod(new DateTime('2010-01-01'), CarbonInterval::day(), new DateTime('2010-02-01')) )); $period = $periodClass::create('2010-01-01', '2010-02-01', 'P2D'); $this->assertTrue($period->eq($periodClass::create('2010-01-01', '2010-02-01', 'P2D'))); $this->assertTrue($period->eq($periodClass::create('2010-01-01', '2010-02-01', CarbonInterval::day(2)))); $this->assertTrue($period->eq($periodClass::create('2010-01-01', '2010-02-01')->setDateInterval('P2D'))); $this->assertTrue($period->eq($periodClass::create('R3/2010-01-01/P2D/2010-02-01'))); $period = $periodClass::create('2010-01-01', '2010-02-01', $periodClass::EXCLUDE_START_DATE); $this->assertTrue($period->eq($periodClass::create('2010-01-01', '2010-02-01', $periodClass::EXCLUDE_START_DATE))); $this->assertTrue($period->eq($periodClass::create('2010-01-01', '2010-02-01')->setOptions($periodClass::EXCLUDE_START_DATE))); } public function testEqualToFalse() { $periodClass = static::$periodClass; $period = $periodClass::create('2010-01-01', '2010-02-01'); $this->assertFalse($period->equalTo($periodClass::create('2010-01-02', '2010-02-01'))); $this->assertFalse($period->eq($periodClass::create('2010-01-02', '2010-02-01'))); $this->assertFalse($period->eq($periodClass::create('2010-01-01', '2010-02-02'))); $this->assertFalse($period->eq($periodClass::create('2010-01-01', '2010-02-02', 'P2D'))); $this->assertFalse($period->eq($periodClass::create('2010-01-01', '2010-02-02', $periodClass::EXCLUDE_START_DATE))); } public function testNotEqualToTrue() { $periodClass = static::$periodClass; $period = $periodClass::create('2010-01-01', '2010-02-01'); $this->assertTrue($period->notEqualTo($periodClass::create('2010-01-02', '2010-02-01'))); $this->assertTrue($period->ne($periodClass::create('2010-01-02', '2010-02-01'))); $this->assertTrue($period->ne($periodClass::create('2010-01-01', '2010-02-02'))); $this->assertTrue($period->ne($periodClass::create('2010-01-01', '2010-02-02', 'P2D'))); $this->assertTrue($period->ne($periodClass::create('2010-01-01', '2010-02-02', $periodClass::EXCLUDE_START_DATE))); } public function testNotEqualToFalse() { $periodClass = static::$periodClass; $period = $periodClass::create('2010-01-01', '2010-02-01'); $this->assertFalse($period->notEqualTo($period)); $this->assertFalse($period->ne($period)); $this->assertFalse($period->ne($periodClass::create('2010-01-01', '2010-02-01'))); $this->assertFalse($period->ne($periodClass::create('R3/2010-01-01/P1D/2010-02-01'))); $this->assertFalse($period->ne(Carbon::parse('2010-01-01')->daysUntil('2010-02-01'))); $this->assertFalse($period->ne( new DatePeriod(new DateTime('2010-01-01'), CarbonInterval::day(), new DateTime('2010-02-01')) )); $period = $periodClass::create('2010-01-01', '2010-02-01', 'P2D'); $this->assertFalse($period->ne($periodClass::create('2010-01-01', '2010-02-01', 'P2D'))); $this->assertFalse($period->ne($periodClass::create('2010-01-01', '2010-02-01', CarbonInterval::day(2)))); $this->assertFalse($period->ne($periodClass::create('2010-01-01', '2010-02-01')->setDateInterval('P2D'))); $this->assertFalse($period->ne($periodClass::create('R3/2010-01-01/P2D/2010-02-01'))); $period = $periodClass::create('2010-01-01', '2010-02-01', $periodClass::EXCLUDE_START_DATE); $this->assertFalse($period->ne($periodClass::create('2010-01-01', '2010-02-01', $periodClass::EXCLUDE_START_DATE))); $this->assertFalse($period->ne($periodClass::create('2010-01-01', '2010-02-01')->setOptions($periodClass::EXCLUDE_START_DATE))); } public function testStartComparisons() { $periodClass = static::$periodClass; Carbon::setTestNow('2020-01-01'); CarbonImmutable::setTestNow('2020-01-01'); $this->assertFalse($periodClass::create('2020-01-05', '2020-02-01')->startsBefore($periodClass::create('2019-12-05', '2020-02-01'))); $this->assertTrue($periodClass::create('2020-01-05', '2020-02-01')->startsBefore($periodClass::create('2020-01-07', '2020-01-08'))); $this->assertFalse($periodClass::create('2020-01-05', '2020-02-01')->startsBefore(CarbonInterval::days(2))); $this->assertFalse($periodClass::create('2020-01-05', '2020-02-01')->startsBefore(CarbonInterval::days(4))); $this->assertTrue($periodClass::create('2020-01-05', '2020-02-01')->startsBeforeOrAt(CarbonInterval::days(4))); $this->assertTrue($periodClass::create('2020-01-05', '2020-02-01')->startsBefore(CarbonInterval::days(5))); $this->assertTrue($periodClass::create('2020-01-05', '2020-02-01')->startsAfter($periodClass::create('2019-12-05', '2020-02-01'))); $this->assertFalse($periodClass::create('2020-01-05', '2020-02-01')->startsAfter($periodClass::create('2020-01-07', '2020-01-08'))); $this->assertTrue($periodClass::create('2020-01-05', '2020-02-01')->startsAfter(CarbonInterval::days(2))); $this->assertFalse($periodClass::create('2020-01-05', '2020-02-01')->startsAfter(CarbonInterval::days(4))); $this->assertTrue($periodClass::create('2020-01-05', '2020-02-01')->startsAfterOrAt(CarbonInterval::days(4))); $this->assertFalse($periodClass::create('2020-01-05', '2020-02-01')->startsAfter(CarbonInterval::days(5))); $this->assertFalse($periodClass::create('2020-01-05', '2020-02-01')->startsAt('2020-02-01')); $this->assertTrue($periodClass::create('2020-01-05', '2020-02-01')->startsAt('2020-01-05')); } public function testEndComparisons() { $periodClass = static::$periodClass; Carbon::setTestNow('2020-02-05'); CarbonImmutable::setTestNow('2020-02-05'); $this->assertFalse($periodClass::create('2020-01-05', '2020-02-01')->endsBefore($periodClass::create('2019-12-05', '2020-02-01'))); $this->assertFalse($periodClass::create('2020-01-05', '2020-02-01')->endsBefore($periodClass::create('2020-01-07', '2020-01-08'))); $this->assertFalse($periodClass::create('2020-01-05', '2020-02-01')->endsBefore($periodClass::create('2020-02-01', '2020-02-08'))); $this->assertTrue($periodClass::create('2020-01-05', '2020-02-01')->endsBeforeOrAt($periodClass::create('2020-02-01', '2020-02-08'))); $this->assertTrue($periodClass::create('2020-01-05', '2020-02-01')->endsBefore($periodClass::create('2020-02-03', '2020-02-08'))); $this->assertTrue($periodClass::create('2020-01-05', '2020-02-01')->endsBefore(CarbonInterval::days(2)->invert())); $this->assertFalse($periodClass::create('2020-01-05', '2020-02-01')->endsBefore(CarbonInterval::days(4)->invert())); $this->assertTrue($periodClass::create('2020-01-05', '2020-02-01')->endsBeforeOrAt(CarbonInterval::days(4)->invert())); $this->assertFalse($periodClass::create('2020-01-05', '2020-02-01')->endsBefore(CarbonInterval::days(5)->invert())); $this->assertTrue($periodClass::create('2020-01-05', '2020-02-01')->endsAfter($periodClass::create('2019-12-05', '2020-02-01'))); $this->assertTrue($periodClass::create('2020-01-05', '2020-02-01')->endsAfter($periodClass::create('2020-01-07', '2020-01-08'))); $this->assertTrue($periodClass::create('2020-01-05', '2020-02-01')->endsAfterOrAt($periodClass::create('2020-02-01', '2020-01-08'))); $this->assertFalse($periodClass::create('2020-01-05', '2020-02-01')->endsAfter($periodClass::create('2020-02-01', '2020-01-08'))); $this->assertFalse($periodClass::create('2020-01-05', '2020-02-01')->endsAfter($periodClass::create('2020-02-02', '2020-01-08'))); $this->assertFalse($periodClass::create('2020-01-05', '2020-02-01')->endsAfter(CarbonInterval::days(2)->invert())); $this->assertFalse($periodClass::create('2020-01-05', '2020-02-01')->endsAfter(CarbonInterval::days(4)->invert())); $this->assertTrue($periodClass::create('2020-01-05', '2020-02-01')->endsAfterOrAt(CarbonInterval::days(4)->invert())); $this->assertTrue($periodClass::create('2020-01-05', '2020-02-01')->endsAfter(CarbonInterval::days(5)->invert())); $this->assertTrue($periodClass::create('2020-01-05', '2020-02-01')->endsAt('2020-02-01')); $this->assertFalse($periodClass::create('2020-01-05', '2020-02-01')->endsAt('2020-01-05')); } public function testContains() { $periodClass = static::$periodClass; $period = $periodClass::create('2019-08-01', '2019-08-10'); $this->assertFalse($period->contains('2019-07-31 23:59:59')); $this->assertTrue($period->contains('2019-08-01')); $this->assertTrue($period->contains('2019-08-02')); $this->assertTrue($period->contains('2019-08-10')); $this->assertFalse($period->contains('2019-08-10 00:00:01')); $period = $periodClass::create('2019-08-01', '2019-08-10', $periodClass::EXCLUDE_START_DATE | $periodClass::EXCLUDE_END_DATE); $this->assertFalse($period->contains('2019-08-01')); $this->assertTrue($period->contains('2019-08-01 00:00:01')); $this->assertTrue($period->contains('2019-08-02')); $this->assertTrue($period->contains('2019-08-09 23:59:59')); $this->assertFalse($period->contains('2019-08-10')); } public function testConsecutivePeriods() { $periodClass = static::$periodClass; $july = $periodClass::create('2019-07-29', '2019-07-31'); $august = $periodClass::create('2019-08-01', '2019-08-12'); $this->assertFalse($july->follows($august)); $this->assertTrue($august->follows($july)); $this->assertTrue($july->isFollowedBy($august)); $this->assertFalse($august->isFollowedBy($july)); $this->assertTrue($july->isConsecutiveWith($august)); $this->assertTrue($august->isConsecutiveWith($july)); $this->assertFalse($july->follows('2019-08-01', '2019-08-12')); $this->assertTrue($august->follows('2019-07-29', '2019-07-31')); $this->assertTrue($july->isFollowedBy('2019-08-01', '2019-08-12')); $this->assertFalse($august->isFollowedBy('2019-07-29', '2019-07-31')); $this->assertTrue($july->isConsecutiveWith('2019-08-01', '2019-08-12')); $this->assertTrue($august->isConsecutiveWith('2019-07-29', '2019-07-31')); $july2 = new DatePeriod( new DateTimeImmutable('2019-07-29'), new DateInterval('P1D'), new DateTimeImmutable('2019-07-31'), ); $august2 = new DatePeriod( new DateTimeImmutable('2019-08-01'), new DateInterval('P1D'), new DateTimeImmutable('2019-08-12'), ); $this->assertFalse($july->follows($august2)); $this->assertTrue($august->follows($july2)); $this->assertTrue($july->isFollowedBy($august2)); $this->assertFalse($august->isFollowedBy($july2)); $this->assertTrue($july->isConsecutiveWith($august2)); $this->assertTrue($august->isConsecutiveWith($july2)); $july = $periodClass::create('2019-07-29', '2019-08-01'); $august = $periodClass::create('2019-08-01', '2019-08-12'); $this->assertFalse($july->follows($august)); $this->assertFalse($august->follows($july)); $this->assertFalse($july->isFollowedBy($august)); $this->assertFalse($august->isFollowedBy($july)); $this->assertFalse($july->isConsecutiveWith($august)); $this->assertFalse($august->isConsecutiveWith($july)); $july = $periodClass::create('2019-07-29', '2019-07-31', $periodClass::EXCLUDE_END_DATE); $august = $periodClass::create('2019-08-01', '2019-08-12', $periodClass::EXCLUDE_START_DATE); $this->assertFalse($july->follows($august)); $this->assertFalse($august->follows($july)); $this->assertFalse($july->isFollowedBy($august)); $this->assertFalse($august->isFollowedBy($july)); $this->assertFalse($july->isConsecutiveWith($august)); $this->assertFalse($august->isConsecutiveWith($july)); } public function testConsecutivePeriodsWithExclusion() { $periodClass = static::$periodClass; $july = $periodClass::create('2019-07-29', '2019-08-01', $periodClass::EXCLUDE_END_DATE); $august = $periodClass::create('2019-07-31', '2019-08-12', $periodClass::EXCLUDE_START_DATE); $this->assertFalse($july->follows($august)); $this->assertTrue($august->follows($july)); $this->assertTrue($july->isFollowedBy($august)); $this->assertFalse($august->isFollowedBy($july)); $this->assertTrue($july->isConsecutiveWith($august)); $this->assertTrue($august->isConsecutiveWith($july)); } public function testConsecutivePeriodsWithDynamicEnd() { $periodClass = static::$periodClass; $july = $periodClass::create('2019-07-29', '1 day', 4); $august = $periodClass::create('2019-08-02', '2019-08-12'); $this->assertFalse($july->follows($august)); $this->assertTrue($august->follows($july)); $this->assertTrue($july->isFollowedBy($august)); $this->assertFalse($august->isFollowedBy($july)); $this->assertTrue($july->isConsecutiveWith($august)); $this->assertTrue($august->isConsecutiveWith($july)); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriod/IteratorTest.php
tests/CarbonPeriod/IteratorTest.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonPeriod; use Carbon\Carbon; use Carbon\CarbonInterval; use Carbon\CarbonPeriod; use Generator; use PHPUnit\Framework\Attributes\DataProvider; use Tests\AbstractTestCase; use Tests\CarbonPeriod\Fixtures\CarbonPeriodFactory; class IteratorTest extends AbstractTestCase { protected $iterationLimit = 100; public function testKeyAndCurrentAreCorrectlyInstantiated() { $period = CarbonPeriodFactory::withEvenDaysFilter(static::$periodClass); $this->assertSame(0, $period->key()); $this->assertInstanceOfCarbon($period->current()); $this->assertSame('2012-07-04 00:00:00', $period->current()->format('Y-m-d H:i:s')); $this->assertTrue($period->valid()); } public function testValidIsCorrectlyInstantiated() { $period = CarbonPeriodFactory::withEvenDaysFilter(static::$periodClass); $this->assertTrue($period->valid()); } public function testCurrentIsAlwaysCarbonInstance() { $period = CarbonPeriodFactory::withEvenDaysFilter(static::$periodClass); foreach ($period as $current) { $this->assertInstanceOfCarbon($current); $this->assertEquals($current, $period->current()); if (PHP_VERSION < 8.2) { $this->assertEquals($current, $period->current); } } } public function testKeysAreSequential() { $keys = []; $period = CarbonPeriodFactory::withEvenDaysFilter(static::$periodClass); foreach ($period as $key => $current) { $this->assertIsInt($keys[] = $key); $this->assertSame($key, $period->key()); } $this->assertSame(array_keys($keys), $keys); } public function testElementsInLoopAreAlwaysValid() { $period = CarbonPeriodFactory::withEvenDaysFilter(static::$periodClass); foreach ($period as $key => $current) { $this->assertTrue($period->valid()); } } public function testKeyAndCurrentAreCorrectlyIterated() { $period = CarbonPeriodFactory::withEvenDaysFilter(static::$periodClass); $period->next(); $this->assertSame(1, $period->key()); $this->assertSame('2012-07-10 00:00:00', $period->current()->format('Y-m-d H:i:s')); $this->assertTrue($period->valid()); } public function testKeyAndCurrentAreCorrectlyRewound() { $period = CarbonPeriodFactory::withEvenDaysFilter(static::$periodClass); $period->next(); $period->rewind(); $this->assertSame(0, $period->key()); $this->assertSame('2012-07-04 00:00:00', $period->current()->format('Y-m-d H:i:s')); $this->assertTrue($period->valid()); } public function testKeyAndCurrentAreNullAfterIteration() { $period = CarbonPeriodFactory::withEvenDaysFilter(static::$periodClass); foreach ($period as $key => $current) { // } $this->assertNull($period->key()); $this->assertNull($period->current()); $this->assertFalse($period->valid()); } #[DataProvider('dataForIterateBackwardsArguments')] public function testIterateBackwards(array $arguments, array $expected) { $periodClass = static::$periodClass; $period = $periodClass::create(...$arguments); $interval = new CarbonInterval('P3D'); $interval->invert = 1; $period = $period->setDateInterval($interval); $this->assertSame( $this->standardizeDates($expected), $this->standardizeDates($period), ); } public static function dataForIterateBackwardsArguments(): Generator { yield [ ['2015-10-15', '2015-10-06'], ['2015-10-15', '2015-10-12', '2015-10-09', '2015-10-06'], ]; yield [ ['2015-10-15', '2015-10-06', CarbonPeriod::EXCLUDE_START_DATE], ['2015-10-12', '2015-10-09', '2015-10-06'], ]; yield [ ['2015-10-15', '2015-10-06', CarbonPeriod::EXCLUDE_END_DATE], ['2015-10-15', '2015-10-12', '2015-10-09'], ]; yield [ ['2015-10-15', '2015-10-06', CarbonPeriod::EXCLUDE_START_DATE | CarbonPeriod::EXCLUDE_END_DATE], ['2015-10-12', '2015-10-09'], ]; yield [ ['2015-10-15', 3], ['2015-10-15', '2015-10-12', '2015-10-09'], ]; } public function testChangingParametersShouldNotCauseInfiniteLoop() { $periodClass = static::$periodClass; $period = $periodClass::create() ->setStartDate($start = '2012-07-01') ->setEndDate($end = '2012-07-20') ->setDateInterval($interval = 'P1D') ->setRecurrences($recurrences = 10) ->setOptions($options = $periodClass::EXCLUDE_START_DATE | $periodClass::EXCLUDE_END_DATE) ->addFilter($filter = function () { return true; }); $counter = 0; foreach ($period as $current) { if (++$counter >= $this->iterationLimit) { break; } $period->removeFilter($filter) ->prependFilter($filter) ->setFilters([]) ->setStartDate($start) ->setEndDate($end) ->invertDateInterval() ->setDateInterval($interval) ->setRecurrences($recurrences) ->setOptions($options) ->resetFilters() ->addFilter($filter); } $this->assertLessThan($this->iterationLimit, $counter, 'Changing parameters during the iteration caused an infinite loop.'); } public function testChangeEndDateDuringIteration() { $period = CarbonPeriodFactory::withEvenDaysFilter(static::$periodClass); $results = []; foreach ($period as $key => $current) { $results[] = \sprintf('%s => %s', $key, $current->toDateString()); if ($current->toDateString() === '2012-07-16') { $period = $period->setEndDate($current); // Note: Current is no longer valid, because it is now equal to end, which is excluded. $this->assertNull($period->key()); $this->assertNull($period->current()); $this->assertFalse($period->valid()); } if (\count($results) >= $this->iterationLimit) { $this->fail('Infinite loop detected when traversing the period.'); } } $this->assertSame( ['0 => 2012-07-04', '1 => 2012-07-10', '2 => 2012-07-16'], $results, ); } public function testKeepIncreasingRecurrencesDuringIteration() { $period = new CarbonPeriod('2012-07-01', $recurrences = 1); $results = []; foreach ($period as $key => $current) { $results[] = \sprintf('%s => %s', $key, $current->toDateString()); if ($recurrences < 4) { $period->setRecurrences(++$recurrences); // Note: Current is still valid, because we simply extended the period. $this->assertSame($key, $period->key()); $this->assertEquals($current, $period->current()); $this->assertTrue($period->valid()); } if (\count($results) >= $this->iterationLimit) { $this->fail('Infinite loop detected when traversing the period.'); } } $this->assertSame( ['0 => 2012-07-01', '1 => 2012-07-02', '2 => 2012-07-03', '3 => 2012-07-04'], $results, ); } public function testChangeStartDateDuringIteration() { $period = new CarbonPeriod('2012-07-01', '2012-07-04'); $results = []; $newStart = new Carbon('2012-07-03'); foreach ($period as $key => $current) { $results[] = \sprintf('%s => %s', $key, $current->toDateString()); if ($current < $newStart) { $period->setStartDate($newStart); // Note: Current is still valid, because start date is used only for initialization. $this->assertEquals($key, $period->key()); $this->assertEquals($current, $period->current()); $this->assertTrue($period->valid()); } if (\count($results) >= $this->iterationLimit) { $this->fail('Infinite loop detected when traversing the period.'); } } $this->assertSame( // Note: Results are not affected, because start date is used only for initialization. ['0 => 2012-07-01', '1 => 2012-07-02', '2 => 2012-07-03', '3 => 2012-07-04'], $results, ); } public function testChangeDateIntervalDuringIteration() { $period = new CarbonPeriod('2012-07-01', 3); $results = []; foreach ($period as $key => $current) { $results[] = \sprintf('%s => %s', $key, $current->toDateString()); $period->setDateInterval('P3D'); // Note: Current is still valid, because changed interval changes only subsequent items. $this->assertSame($key, $period->key()); $this->assertEquals($current, $period->current()); $this->assertTrue($period->valid()); if (\count($results) >= $this->iterationLimit) { $this->fail('Infinite loop detected when traversing the period.'); } } $this->assertSame( ['0 => 2012-07-01', '1 => 2012-07-04', '2 => 2012-07-07'], $results, ); } public function testValidateOncePerIteration() { $period = CarbonPeriodFactory::withCounter(static::$periodClass, $counter); $period->key(); $period->current(); $period->valid(); $this->assertSame(1, $counter); $period->next(); $this->assertSame(2, $counter); $period->key(); $period->current(); $period->valid(); $this->assertSame(2, $counter); } public function testInvalidateCurrentAfterChangingParameters() { $periodClass = static::$periodClass; $period = $periodClass::create('2012-10-01'); $this->assertInstanceOfCarbon($period->current()); $period = $period->addFilter($periodClass::END_ITERATION); $this->assertNull($period->current()); } public function testTraversePeriodDynamically() { $period = CarbonPeriodFactory::withEvenDaysFilter(static::$periodClass); $results = []; while ($current = $period->current()) { $results[] = $current; $period->next(); if (\count($results) >= $this->iterationLimit) { $this->fail('Infinite loop detected when traversing the period.'); } } $this->assertSame( $this->standardizeDates(['2012-07-04', '2012-07-10', '2012-07-16']), $this->standardizeDates($results), ); } public function testExtendCompletedIteration() { $periodClass = static::$periodClass; $period = $periodClass::create('2018-10-10', '2018-10-11'); $results = []; while ($period->valid()) { $results[] = $period->current(); $period->next(); } $period = $period->setEndDate('2018-10-13'); while ($period->valid()) { $results[] = $period->current(); $period->next(); } $this->assertSame( $this->standardizeDates(['2018-10-10', '2018-10-11', '2018-10-12', '2018-10-13']), $this->standardizeDates($results), ); } public function testRevalidateCurrentAfterChangeOfParameters() { $periodClass = static::$periodClass; $period = $periodClass::create()->setStartDate($start = new Carbon('2018-10-28')); $this->assertEquals($start, $period->current()); $this->assertNotSame($start, $period->current()); $period = $period->addFilter($excludeStart = function ($date) use ($start) { return $date != $start; }); $this->assertNull($period->current()); $period = $period->removeFilter($excludeStart); $this->assertEquals($start, $period->current()); $this->assertNotSame($start, $period->current()); } public function testRevalidateCurrentAfterEndOfIteration() { $periodClass = static::$periodClass; $period = $periodClass::create()->setStartDate($start = new Carbon('2018-10-28')); $this->assertEquals($start, $period->current()); $this->assertNotSame($start, $period->current()); $period = $period->addFilter($periodClass::END_ITERATION); $this->assertNull($period->current()); $period = $period->removeFilter($periodClass::END_ITERATION); $this->assertEquals($start, $period->current()); $this->assertNotSame($start, $period->current()); } public function testChangeStartDateBeforeIteration() { $periodClass = static::$periodClass; $period = $periodClass::create(new Carbon('2018-10-05'), 3) ->setStartDate(new Carbon('2018-10-13')) ->toggleOptions($periodClass::EXCLUDE_START_DATE, true); $this->assertEquals(new Carbon('2018-10-14'), $period->current()); } public function testChangeStartDateAfterStartedIteration() { $periodClass = static::$periodClass; $period = $periodClass::create(new Carbon('2018-10-05'), 3); $current = $period->current(); $period->toggleOptions($periodClass::EXCLUDE_START_DATE, true); $period->setStartDate(new Carbon('2018-10-13')); $this->assertEquals($current, $period->current()); } public function testInvertDateIntervalDuringIteration() { $periodClass = static::$periodClass; $period = new $periodClass('2018-04-11', 5); $results = []; foreach ($period as $key => $date) { $results[] = $date; if ($key === 2) { $period->invertDateInterval(); } } $this->assertSame( $this->standardizeDates(['2018-04-11', '2018-04-12', '2018-04-13', '2018-04-12', '2018-04-11']), $this->standardizeDates($results), ); } public function testManualIteration() { $period = CarbonPeriodFactory::withStackFilter(static::$periodClass); $period->rewind(); $str = ''; while ($period->valid()) { if ($period->key()) { $str .= ', '; } $str .= $period->current()->format('m-d'); $period->next(); } $this->assertSame('01-01, 01-03', $str); } public function testSkip() { $periodClass = static::$periodClass; $period = $periodClass::create('2018-05-30', '2018-07-13'); $output = []; foreach ($period as $day) { /* @var Carbon $day */ $output[] = $day->format('Y-m-d'); if ($day->isSunday()) { $this->assertTrue($period->skip(7)); $output[] = '...'; } } $this->assertSame([ '2018-05-30', '2018-05-31', '2018-06-01', '2018-06-02', '2018-06-03', '...', '2018-06-11', '2018-06-12', '2018-06-13', '2018-06-14', '2018-06-15', '2018-06-16', '2018-06-17', '...', '2018-06-25', '2018-06-26', '2018-06-27', '2018-06-28', '2018-06-29', '2018-06-30', '2018-07-01', '...', '2018-07-09', '2018-07-10', '2018-07-11', '2018-07-12', '2018-07-13', ], $output); $this->assertFalse($period->skip()); $this->assertFalse($period->skip(7)); } public function testLocale() { /** @var CarbonPeriod $period */ $period = CarbonPeriodFactory::withStackFilter(static::$periodClass)->locale('de'); $str = ''; foreach ($period as $key => $date) { if ($key) { $str .= ', '; } $str .= $date->isoFormat('MMMM dddd'); } $this->assertSame('Januar Montag, Januar Mittwoch', $str); } public function testTimezone() { $period = CarbonPeriodFactory::withStackFilter(static::$periodClass)->shiftTimezone('America/Toronto'); $str = null; foreach ($period as $key => $date) { $str = $date->format('H e'); break; } $this->assertSame('00 America/Toronto', $str); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriod/ToArrayTest.php
tests/CarbonPeriod/ToArrayTest.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonPeriod; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterval; use Carbon\CarbonPeriod; use Carbon\CarbonPeriodImmutable; use Carbon\Exceptions\EndLessPeriodException; use DateTimeInterface; use Tests\AbstractTestCase; use Tests\CarbonPeriod\Fixtures\CarbonPeriodFactory; class ToArrayTest extends AbstractTestCase { public function testToArrayIsNotEmptyArray() { $result = CarbonPeriodFactory::withEvenDaysFilter(static::$periodClass)->toArray(); $this->assertIsArray($result); $this->assertNotEmpty($result); } public function testToArrayHasCorrectCount() { $period = CarbonPeriodFactory::withEvenDaysFilter(static::$periodClass); $this->assertCount(3, $period->toArray()); } public function testToArrayValuesAreCarbonInstances() { $result = CarbonPeriodFactory::withEvenDaysFilter(static::$periodClass)->toArray(); foreach ($result as $key => $current) { $this->assertInstanceOfCarbon($current); } } public function testToArrayKeysAreSequential() { $result = CarbonPeriodFactory::withEvenDaysFilter(static::$periodClass)->toArray(); $this->assertSame([0, 1, 2], array_keys($result)); } public function testToArrayHasCorrectValues() { $result = CarbonPeriodFactory::withEvenDaysFilter(static::$periodClass)->toArray(); $this->assertSame( $this->standardizeDates(['2012-07-04', '2012-07-10', '2012-07-16']), $this->standardizeDates($result), ); } public function testJsonSerialize() { $result = json_encode(CarbonPeriodFactory::withEvenDaysFilter(static::$periodClass)); $this->assertSame('["2012-07-04T04:00:00.000000Z","2012-07-10T04:00:00.000000Z","2012-07-16T04:00:00.000000Z"]', $result); } public function testCountEmptyPeriod() { $periodClass = static::$periodClass; $assertThrow = function (CarbonPeriod $period) { $message = null; try { $period->count(); } catch (EndLessPeriodException $exception) { $message = $exception->getMessage(); } $this->assertSame("Endless period can't be converted to array nor counted.", $message); }; $period = new $periodClass(); $this->assertTrue($period->isUnfilteredAndEndLess()); $assertThrow($period); $this->assertSame(Carbon::now()->format('Y-m-d H:i:s'), $period->first()->format('Y-m-d H:i:s')); foreach ($period as $date) { break; } $date ??= null; $this->assertInstanceOfCarbon($date); $this->assertSame(Carbon::now()->format('Y-m-d H:i:s'), $date->format('Y-m-d H:i:s')); $period = new $periodClass(INF); $this->assertTrue($period->isUnfilteredAndEndLess()); $assertThrow($period); $period = new $periodClass('2022-05-18', '1 day'); $this->assertTrue($period->isUnfilteredAndEndLess()); $assertThrow($period); $period = new $periodClass('2022-05-18', '1 day', CarbonImmutable::endOfTime()); $this->assertTrue($period->isUnfilteredAndEndLess()); $assertThrow($period); $period = new $periodClass('2022-05-18', '1 day'); $period->setDateClass(CarbonImmutable::class); $period->setEndDate(CarbonImmutable::endOfTime()); $this->assertTrue($period->isUnfilteredAndEndLess()); $assertThrow($period); $period = new $periodClass(3); $this->assertFalse($period->isUnfilteredAndEndLess()); $this->assertSame(3, $period->count()); $period = new $periodClass('2022-05-18', '2022-05-23'); $this->assertFalse($period->isUnfilteredAndEndLess()); $this->assertSame(6, $period->count()); $period = new $periodClass('2022-05-18', INF); $period = $period->addFilter(static function (DateTimeInterface $date) use ($periodClass) { if ($date->format('Y-m-d') > '2022-05-20') { return $periodClass::END_ITERATION; } return true; }); $this->assertFalse($period->isUnfilteredAndEndLess()); $this->assertSame(3, $period->count()); } public function testCountByMethod() { $period = CarbonPeriodFactory::withEvenDaysFilter(static::$periodClass); $this->assertSame(3, $period->count()); } public function testCountByFunction() { $period = CarbonPeriodFactory::withEvenDaysFilter(static::$periodClass); $this->assertCount(3, $period); } public function testFirst() { $period = CarbonPeriodFactory::withEvenDaysFilter(static::$periodClass); $this->assertEquals(new Carbon('2012-07-04'), $period->first()); } public function testLast() { $period = CarbonPeriodFactory::withEvenDaysFilter(static::$periodClass); $this->assertEquals(new Carbon('2012-07-16'), $period->last()); } public function testToArrayOfEmptyPeriod() { $periodClass = static::$periodClass; $result = $periodClass::create(0)->toArray(); $this->assertSame([], $result); } public function testCountOfEmptyPeriod() { $periodClass = static::$periodClass; $period = $periodClass::create(0); $this->assertSame(0, $period->count()); } public function testFirstOfEmptyPeriod() { $periodClass = static::$periodClass; $period = $periodClass::create(0); $this->assertNull($period->first()); $period = new class(0) extends CarbonPeriod { public function isUnfilteredAndEndLess(): bool { return true; } }; $this->assertNull($period->first()); } public function testLastOfEmptyPeriod() { $periodClass = static::$periodClass; $period = $periodClass::create(0); $this->assertNull($period->last()); } public function testRestoreIterationStateAfterCallingToArray() { $period = CarbonPeriodFactory::withEvenDaysFilter(static::$periodClass); $key = $period->key(); $current = $period->current(); $this->assertSame(0, $key); $this->assertEquals(new Carbon('2012-07-04'), $current); $period->next(); $this->assertSame( $this->standardizeDates(['2012-07-04', '2012-07-10', '2012-07-16']), $this->standardizeDates($period->toArray()), ); $this->assertSame(1, $period->key()); $this->assertEquals(new Carbon('2012-07-10'), $period->current()); $period->next(); $this->assertSame(2, $period->key()); $this->assertEquals(new Carbon('2012-07-16'), $period->current()); } public function testToArrayResultsAreInTheExpectedTimezone() { $periodClass = static::$periodClass; $period = $periodClass::create('2018-05-13 12:00 Asia/Kabul', 'PT1H', 3); $expected = [ '2018-05-13 12:00:00 +04:30', '2018-05-13 13:00:00 +04:30', '2018-05-13 14:00:00 +04:30', ]; $this->assertSame($expected, $this->standardizeDates($period->toArray())); } public function testDebugInfo() { $periodClass = static::$periodClass; $dateClass = $periodClass === CarbonPeriodImmutable::class ? CarbonImmutable::class : Carbon::class; $period = $periodClass::create('2018-05-13 12:00 Asia/Kabul', 'PT1H', 3); $expected = [ 'dateClass' => $dateClass, 'dateInterval' => CarbonInterval::hour()->optimize(), 'filters' => [ [ $periodClass::RECURRENCES_FILTER, null, ], ], 'startDate' => $dateClass::parse('2018-05-13 12:00 Asia/Kabul'), 'recurrences' => 3, ...($this->initialOptions ? ['options' => $this->initialOptions] : []), ]; $actual = $period->__debugInfo(); $actual = array_combine(array_map( static fn (string $key): string => preg_replace('/^\000\*\000/', '', $key), array_keys($actual), ), $actual); $interval = $actual['dateInterval'] ?? null; $interval?->optimize(); $this->assertEquals($expected, $actual); $period = $period->setRecurrences(5); $actual = $period->__debugInfo(); $this->assertSame(5, $actual['recurrences']); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriod/SerializationTest.php
tests/CarbonPeriod/SerializationTest.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterval; use Carbon\CarbonPeriod; use PHPUnit\Framework\Attributes\DataProvider; use Tests\AbstractTestCase; class SerializationTest extends AbstractTestCase { public function testSerializationFromV2(): void { $data = "O:19:\"Carbon\CarbonPeriod\":24:{s:12:\"\0*\0dateClass\";s:13:\"Carbon\Carbon\";s:15:\"\0*\0dateInterval\";O:21:\"Carbon\CarbonInterval\":22:{s:1:\"y\";i:0;s:1:\"m\";i:0;s:1:\"d\";i:3;s:1:\"h\";i:0;s:1:\"i\";i:0;s:1:\"s\";i:0;s:1:\"f\";d:0;s:6:\"invert\";i:0;s:4:\"days\";b:0;s:11:\"from_string\";b:0;s:9:\"\0*\0tzName\";N;s:7:\"\0*\0step\";N;s:22:\"\0*\0localMonthsOverflow\";N;s:21:\"\0*\0localYearsOverflow\";N;s:25:\"\0*\0localStrictModeEnabled\";N;s:24:\"\0*\0localHumanDiffOptions\";N;s:22:\"\0*\0localToStringFormat\";N;s:18:\"\0*\0localSerializer\";N;s:14:\"\0*\0localMacros\";N;s:21:\"\0*\0localGenericMacros\";N;s:22:\"\0*\0localFormatFunction\";N;s:18:\"\0*\0localTranslator\";N;}s:14:\"\0*\0constructed\";b:1;s:20:\"\0*\0isDefaultInterval\";b:0;s:10:\"\0*\0filters\";a:1:{i:0;a:2:{i:0;a:2:{i:0;s:19:\"Carbon\CarbonPeriod\";i:1;s:13:\"filterEndDate\";}i:1;N;}}s:12:\"\0*\0startDate\";O:13:\"Carbon\Carbon\":3:{s:4:\"date\";s:26:\"2018-04-21 00:00:00.000000\";s:13:\"timezone_type\";i:3;s:8:\"timezone\";s:3:\"UTC\";}s:10:\"\0*\0endDate\";O:13:\"Carbon\Carbon\":3:{s:4:\"date\";s:26:\"2018-04-27 00:00:00.000000\";s:13:\"timezone_type\";i:3;s:8:\"timezone\";s:3:\"UTC\";}s:14:\"\0*\0recurrences\";N;s:10:\"\0*\0options\";i:0;s:6:\"\0*\0key\";N;s:10:\"\0*\0current\";N;s:11:\"\0*\0timezone\";N;s:19:\"\0*\0validationResult\";N;s:9:\"\0*\0tzName\";N;s:22:\"\0*\0localMonthsOverflow\";N;s:21:\"\0*\0localYearsOverflow\";N;s:25:\"\0*\0localStrictModeEnabled\";N;s:24:\"\0*\0localHumanDiffOptions\";N;s:22:\"\0*\0localToStringFormat\";N;s:18:\"\0*\0localSerializer\";N;s:14:\"\0*\0localMacros\";N;s:21:\"\0*\0localGenericMacros\";N;s:22:\"\0*\0localFormatFunction\";N;s:18:\"\0*\0localTranslator\";N;}"; $period = unserialize($data); /** @var CarbonPeriod $period */ $period = unserialize(serialize($period)); $this->assertInstanceOf(CarbonPeriod::class, $period); $this->assertSame(Carbon::class, $period->getDateClass()); $this->assertSame(0, $period->getOptions()); $this->assertNull($period->getRecurrences()); $this->assertDate('2018-04-21', $period->getStartDate()); $this->assertDate('2018-04-27', $period->getEndDate()); $this->assertIntervalDuration('3 days', $period->getDateInterval()); $this->assertSame('UTC', $period->current()->tzName); } public function testSerializationFromV2WithImmutableStart(): void { $data = "O:19:\"Carbon\CarbonPeriod\":24:{s:12:\"\0*\0dateClass\";s:13:\"Carbon\Carbon\";s:15:\"\0*\0dateInterval\";O:21:\"Carbon\CarbonInterval\":22:{s:1:\"y\";i:0;s:1:\"m\";i:0;s:1:\"d\";i:3;s:1:\"h\";i:0;s:1:\"i\";i:0;s:1:\"s\";i:0;s:1:\"f\";d:0;s:6:\"invert\";i:0;s:4:\"days\";b:0;s:11:\"from_string\";b:0;s:9:\"\0*\0tzName\";N;s:7:\"\0*\0step\";N;s:22:\"\0*\0localMonthsOverflow\";N;s:21:\"\0*\0localYearsOverflow\";N;s:25:\"\0*\0localStrictModeEnabled\";N;s:24:\"\0*\0localHumanDiffOptions\";N;s:22:\"\0*\0localToStringFormat\";N;s:18:\"\0*\0localSerializer\";N;s:14:\"\0*\0localMacros\";N;s:21:\"\0*\0localGenericMacros\";N;s:22:\"\0*\0localFormatFunction\";N;s:18:\"\0*\0localTranslator\";N;}s:14:\"\0*\0constructed\";b:1;s:20:\"\0*\0isDefaultInterval\";b:0;s:10:\"\0*\0filters\";a:1:{i:0;a:2:{i:0;a:2:{i:0;s:19:\"Carbon\CarbonPeriod\";i:1;s:13:\"filterEndDate\";}i:1;N;}}s:12:\"\0*\0startDate\";O:22:\"Carbon\CarbonImmutable\":3:{s:4:\"date\";s:26:\"2018-04-21 00:00:00.000000\";s:13:\"timezone_type\";i:3;s:8:\"timezone\";s:3:\"UTC\";}s:10:\"\0*\0endDate\";O:13:\"Carbon\Carbon\":3:{s:4:\"date\";s:26:\"2018-04-27 00:00:00.000000\";s:13:\"timezone_type\";i:3;s:8:\"timezone\";s:3:\"UTC\";}s:14:\"\0*\0recurrences\";N;s:10:\"\0*\0options\";i:0;s:6:\"\0*\0key\";N;s:10:\"\0*\0current\";N;s:11:\"\0*\0timezone\";N;s:19:\"\0*\0validationResult\";N;s:9:\"\0*\0tzName\";N;s:22:\"\0*\0localMonthsOverflow\";N;s:21:\"\0*\0localYearsOverflow\";N;s:25:\"\0*\0localStrictModeEnabled\";N;s:24:\"\0*\0localHumanDiffOptions\";N;s:22:\"\0*\0localToStringFormat\";N;s:18:\"\0*\0localSerializer\";N;s:14:\"\0*\0localMacros\";N;s:21:\"\0*\0localGenericMacros\";N;s:22:\"\0*\0localFormatFunction\";N;s:18:\"\0*\0localTranslator\";N;}"; $period = unserialize($data); /** @var CarbonPeriod $period */ $period = unserialize(serialize($period)); $this->assertInstanceOf(CarbonPeriod::class, $period); $this->assertSame(Carbon::class, $period->getDateClass()); $this->assertSame(0, $period->getOptions()); $this->assertNull($period->getRecurrences()); $this->assertDate('2018-04-21', $period->getStartDate(), CarbonImmutable::class); $this->assertDate('2018-04-27', $period->getEndDate()); $this->assertIntervalDuration('3 days', $period->getDateInterval()); $this->assertSame('UTC', $period->current()->tzName); } public function testSerializationFromV2WithRecurrences(): void { $data = 'O:19:"Carbon\\CarbonPeriod":24:{s:12:"'."\0".'*'."\0".'dateClass";s:13:"Carbon\\Carbon";s:15:"'."\0".'*'."\0".'dateInterval";O:21:"Carbon\\CarbonInterval":22:{s:1:"y";i:0;s:1:"m";i:0;s:1:"d";i:0;s:1:"h";i:1;s:1:"i";i:0;s:1:"s";i:0;s:1:"f";d:0;s:6:"invert";i:0;s:4:"days";b:0;s:11:"from_string";b:0;s:9:"'."\0".'*'."\0".'tzName";N;s:7:"'."\0".'*'."\0".'step";N;s:22:"'."\0".'*'."\0".'localMonthsOverflow";N;s:21:"'."\0".'*'."\0".'localYearsOverflow";N;s:25:"'."\0".'*'."\0".'localStrictModeEnabled";N;s:24:"'."\0".'*'."\0".'localHumanDiffOptions";N;s:22:"'."\0".'*'."\0".'localToStringFormat";N;s:18:"'."\0".'*'."\0".'localSerializer";N;s:14:"'."\0".'*'."\0".'localMacros";N;s:21:"'."\0".'*'."\0".'localGenericMacros";N;s:22:"'."\0".'*'."\0".'localFormatFunction";N;s:18:"'."\0".'*'."\0".'localTranslator";N;}s:14:"'."\0".'*'."\0".'constructed";b:1;s:20:"'."\0".'*'."\0".'isDefaultInterval";b:0;s:10:"'."\0".'*'."\0".'filters";a:1:{i:0;a:2:{i:0;a:2:{i:0;s:19:"Carbon\\CarbonPeriod";i:1;s:17:"filterRecurrences";}i:1;N;}}s:12:"'."\0".'*'."\0".'startDate";O:13:"Carbon\\Carbon":3:{s:4:"date";s:26:"2018-05-13 10:30:00.000000";s:13:"timezone_type";i:3;s:8:"timezone";s:11:"Europe/Kyiv";}s:10:"'."\0".'*'."\0".'endDate";N;s:14:"'."\0".'*'."\0".'recurrences";i:3;s:10:"'."\0".'*'."\0".'options";i:3;s:6:"'."\0".'*'."\0".'key";N;s:10:"'."\0".'*'."\0".'current";N;s:11:"'."\0".'*'."\0".'timezone";s:11:"Europe/Kyiv";s:19:"'."\0".'*'."\0".'validationResult";N;s:9:"'."\0".'*'."\0".'tzName";s:11:"Europe/Kyiv";s:22:"'."\0".'*'."\0".'localMonthsOverflow";N;s:21:"'."\0".'*'."\0".'localYearsOverflow";N;s:25:"'."\0".'*'."\0".'localStrictModeEnabled";N;s:24:"'."\0".'*'."\0".'localHumanDiffOptions";N;s:22:"'."\0".'*'."\0".'localToStringFormat";N;s:18:"'."\0".'*'."\0".'localSerializer";N;s:14:"'."\0".'*'."\0".'localMacros";N;s:21:"'."\0".'*'."\0".'localGenericMacros";N;s:22:"'."\0".'*'."\0".'localFormatFunction";N;s:18:"'."\0".'*'."\0".'localTranslator";N;}'; $period = unserialize($data); /** @var CarbonPeriod $period */ $period = unserialize(serialize($period)); $this->assertInstanceOf(CarbonPeriod::class, $period); $this->assertSame(Carbon::class, $period->getDateClass()); $this->assertSame(3, $period->getOptions()); $this->assertSame(3, $period->getRecurrences()); $this->assertDate('2018-05-13T10:30:00+03:00', $period->getStartDate()); $this->assertNull($period->getEndDate()); $this->assertIntervalDuration('1 hour', $period->getDateInterval()); $this->assertSame('Europe/Kyiv', $period->current()->tzName); } public function testSerializationFromV2WithTimezone(): void { $data = 'O:19:"Carbon\\CarbonPeriod":24:{s:12:"'."\0".'*'."\0".'dateClass";s:13:"Carbon\\Carbon";s:15:"'."\0".'*'."\0".'dateInterval";O:21:"Carbon\\CarbonInterval":22:{s:1:"y";i:0;s:1:"m";i:0;s:1:"d";i:0;s:1:"h";i:1;s:1:"i";i:0;s:1:"s";i:0;s:1:"f";d:0;s:6:"invert";i:0;s:4:"days";b:0;s:11:"from_string";b:0;s:9:"'."\0".'*'."\0".'tzName";N;s:7:"'."\0".'*'."\0".'step";N;s:22:"'."\0".'*'."\0".'localMonthsOverflow";N;s:21:"'."\0".'*'."\0".'localYearsOverflow";N;s:25:"'."\0".'*'."\0".'localStrictModeEnabled";N;s:24:"'."\0".'*'."\0".'localHumanDiffOptions";N;s:22:"'."\0".'*'."\0".'localToStringFormat";N;s:18:"'."\0".'*'."\0".'localSerializer";N;s:14:"'."\0".'*'."\0".'localMacros";N;s:21:"'."\0".'*'."\0".'localGenericMacros";N;s:22:"'."\0".'*'."\0".'localFormatFunction";N;s:18:"'."\0".'*'."\0".'localTranslator";N;}s:14:"'."\0".'*'."\0".'constructed";b:1;s:20:"'."\0".'*'."\0".'isDefaultInterval";b:0;s:10:"'."\0".'*'."\0".'filters";a:1:{i:0;a:2:{i:0;a:2:{i:0;s:19:"Carbon\\CarbonPeriod";i:1;s:17:"filterRecurrences";}i:1;N;}}s:12:"'."\0".'*'."\0".'startDate";O:13:"Carbon\\Carbon":3:{s:4:"date";s:26:"2018-05-13 10:30:00.000000";s:13:"timezone_type";i:3;s:8:"timezone";s:11:"Europe/Kyiv";}s:10:"'."\0".'*'."\0".'endDate";N;s:14:"'."\0".'*'."\0".'recurrences";i:8;s:10:"'."\0".'*'."\0".'options";i:3;s:6:"'."\0".'*'."\0".'key";i:1;s:10:"'."\0".'*'."\0".'current";O:13:"Carbon\\Carbon":3:{s:4:"date";s:26:"2018-05-13 09:30:00.000000";s:13:"timezone_type";i:3;s:8:"timezone";s:3:"UTC";}s:11:"'."\0".'*'."\0".'timezone";O:21:"Carbon\\CarbonTimeZone":2:{s:13:"timezone_type";i:3;s:8:"timezone";s:11:"Europe/Kyiv";}s:19:"'."\0".'*'."\0".'validationResult";b:1;s:9:"'."\0".'*'."\0".'tzName";s:11:"Europe/Kyiv";s:22:"'."\0".'*'."\0".'localMonthsOverflow";N;s:21:"'."\0".'*'."\0".'localYearsOverflow";N;s:25:"'."\0".'*'."\0".'localStrictModeEnabled";N;s:24:"'."\0".'*'."\0".'localHumanDiffOptions";N;s:22:"'."\0".'*'."\0".'localToStringFormat";N;s:18:"'."\0".'*'."\0".'localSerializer";N;s:14:"'."\0".'*'."\0".'localMacros";N;s:21:"'."\0".'*'."\0".'localGenericMacros";N;s:22:"'."\0".'*'."\0".'localFormatFunction";N;s:18:"'."\0".'*'."\0".'localTranslator";N;}'; $period = unserialize($data); /** @var CarbonPeriod $period */ $period = unserialize(serialize($period)); $this->assertInstanceOf(CarbonPeriod::class, $period); $this->assertSame(Carbon::class, $period->getDateClass()); $this->assertSame(3, $period->getOptions()); $this->assertSame(8, $period->getRecurrences()); $this->assertDate('2018-05-13T10:30:00+03:00', $period->getStartDate()); $this->assertNull($period->getEndDate()); $this->assertIntervalDuration('1 hour', $period->getDateInterval()); $this->assertSame('Europe/Kyiv', $period->current()->tzName); } public function testSerializationFromV2WithCurrent(): void { $data = 'O:19:"Carbon\\CarbonPeriod":24:{s:12:"'."\0".'*'."\0".'dateClass";s:22:"Carbon\\CarbonImmutable";s:15:"'."\0".'*'."\0".'dateInterval";O:21:"Carbon\\CarbonInterval":22:{s:1:"y";i:0;s:1:"m";i:0;s:1:"d";i:1;s:1:"h";i:0;s:1:"i";i:0;s:1:"s";i:0;s:1:"f";d:0;s:6:"invert";i:0;s:4:"days";b:0;s:11:"from_string";b:0;s:9:"'."\0".'*'."\0".'tzName";N;s:7:"'."\0".'*'."\0".'step";N;s:22:"'."\0".'*'."\0".'localMonthsOverflow";N;s:21:"'."\0".'*'."\0".'localYearsOverflow";N;s:25:"'."\0".'*'."\0".'localStrictModeEnabled";N;s:24:"'."\0".'*'."\0".'localHumanDiffOptions";N;s:22:"'."\0".'*'."\0".'localToStringFormat";N;s:18:"'."\0".'*'."\0".'localSerializer";N;s:14:"'."\0".'*'."\0".'localMacros";N;s:21:"'."\0".'*'."\0".'localGenericMacros";N;s:22:"'."\0".'*'."\0".'localFormatFunction";N;s:18:"'."\0".'*'."\0".'localTranslator";N;}s:14:"'."\0".'*'."\0".'constructed";b:1;s:20:"'."\0".'*'."\0".'isDefaultInterval";b:0;s:10:"'."\0".'*'."\0".'filters";a:1:{i:0;a:2:{i:0;a:2:{i:0;s:19:"Carbon\\CarbonPeriod";i:1;s:13:"filterEndDate";}i:1;N;}}s:12:"'."\0".'*'."\0".'startDate";O:13:"Carbon\\Carbon":3:{s:4:"date";s:26:"2030-01-02 00:00:00.000000";s:13:"timezone_type";i:3;s:8:"timezone";s:15:"America/Toronto";}s:10:"'."\0".'*'."\0".'endDate";O:13:"Carbon\\Carbon":3:{s:4:"date";s:26:"2030-01-21 00:00:00.000000";s:13:"timezone_type";i:3;s:8:"timezone";s:15:"America/Toronto";}s:14:"'."\0".'*'."\0".'recurrences";N;s:10:"'."\0".'*'."\0".'options";i:4;s:6:"'."\0".'*'."\0".'key";N;s:10:"'."\0".'*'."\0".'current";N;s:11:"'."\0".'*'."\0".'timezone";N;s:19:"'."\0".'*'."\0".'validationResult";N;s:9:"'."\0".'*'."\0".'tzName";N;s:22:"'."\0".'*'."\0".'localMonthsOverflow";N;s:21:"'."\0".'*'."\0".'localYearsOverflow";N;s:25:"'."\0".'*'."\0".'localStrictModeEnabled";N;s:24:"'."\0".'*'."\0".'localHumanDiffOptions";N;s:22:"'."\0".'*'."\0".'localToStringFormat";N;s:18:"'."\0".'*'."\0".'localSerializer";N;s:14:"'."\0".'*'."\0".'localMacros";N;s:21:"'."\0".'*'."\0".'localGenericMacros";N;s:22:"'."\0".'*'."\0".'localFormatFunction";N;s:18:"'."\0".'*'."\0".'localTranslator";N;}'; $period = unserialize($data); /** @var CarbonPeriod $period */ $period = unserialize(serialize($period)); $this->assertInstanceOf(CarbonPeriod::class, $period); $this->assertSame(CarbonImmutable::class, $period->getDateClass()); $this->assertNull($period->getRecurrences()); $this->assertDate('2030-01-02T00:00:00-05:00', $period->getStartDate()); $this->assertDate('2030-01-21T00:00:00-05:00', $period->getEndDate()); $this->assertIntervalDuration('1 day', $period->getDateInterval()); $this->assertSame('America/Toronto', $period->current()->tzName); } public function testSerializationFromV2WithDateTimeObject(): void { $data = 'O:19:"Carbon\\CarbonPeriod":7:{s:5:"start";O:8:"DateTime":3:{s:4:"date";s:26:"2030-01-02 00:00:00.000000";s:13:"timezone_type";i:3;s:8:"timezone";s:15:"America/Toronto";}s:7:"current";N;s:3:"end";O:8:"DateTime":3:{s:4:"date";s:26:"2030-01-21 00:00:00.000000";s:13:"timezone_type";i:3;s:8:"timezone";s:15:"America/Toronto";}s:8:"interval";O:12:"DateInterval":10:{s:1:"y";i:0;s:1:"m";i:0;s:1:"d";i:1;s:1:"h";i:0;s:1:"i";i:0;s:1:"s";i:0;s:1:"f";d:0;s:6:"invert";i:0;s:4:"days";b:0;s:11:"from_string";b:0;}s:11:"recurrences";i:1;s:18:"include_start_date";b:1;s:16:"include_end_date";b:0;}'; $period = unserialize($data); /** @var CarbonPeriod $period */ $period = unserialize(serialize($period)); $this->assertInstanceOf(CarbonPeriod::class, $period); $this->assertSame(Carbon::class, $period->getDateClass()); $this->assertNull($period->getRecurrences()); $this->assertDate('2030-01-02T00:00:00-05:00', $period->getStartDate()); $this->assertDate('2030-01-21T00:00:00-05:00', $period->getEndDate()); $this->assertIntervalDuration('1 day', $period->getDateInterval()); $this->assertNull($period->current()); } public function testSerializationFromV2WithDateTimeImmutableObject(): void { $data = 'O:19:"Carbon\\CarbonPeriod":7:{s:5:"start";O:17:"DateTimeImmutable":3:{s:4:"date";s:26:"2030-01-02 00:00:00.000000";s:13:"timezone_type";i:3;s:8:"timezone";s:15:"America/Toronto";}s:7:"current";N;s:3:"end";O:17:"DateTimeImmutable":3:{s:4:"date";s:26:"2030-01-21 00:00:00.000000";s:13:"timezone_type";i:3;s:8:"timezone";s:15:"America/Toronto";}s:8:"interval";O:12:"DateInterval":10:{s:1:"y";i:0;s:1:"m";i:0;s:1:"d";i:1;s:1:"h";i:0;s:1:"i";i:0;s:1:"s";i:0;s:1:"f";d:0;s:6:"invert";i:0;s:4:"days";b:0;s:11:"from_string";b:0;}s:11:"recurrences";i:1;s:18:"include_start_date";b:1;s:16:"include_end_date";b:0;}'; $period = unserialize($data); /** @var CarbonPeriod $period */ $period = unserialize(serialize($period)); $this->assertInstanceOf(CarbonPeriod::class, $period); $this->assertNull($period->getRecurrences()); $this->assertDate('2030-01-02T00:00:00-05:00', $period->getStartDate(), CarbonImmutable::class); $this->assertDate('2030-01-21T00:00:00-05:00', $period->getEndDate(), CarbonImmutable::class); $this->assertIntervalDuration('1 day', $period->getDateInterval()); $this->assertNull($period->current()); } #[DataProvider('getCarbonPeriods')] public function testSerialization(CarbonPeriod $period): void { $this->assertSerializationWorks($period); } /** * @SuppressWarnings(MissingImport) */ public function testUnserializeError(): void { $this->expectExceptionMessage( PHP_VERSION_ID < 8_02_00 ? 'Disallowed' : 'Invalid serialization data for DatePeriod object', ); if (!class_exists('CarbonDisallowingToDateTime')) { eval(' class CarbonDisallowingToDateTime extends \Carbon\Carbon { public function toDateTime(): DateTime { throw new LogicException("Disallowed"); } } '); } $periodClass = static::$periodClass; /** @var CarbonPeriod $period */ $period = new $periodClass(); $period->__unserialize([ /* @phpstan-ignore-next-line */ 'start' => new CarbonDisallowingToDateTime('2030-01-02 UTC'), /* @phpstan-ignore-next-line */ 'end' => new CarbonDisallowingToDateTime('2030-01-10 UTC'), 'interval' => new DateInterval('PT12H'), ]); } public static function getCarbonPeriods(): array { $periodClass = static::$periodClass; return [ 'new' => [new $periodClass()], 'range string' => [$periodClass::createFromIso('2023-07-01T00:00:00Z/P7D/2023-11-01T00:00:00Z')], 'include start and end' => [$periodClass::options(0)], 'exclude start and end' => [$periodClass::options($periodClass::EXCLUDE_START_DATE | $periodClass::EXCLUDE_END_DATE)], 'with timezone' => [ $periodClass::createFromIso('2023-07-01T00:00:00Z/P7D/2023-11-01T00:00:00Z') ->setTimezone('Europe/Kyiv'), ], ]; } public function testSerializationWithRecurrences(): void { $periodClass = static::$periodClass; $period = $periodClass::createFromISO8601String('R4/2023-07-01T00:00:00Z/P7D'); $this->assertInstanceOf(CarbonPeriod::class, $period); $this->assertDate('2023-07-01', $period->getStartDate()); $this->assertNull($period->getEndDate()); $this->assertSame(4, $period->getRecurrences()); $this->assertIntervalDuration('1 week', $period->getDateInterval()); $periodCopy = unserialize(serialize($period)); $this->assertEquivalentPeriods($period, $periodCopy); $this->assertDate('2023-07-01', $periodCopy->getStartDate()); $this->assertNull($periodCopy->getEndDate()); $this->assertSame(4, $periodCopy->getRecurrences()); $this->assertIntervalDuration('1 week', $periodCopy->getDateInterval()); } private function assertIntervalDuration(string $duration, mixed $interval): void { $this->assertInstanceOf(CarbonInterval::class, $interval); $this->assertSame($duration, $interval->forHumans()); } private function assertDate(string $date, mixed $value, string $class = Carbon::class): void { if (\strlen($date) === 10) { $date .= 'T00:00:00'; } if (\strlen($date) === 19) { $date .= '+00:00'; } $this->assertInstanceOf($class, $value); $this->assertSame($date, $value->toIso8601String()); } private function assertSerializationWorks(CarbonPeriod $period): void { $periodCopy = unserialize(serialize($period)); $this->assertEquivalentPeriods($period, $periodCopy); } private function assertEquivalentPeriods(mixed $a, mixed $b): void { $this->assertInstanceOf(CarbonPeriod::class, $b); $this->assertSame($a::class, $b::class); if (PHP_VERSION_ID >= 8_02_00) { $this->assertEquals($a, $b); return; } $this->assertEquals($a->getStartDate(), $b->getStartDate()); $this->assertEquals($a->getDateInterval(), $b->getDateInterval()); $this->assertEquals($a->getEndDate(), $b->getEndDate()); $this->assertEquals($a->getRecurrences(), $b->getRecurrences()); $this->assertEquals($a->getOptions(), $b->getOptions()); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriod/Fixtures/CarbonPeriodFactory.php
tests/CarbonPeriod/Fixtures/CarbonPeriodFactory.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonPeriod\Fixtures; use Carbon\CarbonPeriod; class CarbonPeriodFactory { /** * @template T of CarbonPeriod * * @param class-string<T> $periodClass * * @return T */ public static function withStartIntervalEnd(string $periodClass) { return $periodClass::create( '2012-07-01 17:30:00', 'P3DT5H', '2012-07-15 11:15:00', ); } /** * @template T of CarbonPeriod * * @param class-string<T> $periodClass * * @return T */ public static function withEvenDaysFilter(string $periodClass) { $period = $periodClass::create( '2012-07-01', 'P3D', '2012-07-22', $periodClass::EXCLUDE_END_DATE, ); return $period->addFilter(function ($date) { return $date->day % 2 == 0; }); } /** * @template T of CarbonPeriod * * @param class-string<T> $periodClass * * @return T */ public static function withCounter(string $periodClass, &$counter) { $counter = 0; $period = $periodClass::create( '2012-10-01', 3, ); return $period->addFilter(function () use (&$counter) { $counter++; return true; }); } /** * @template T of CarbonPeriod * * @param class-string<T> $periodClass * * @return T */ public static function withStackFilter(string $periodClass) { $period = $periodClass::create( '2001-01-01', ); $stack = [ true, false, true, $periodClass::END_ITERATION, false, false, true, true, $periodClass::END_ITERATION, ]; return $period->addFilter(function () use (&$stack) { return array_shift($stack); }); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriod/Fixtures/FooFilters.php
tests/CarbonPeriod/Fixtures/FooFilters.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonPeriod\Fixtures; class FooFilters { public function bar($date) { return $date->day % 2 === 0; } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriod/Fixtures/MacroableClass.php
tests/CarbonPeriod/Fixtures/MacroableClass.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonPeriod\Fixtures; use BadMethodCallException; use Carbon\Traits\LocalFactory; use Carbon\Traits\Macro; use Closure; class MacroableClass { use LocalFactory; use Macro; public $endDate; protected array $localMacros = []; public function getEndDate() { return $this->endDate; } public function setEndDate($endDate) { $this->endDate = $endDate; return $this; } public function cast($className) { $new = new $className(); return $new->setEndDate($this->endDate); } public function __call($method, $parameters) { $macro = static::getMacro($method) ?? null; if ($macro instanceof Closure) { return $macro->call($this); } throw new BadMethodCallException("$method not found"); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriod/Fixtures/MixinTrait.php
tests/CarbonPeriod/Fixtures/MixinTrait.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonPeriod\Fixtures; trait MixinTrait { public function oneMoreDay() { return $this->setEndDate($this->endNextDay()); } public function endNextDay() { return $this->getEndDate()->addDay(); } public function copyOneMoreDay() { return $this->copy()->oneMoreDay(); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriod/Fixtures/AbstractCarbon.php
tests/CarbonPeriod/Fixtures/AbstractCarbon.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonPeriod\Fixtures; use Carbon\CarbonInterface; use Carbon\CarbonInterval; use DateTime; use ReturnTypeWillChange; abstract class AbstractCarbon extends DateTime implements CarbonInterface { public function __construct($time = null, $timezone = null) { parent::__construct($time, $timezone); } public static function __set_state($dump): static { return new static($dump); } #[ReturnTypeWillChange] public function add($unit, $value = 1, ?bool $overflow = null): static { return parent::add($unit); } #[ReturnTypeWillChange] public function sub($unit, $value = 1, ?bool $overflow = null): static { return parent::sub($unit); } #[ReturnTypeWillChange] public function diff($date = null, $absolute = false): CarbonInterval { return CarbonInterval::instance(parent::diff($date, $absolute)); } #[ReturnTypeWillChange] public function modify($modify) { return parent::modify($modify); } public function setDate(int $year, int $month, int $day): static { return parent::setDate($year, $month, $day); } public function setISODate(int $year, int $week, int $day = 1): static { return parent::setISODate($year, $week, $day); } public function setTime($hour, $minute, $second = 0, $microsecond = 0): static { return parent::setTime($hour, $minute, $second, $microsecond); } public function setTimestamp(int|string|float $timestamp): static { return parent::setTimestamp($timestamp); } public function setTimezone(\DateTimeZone|string|int $timeZone): static { return parent::setTimezone($timeZone); } public static function createFromFormat($format, $time, $tz = null): static { return parent::createFromFormat($format, $time, $tz); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriod/Fixtures/Mixin.php
tests/CarbonPeriod/Fixtures/Mixin.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonPeriod\Fixtures; class Mixin { public $foo; public function setFoo() { $mixin = $this; return function ($value) use ($mixin) { $mixin->foo = $value; }; } public function getFoo() { $mixin = $this; return function () use ($mixin) { return $mixin->foo; }; } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriod/Fixtures/filters.php
tests/CarbonPeriod/Fixtures/filters.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Carbon\Carbon; function foobar_filter($date) { return $date < Carbon::parse('2017-03-13') || $date > Carbon::parse('2017-03-14'); }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Doctrine/CarbonTypesTest.php
tests/Doctrine/CarbonTypesTest.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\Doctrine; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\Doctrine\CarbonImmutableType; use Carbon\Doctrine\CarbonType; use Carbon\Doctrine\CarbonTypeConverter; use Carbon\Doctrine\DateTimeDefaultPrecision; use Carbon\Doctrine\DateTimeImmutableType; use Carbon\Doctrine\DateTimeType; use DateTimeImmutable; use Doctrine\DBAL\Platforms\AbstractMySQLPlatform; use Doctrine\DBAL\Platforms\DB2Platform; use Doctrine\DBAL\Platforms\MySQL57Platform; use Doctrine\DBAL\Platforms\MySQLPlatform; use Doctrine\DBAL\Types\ConversionException; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Group; use Tests\AbstractTestCase; use Tests\Fixtures\CarbonTypeCase; class CarbonTypesTest extends AbstractTestCase { private static ?array $types = null; public static function setUpBeforeClass(): void { foreach (static::dataForTypes() as [$case]) { $case->initialize(); } } public static function dataForTypes(): array { return self::$types ??= self::generateDataForTypes(); } #[Group('doctrine')] #[DataProvider('dataForTypes')] public function testGetSQLDeclaration(CarbonTypeCase $case): void { $type = $case->getType(); $adaptPrecisionToPlatform = method_exists(CarbonTypeConverter::class, 'getMaximumPrecision'); $precision = DateTimeDefaultPrecision::get(); $this->assertSame(6, $precision); $supportZeroPrecision = self::supportsZeroPrecision(); $this->assertSame('DATETIME', $type->getSQLDeclaration($supportZeroPrecision ? [ 'precision' => 0, ] : [ 'precision' => null, 'secondPrecision' => true, ], $this->getMySQLPlatform())); $this->assertSame('DATETIME(3)', $type->getSQLDeclaration([ 'precision' => 3, ], $this->getMySQLPlatform())); $this->assertSame('TIMESTAMP(0)', $type->getSQLDeclaration($supportZeroPrecision ? [ 'precision' => 0, ] : [ 'precision' => null, 'secondPrecision' => true, ], new DB2Platform())); $this->assertSame('TIMESTAMP(6)', $type->getSQLDeclaration([ 'precision' => null, ], new DB2Platform())); $this->assertSame('TIMESTAMP(6)', $type->getSQLDeclaration($supportZeroPrecision ? [ 'precision' => null, ] : [ 'precision' => 0, ], new DB2Platform())); $this->assertSame('DATETIME(6)', $type->getSQLDeclaration($supportZeroPrecision ? [ 'precision' => null, ] : [ 'precision' => 0, ], $this->getMySQLPlatform())); $this->assertSame('DATETIME(6)', $type->getSQLDeclaration([ 'precision' => null, ], $this->getMySQLPlatform())); DateTimeDefaultPrecision::set(4); $this->assertSame('DATETIME(4)', $type->getSQLDeclaration([ 'precision' => null, ], $this->getMySQLPlatform())); DateTimeDefaultPrecision::set(9); $this->assertSame($adaptPrecisionToPlatform ? 'DATETIME(6)' : 'DATETIME(9)', $type->getSQLDeclaration([ 'precision' => null, ], $this->getMySQLPlatform())); DateTimeDefaultPrecision::set(0); $this->assertSame('DATETIME', $type->getSQLDeclaration([ 'precision' => null, ], $this->getMySQLPlatform())); DateTimeDefaultPrecision::set($precision); } #[Group('doctrine')] #[DataProvider('dataForTypes')] public function testConvertToPHPValue(CarbonTypeCase $case): void { $type = $case->getType(); $this->assertNull($type->convertToPHPValue(null, $this->getMySQLPlatform())); $date = $type->convertToPHPValue(Carbon::parse('2020-06-23 18:47'), $this->getMySQLPlatform()); $this->assertInstanceOf($case->class, $date); $this->assertSame('2020-06-23 18:47:00.000000', $date->format('Y-m-d H:i:s.u')); $date = $type->convertToPHPValue(new DateTimeImmutable('2020-06-23 18:47'), $this->getMySQLPlatform()); $this->assertInstanceOf($case->class, $date); $this->assertSame('2020-06-23 18:47:00.000000', $date->format('Y-m-d H:i:s.u')); $date = $type->convertToPHPValue('2020-06-23 18:47', $this->getMySQLPlatform()); $this->assertInstanceOf($case->class, $date); $this->assertSame('2020-06-23 18:47:00.000000', $date->format('Y-m-d H:i:s.u')); } #[Group('doctrine')] #[DataProvider('dataForTypes')] public function testConvertToPHPValueFailure(CarbonTypeCase $case): void { $conversion = version_compare(self::getDbalVersion(), '4.0.0', '>=') ? "to \"$case->typeClass\" as an error was triggered by the unserialization: " : "\"2020-0776-23 18:47\" to Doctrine Type $case->name. Expected format: "; $this->expectExceptionObject(new ConversionException( 'Could not convert database value '.$conversion. "Y-m-d H:i:s.u or any format supported by $case->class::parse()", )); $case->getType()->convertToPHPValue('2020-0776-23 18:47', $this->getMySQLPlatform()); } #[Group('doctrine')] #[DataProvider('dataForTypes')] public function testConvertToDatabaseValue(CarbonTypeCase $case): void { $type = $case->getType(); $this->assertNull($type->convertToDatabaseValue(null, $this->getMySQLPlatform())); $this->assertSame( '2020-06-23 18:47:00.000000', $type->convertToDatabaseValue(new DateTimeImmutable('2020-06-23 18:47'), $this->getMySQLPlatform()), ); } #[Group('doctrine')] #[DataProvider('dataForTypes')] public function testConvertToDatabaseValueFailure(CarbonTypeCase $case): void { $quote = class_exists('Doctrine\\DBAL\\Version') ? "'" : ''; $conversion = version_compare(self::getDbalVersion(), '4.0.0', '>=') ? "array to type $case->typeClass. " : "{$quote}array{$quote} to type {$quote}$case->name{$quote}. "; $this->expectExceptionObject(new ConversionException( 'Could not convert PHP value of type '.$conversion. 'Expected one of the following types: null, DateTime, Carbon', )); $case->getType()->convertToDatabaseValue([2020, 06, 23], $this->getMySQLPlatform()); } #[Group('doctrine')] #[DataProvider('dataForTypes')] public function testRequiresSQLCommentHint(CarbonTypeCase $case): void { if (version_compare(self::getDbalVersion(), '4.0.0', '>=')) { $this->markTestSkipped('requiresSQLCommentHint dropped since DBAL 4'); } $this->assertSame( $case->hintRequired, $case->getType()->requiresSQLCommentHint($this->getMySQLPlatform()), ); } private static function getDbalVersion(): string { static $dbalVersion = null; if ($dbalVersion === null) { $installed = require __DIR__.'/../../vendor/composer/installed.php'; $dbalVersion = $installed['versions']['doctrine/dbal']['version'] ?? '2.0.0'; } return $dbalVersion; } private static function supportsZeroPrecision(): bool { return version_compare(self::getDbalVersion(), '3.7.0', '>='); } private function getMySQLPlatform(): AbstractMySQLPlatform { return class_exists(MySQLPlatform::class) ? new MySQLPlatform() : new MySQL57Platform(); } private static function generateDataForTypes(): array { $supportZeroPrecision = self::supportsZeroPrecision(); $types = [ [new CarbonTypeCase($supportZeroPrecision ? 'date_time' : 'datetime', Carbon::class, DateTimeType::class, false)], [new CarbonTypeCase($supportZeroPrecision ? 'date_time_immutable' : 'datetime_immutable', CarbonImmutable::class, DateTimeImmutableType::class, true)], [new CarbonTypeCase('carbon', Carbon::class, CarbonType::class, !$supportZeroPrecision)], [new CarbonTypeCase('carbon_immutable', CarbonImmutable::class, CarbonImmutableType::class, true)], ]; return array_combine(array_column($types, 0), $types); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonInterval/StrictModeTest.php
tests/CarbonInterval/StrictModeTest.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonInterval; use BadMethodCallException; use Carbon\Carbon; use Carbon\CarbonInterval; use InvalidArgumentException; use Tests\AbstractTestCase; class StrictModeTest extends AbstractTestCase { public function testSetWithStrictMode() { $this->expectExceptionObject(new InvalidArgumentException( 'Unknown setter \'foobar\'', )); /** @var mixed $interval */ $interval = CarbonInterval::day(); $interval->foobar = 'biz'; } public function testGetWithStrictMode() { $this->expectExceptionObject(new InvalidArgumentException( 'Unknown getter \'foobar\'', )); /** @var mixed $interval */ $interval = CarbonInterval::day(); $interval->foobar; } public function testSetAndGetWithoutStrictMode() { Carbon::useStrictMode(false); /** @var mixed $interval */ $interval = CarbonInterval::day(); @$interval->foobar = 'biz'; $this->assertSame('biz', $interval->foobar); } public function testStaticCallWithStrictMode() { $this->expectExceptionObject(new BadMethodCallException( 'Unknown fluent constructor \'foobar\'', )); CarbonInterval::foobar(); } public function testStaticCallWithoutStrictMode() { Carbon::useStrictMode(false); $this->assertNull(CarbonInterval::foobar()); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonInterval/CloneTest.php
tests/CarbonInterval/CloneTest.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonInterval; use Carbon\CarbonInterval; use Tests\AbstractTestCase; class CloneTest extends AbstractTestCase { public function testClone() { $first = CarbonInterval::minute(); $second = $first->clone(); $result = $first->compare($second); $this->assertSame(0, $result); $this->assertNotSame($second, $first); $this->assertEquals($second, $first); } public function testCopy() { $first = CarbonInterval::minute(); $second = $first->copy(); $result = $first->compare($second); $this->assertSame(0, $result); $this->assertNotSame($second, $first); $this->assertEquals($second, $first); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonInterval/ConstructTest.php
tests/CarbonInterval/ConstructTest.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonInterval; use BadMethodCallException; use Carbon\Carbon; use Carbon\CarbonInterval; use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\OutOfRangeException; use Carbon\Unit; use DateInterval; use Exception; use Tests\AbstractTestCase; class ConstructTest extends AbstractTestCase { public function testInheritedConstruct() { /** @phpstan-var CarbonInterval $ci */ $ci = CarbonInterval::createFromDateString('1 hour'); $this->assertSame('PT1H', $ci->spec()); $ci = new CarbonInterval('PT0S'); $this->assertInstanceOf(CarbonInterval::class, $ci); $this->assertInstanceOf(DateInterval::class, $ci); $this->assertSame('PT0S', $ci->spec()); $ci = new CarbonInterval('P1Y2M3D'); $this->assertSame('P1Y2M3D', $ci->spec()); $ci = CarbonInterval::create('PT0S'); $this->assertSame('PT0S', $ci->spec()); $ci = CarbonInterval::create('P1Y2M3D'); $this->assertSame('P1Y2M3D', $ci->spec()); $ci = CarbonInterval::create('P1Y2M3.0D'); $this->assertSame('P1Y2M3D', $ci->spec()); $ci = CarbonInterval::create('PT9.5H+85M'); $this->assertSame('PT9H115M', $ci->spec()); $ci = CarbonInterval::create('PT9H+85M'); $this->assertSame('PT9H85M', $ci->spec()); $ci = CarbonInterval::create('PT1999999999999.5H+85M'); $this->assertSame('PT1999999999999H115M', $ci->spec()); } public function testConstructWithDateInterval() { $month = (PHP_VERSION_ID === 8_03_20) ? 6 : -6; // PHP 8.3.20 triggers segfault with negative or zero values $ci = new CarbonInterval(new DateInterval('P1Y2M3D')); $this->assertSame('P1Y2M3D', $ci->spec()); $interval = new DateInterval('P1Y2M3D'); $interval->m = $month; $interval->invert = 1; $ci = new CarbonInterval($interval); $this->assertSame(1, $ci->y); $this->assertSame($month, $ci->m); $this->assertSame(3, $ci->d); $this->assertSame(1, $ci->invert); } public function testDefaults() { $ci = new CarbonInterval(); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 0, 0, 0, 0); } public function testNulls() { $ci = new CarbonInterval(null, null, null, null, null, null); $this->assertCarbonInterval($ci, 0, 0, 0, 0, 0, 0); $ci = CarbonInterval::days(null); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 0, 0, 0, 0); } public function testZeroes() { $ci = new CarbonInterval(0, 0, 0, 0, 0, 0); $this->assertCarbonInterval($ci, 0, 0, 0, 0, 0, 0); $ci = CarbonInterval::days(0); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 0, 0, 0, 0); } public function testZeroesChained() { $ci = CarbonInterval::days(0)->week(0)->minutes(0); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 0, 0, 0, 0); } public function testYears() { $ci = new CarbonInterval(1); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 1, 0, 0, 0, 0, 0); $ci = CarbonInterval::years(2); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 2, 0, 0, 0, 0, 0); $ci = CarbonInterval::year(); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 1, 0, 0, 0, 0, 0); $ci = CarbonInterval::year(3); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 3, 0, 0, 0, 0, 0); } public function testMonths() { $ci = new CarbonInterval(0, 1); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 1, 0, 0, 0, 0); $ci = CarbonInterval::months(2); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 2, 0, 0, 0, 0); $ci = CarbonInterval::month(); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 1, 0, 0, 0, 0); $ci = CarbonInterval::month(3); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 3, 0, 0, 0, 0); } public function testWeeks() { $ci = new CarbonInterval(0, 0, 1); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 7, 0, 0, 0); $ci = CarbonInterval::weeks(2); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 14, 0, 0, 0); $ci = CarbonInterval::week(); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 7, 0, 0, 0); $ci = CarbonInterval::week(3); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 21, 0, 0, 0); } public function testDays() { $ci = new CarbonInterval(0, 0, 0, 1); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 1, 0, 0, 0); $ci = CarbonInterval::days(2); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 2, 0, 0, 0); $ci = CarbonInterval::dayz(2); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 2, 0, 0, 0); $ci = CarbonInterval::day(); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 1, 0, 0, 0); $ci = CarbonInterval::day(3); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 3, 0, 0, 0); } public function testHours() { $ci = new CarbonInterval(0, 0, 0, 0, 1); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 0, 1, 0, 0); $ci = CarbonInterval::hours(2); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 0, 2, 0, 0); $ci = CarbonInterval::hour(); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 0, 1, 0, 0); $ci = CarbonInterval::hour(3); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 0, 3, 0, 0); } public function testMinutes() { $ci = new CarbonInterval(0, 0, 0, 0, 0, 1); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 0, 0, 1, 0); $ci = CarbonInterval::minutes(2); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 0, 0, 2, 0); $ci = CarbonInterval::minute(); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 0, 0, 1, 0); $ci = CarbonInterval::minute(3); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 0, 0, 3, 0); } public function testSeconds() { $ci = new CarbonInterval(0, 0, 0, 0, 0, 0, 1); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 0, 0, 0, 1); $ci = CarbonInterval::seconds(2); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 0, 0, 0, 2); $ci = CarbonInterval::second(); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 0, 0, 0, 1); $ci = CarbonInterval::second(3); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 0, 0, 0, 3); } public function testMilliseconds() { $ci = CarbonInterval::milliseconds(2); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 0, 0, 0, 0); $this->assertSame(2, $ci->milliseconds); $ci = CarbonInterval::millisecond(); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 0, 0, 0, 0); $this->assertSame(1, $ci->milliseconds); } public function testMicroseconds() { $ci = CarbonInterval::microseconds(2); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 0, 0, 0, 0); $this->assertSame(2, $ci->microseconds); $ci = CarbonInterval::microsecond(); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 0, 0, 0, 0); $this->assertSame(1, $ci->microseconds); } public function testYearsAndHours() { $ci = new CarbonInterval(5, 0, 0, 0, 3, 0, 0); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 5, 0, 0, 3, 0, 0); } public function testAll() { $ci = new CarbonInterval(5, 6, 2, 5, 9, 10, 11); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 5, 6, 19, 9, 10, 11); } public function testAllWithCreate() { $ci = CarbonInterval::create(5, 6, 2, 5, 9, 10, 11); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 5, 6, 19, 9, 10, 11); } public function testInstance() { $ci = CarbonInterval::instance(new DateInterval('P2Y1M5DT22H33M44S')); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 2, 1, 5, 22, 33, 44); $this->assertFalse($ci->days); } public function testInstanceWithSkipCopy() { $ci = CarbonInterval::instance(new DateInterval('P2Y1M5DT22H33M44S')); $copy = CarbonInterval::instance($ci, [], true); $this->assertSame($ci, $copy); } public function testInstanceWithNegativeDateInterval() { $di = new DateInterval('P2Y1M5DT22H33M44S'); $di->invert = 1; $ci = CarbonInterval::instance($di); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 2, 1, 5, 22, 33, 44); $this->assertFalse($ci->days); $this->assertSame(1, $ci->invert); } public function testInstanceWithDays() { $expectedDiff = PHP_VERSION_ID < 8_02_00 ? false : 21; $diff = Carbon::now()->diffAsDateInterval(Carbon::now()->addWeeks(3)); $ci = CarbonInterval::instance($diff); $this->assertCarbonInterval($ci, 0, 0, 21, 0, 0, 0); $this->assertSame($expectedDiff, $ci->days); $this->assertSame($expectedDiff, $ci->toDateInterval()->days); $ci2 = CarbonInterval::instance($ci->toDateInterval()); $this->assertCarbonInterval($ci2, 0, 0, 21, 0, 0, 0); $this->assertSame($expectedDiff, $ci2->days); $this->assertSame($expectedDiff, $ci2->toDateInterval()->days); $ci3 = unserialize(serialize($ci2)); $this->assertCarbonInterval($ci3, 0, 0, 21, 0, 0, 0); $this->assertSame($expectedDiff, $ci3->days); $this->assertSame($expectedDiff, $ci3->toDateInterval()->days); $ci = Carbon::now()->diffAsCarbonInterval(Carbon::now()->addWeeks(3)); $this->assertCarbonInterval($ci, 0, 0, 21, 0, 0, 0); $this->assertSame($expectedDiff, $ci->days); $this->assertSame($expectedDiff, $ci->toDateInterval()->days); } public function testInstanceWithoutDays() { $ci = CarbonInterval::fromString('1 day 3 hours'); $this->assertCarbonInterval($ci, 0, 0, 1, 3, 0, 0); $this->assertFalse($ci->days); $this->assertFalse($ci->toDateInterval()->days); $ci2 = CarbonInterval::instance($ci->toDateInterval()); $this->assertCarbonInterval($ci2, 0, 0, 1, 3, 0, 0); $this->assertFalse($ci2->days); $this->assertFalse($ci2->toDateInterval()->days); $ci3 = unserialize(serialize($ci2)); $this->assertCarbonInterval($ci3, 0, 0, 1, 3, 0, 0); $this->assertFalse($ci3->days); $this->assertFalse($ci3->toDateInterval()->days); } public function testCopy() { $one = CarbonInterval::days(10); $two = $one->hours(6)->copy()->hours(3); $this->assertCarbonInterval($one, 0, 0, 10, 6, 0, 0); $this->assertCarbonInterval($two, 0, 0, 10, 3, 0, 0); } public function testMake() { $this->assertCarbonInterval(CarbonInterval::make(3, 'hours'), 0, 0, 0, 3, 0, 0); $this->assertCarbonInterval(CarbonInterval::make('3 hours 30 m'), 0, 0, 0, 3, 30, 0); $this->assertCarbonInterval(CarbonInterval::make('PT5H'), 0, 0, 0, 5, 0, 0); $this->assertCarbonInterval(CarbonInterval::make('PT13.516837S'), 0, 0, 0, 0, 0, 13, 516_837); $this->assertCarbonInterval(CarbonInterval::make('PT32.245S'), 0, 0, 0, 0, 0, 32, 245_000); $this->assertCarbonInterval(CarbonInterval::make('PT13.000001S'), 0, 0, 0, 0, 0, 13, 1); $this->assertCarbonInterval(CarbonInterval::make('PT13.001S'), 0, 0, 0, 0, 0, 13, 1_000); $this->assertCarbonInterval(CarbonInterval::make(new DateInterval('P1D')), 0, 0, 1, 0, 0, 0); $this->assertCarbonInterval(CarbonInterval::make(new CarbonInterval('P2M')), 0, 2, 0, 0, 0, 0); $this->assertNull(CarbonInterval::make(3)); $this->assertSame(3.0, CarbonInterval::make('3 milliseconds')->totalMilliseconds); $this->assertSame(3.0, CarbonInterval::make('3 microseconds')->totalMicroseconds); $this->assertSame(21.0, CarbonInterval::make('3 weeks')->totalDays); $this->assertSame(9.0, CarbonInterval::make('3 quarters')->totalMonths); $this->assertSame(30.0, CarbonInterval::make('3 decades')->totalYears); $this->assertSame(300.0, CarbonInterval::make('3 centuries')->totalYears); $this->assertSame(3000.0, CarbonInterval::make('3 millennia')->totalYears); } public function testBadFormats() { $this->expectExceptionObject(new Exception('PT1999999999999.5.5H+85M')); CarbonInterval::create('PT1999999999999.5.5H+85M'); } public function testOutOfRange() { $this->expectExceptionObject(new OutOfRangeException( 'hour', -0x7fffffffffffffff, 0x7fffffffffffffff, 999999999999999999999999 )); CarbonInterval::create('PT999999999999999999999999H'); } public function testCallInvalidStaticMethod() { $this->expectExceptionObject(new BadMethodCallException( 'Unknown fluent constructor \'anything\'', )); CarbonInterval::anything(); } public function testOriginal() { $this->assertSame('3 hours', CarbonInterval::make(3, 'hours')->original()); $this->assertSame('3 hours 30 m', CarbonInterval::make('3 hours 30 m')->original()); $this->assertSame('PT5H', CarbonInterval::make('PT5H')->original()); $interval = new DateInterval('P1D'); $this->assertSame($interval, CarbonInterval::make($interval)->original()); $interval = new CarbonInterval('P2M'); $this->assertSame($interval, CarbonInterval::make($interval)->original()); } public function testCreateFromDateString() { $this->assertCarbonInterval(CarbonInterval::createFromDateString('3 hours'), 0, 0, 0, 3, 0, 0); $this->assertCarbonInterval(CarbonInterval::createFromDateString('46 days, 43 hours and 57 minutes'), 0, 0, 46, 43, 57, 0); } public function testCreateFromDateIncorrectString() { $this->expectExceptionObject(new InvalidFormatException( 'Could not create interval from: '.var_export('foo bar', true), )); CarbonInterval::createFromDateString('foo bar'); } public function testCreateFromDateIncorrectStringWithErrorAsException() { $this->expectExceptionObject(new InvalidFormatException( 'Could not create interval from: '.var_export('foo bar', true), )); $this->withErrorAsException(function () { CarbonInterval::createFromDateString('foo bar'); }); } public function testMakeFromDateIncorrectString() { $this->expectExceptionObject(new InvalidFormatException( 'Could not create interval from: '.var_export('foo bar', true), )); CarbonInterval::make('foo bar'); } public function testMakeFromDateIncorrectStringWithErrorAsException() { $this->expectExceptionObject(new InvalidFormatException( 'Could not create interval from: '.var_export('foo bar', true), )); $this->withErrorAsException(function () { CarbonInterval::make('foo bar'); }); } public function testEnums() { $this->assertCarbonInterval(CarbonInterval::make(3, Unit::Hour), 0, 0, 0, 3, 0, 0); $this->assertCarbonInterval(CarbonInterval::make(Unit::Week), 0, 0, 7, 0, 0, 0); } public function testFromSerialization() { $past = new Carbon('-3 Days'); $today = new Carbon('today'); $interval = $today->diffAsCarbonInterval($past); /** @var CarbonInterval $copy */ $copy = unserialize(serialize($interval)); $this->assertInstanceOf(CarbonInterval::class, $copy); $this->assertSame('2 days', $interval->forHumans(parts: 1)); $this->assertSame('2 days', $copy->forHumans(parts: 1)); $this->assertSame(['en'], array_keys($interval->getLocalTranslator()->getMessages()) ?: ['en']); $this->assertSame(['en'], array_keys($copy->getLocalTranslator()->getMessages()) ?: ['en']); $this->assertSame($interval->locale, $copy->locale); // Ignore translator for the English comparison $copy->setLocalTranslator($interval->getLocalTranslator()); $this->assertSameIntervals($interval, $copy, 1); $interval = $today->locale('ja')->diffAsCarbonInterval($past); /** @var CarbonInterval $copy */ $copy = unserialize(serialize($interval)); $this->assertInstanceOf(CarbonInterval::class, $copy); $this->assertSame('二日', $interval->forHumans(['altNumbers' => true, 'parts' => 1])); $this->assertSame('二日', $copy->forHumans(['altNumbers' => true, 'parts' => 1])); $this->assertSame(['ja'], array_keys($interval->getLocalTranslator()->getMessages())); $this->assertSame(['ja'], array_keys($copy->getLocalTranslator()->getMessages())); $this->assertSameIntervals($interval, $copy, 1); } public function testFromSerializationConst() { $past = new Carbon('2024-01-01 00:00:00'); $today = new Carbon('2024-01-03 06:39:47.065034'); $interval = $today->diffAsCarbonInterval($past); /** @var CarbonInterval $copy */ $copy = unserialize(serialize($interval)); $this->assertInstanceOf(CarbonInterval::class, $copy); $this->assertSame('2 days', $interval->forHumans(parts: 1)); $this->assertSame('2 days', $copy->forHumans(parts: 1)); $this->assertSame(['en'], array_keys($interval->getLocalTranslator()->getMessages()) ?: ['en']); $this->assertSame(['en'], array_keys($copy->getLocalTranslator()->getMessages()) ?: ['en']); $this->assertSame($interval->locale, $copy->locale); // Ignore translator for the English comparison $copy->setLocalTranslator($interval->getLocalTranslator()); $this->assertSameIntervals($interval, $copy, 1); $interval = $today->locale('ja')->diffAsCarbonInterval($past); /** @var CarbonInterval $copy */ $copy = unserialize(serialize($interval)); $this->assertInstanceOf(CarbonInterval::class, $copy); $this->assertSame('二日', $interval->forHumans(['altNumbers' => true, 'parts' => 1])); $this->assertSame('二日', $copy->forHumans(['altNumbers' => true, 'parts' => 1])); $this->assertSame(['ja'], array_keys($interval->getLocalTranslator()->getMessages())); $this->assertSame(['ja'], array_keys($copy->getLocalTranslator()->getMessages())); $this->assertSameIntervals($interval, $copy, 1); } public function testFromV2SerializedInterval() { $serializedData = trim(file_get_contents(__DIR__.'/../Fixtures/serialized-interval-from-v2.txt')); $interval = unserialize($serializedData); $this->assertInstanceOf(CarbonInterval::class, $interval); $this->assertSame(2, $interval->m); $this->assertSame(5.4e-5, $interval->f); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonInterval/ParseFromLocaleTest.php
tests/CarbonInterval/ParseFromLocaleTest.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonInterval; use Carbon\CarbonInterval; use Generator; use InvalidArgumentException; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use Tests\AbstractTestCase; class ParseFromLocaleTest extends AbstractTestCase { #[DataProvider('dataForValidStrings')] public function testReturnsInterval(string $string, string $locale, CarbonInterval $expected) { $result = CarbonInterval::parseFromLocale($string, $locale); $this->assertEquals($expected->optimize(), $result->optimize(), "'{$string}' does not return expected interval."); } public static function dataForValidStrings(): Generator { // zero interval yield ['', 'en', new CarbonInterval(0)]; // single values yield ['1y', 'en', new CarbonInterval(1)]; yield ['1mo', 'en', new CarbonInterval(0, 1)]; yield ['1w', 'en', new CarbonInterval(0, 0, 1)]; yield ['1d', 'en', new CarbonInterval(0, 0, 0, 1)]; yield ['1h', 'en', new CarbonInterval(0, 0, 0, 0, 1)]; yield ['1m', 'en', new CarbonInterval(0, 0, 0, 0, 0, 1)]; yield ['1s', 'en', new CarbonInterval(0, 0, 0, 0, 0, 0, 1)]; yield ['1ms', 'en', new CarbonInterval(0, 0, 0, 0, 0, 0, 0, 1000)]; yield ['1µs', 'en', new CarbonInterval(0, 0, 0, 0, 0, 0, 0, 1)]; // single values with space yield ['1 y', 'en', new CarbonInterval(1)]; yield ['1 mo', 'en', new CarbonInterval(0, 1)]; yield ['1 w', 'en', new CarbonInterval(0, 0, 1)]; // fractions with integer result yield ['0.571428571429w', 'en', new CarbonInterval(0, 0, 0, 4)]; yield ['0.5d', 'en', new CarbonInterval(0, 0, 0, 0, 12)]; yield ['0.5h', 'en', new CarbonInterval(0, 0, 0, 0, 0, 30)]; yield ['0.5m', 'en', new CarbonInterval(0, 0, 0, 0, 0, 0, 30)]; // fractions with float result yield ['1.5w', 'en', new CarbonInterval(0, 0, 1, 3, 12)]; yield ['2.34d', 'en', new CarbonInterval(0, 0, 0, 2, 8, 9, 36)]; yield ['3.12h', 'en', new CarbonInterval(0, 0, 0, 0, 3, 7, 12)]; yield ['3.129h', 'en', new CarbonInterval(0, 0, 0, 0, 3, 7, 44, 400000)]; yield ['4.24m', 'en', new CarbonInterval(0, 0, 0, 0, 0, 4, 14, 400000)]; yield ['3.56s', 'en', new CarbonInterval(0, 0, 0, 0, 0, 0, 3, 560000)]; yield ['3.56ms', 'en', new CarbonInterval(0, 0, 0, 0, 0, 0, 0, 3560)]; // combinations yield ['2w 3d', 'en', new CarbonInterval(0, 0, 0, 17)]; yield ['1y 2mo 1.5w 3d', 'en', new CarbonInterval(1, 2, 1, 6, 12)]; // multi same values yield ['1y 2y', 'en', new CarbonInterval(3)]; yield ['1mo 20mo', 'en', new CarbonInterval(0, 21)]; yield ['1w 2w 3w', 'en', new CarbonInterval(0, 0, 6)]; yield ['10d 20d 30d', 'en', new CarbonInterval(0, 0, 0, 60)]; yield ['5h 15h 25h', 'en', new CarbonInterval(0, 0, 0, 0, 45)]; yield ['3m 3m 3m 1m', 'en', new CarbonInterval(0, 0, 0, 0, 0, 10)]; yield ['55s 45s 1s 2s 3s 4s', 'en', new CarbonInterval(0, 0, 0, 0, 0, 0, 110)]; yield ['1500ms 1623555µs', 'en', new CarbonInterval(0, 0, 0, 0, 0, 0, 0, 3123555)]; yield ['430 milli', 'en', new CarbonInterval(0, 0, 0, 0, 0, 0, 0, 430000)]; // multi same values with space yield ['1 y 2 y', 'en', new CarbonInterval(3)]; yield ['1 mo 20 mo', 'en', new CarbonInterval(0, 21)]; yield ['1 w 2 w 3 w', 'en', new CarbonInterval(0, 0, 6)]; // no-space values yield ['2w3d', 'en', new CarbonInterval(0, 0, 0, 17)]; yield ['1y2mo3w4d5h6m7s', 'en', new CarbonInterval(1, 2, 3, 4, 5, 6, 7)]; // written-out units yield ['1year 2month 3week 4day 5hour 6minute 7second', 'en', new CarbonInterval(1, 2, 3, 4, 5, 6, 7)]; yield ['1 year 2 month 3 week', 'en', new CarbonInterval(1, 2, 3)]; yield ['2 Years 3 Months 4 Weeks', 'en', new CarbonInterval(2, 3, 4)]; yield ['5 Days 6 Hours 7 Minutes 8 Seconds', 'en', new CarbonInterval(0, 0, 0, 5, 6, 7, 8)]; // ignore invalid format; parse only [num][char-format] or [num] [char-format] yield ['Hello! Please add 1y2w to ...', 'en', new CarbonInterval(1, 0, 2)]; yield ['nothing to parse :(', 'en', new CarbonInterval(0)]; // case insensitive yield ['1Y 3MO 1W 3D 12H 23M 42S', 'en', new CarbonInterval(1, 3, 1, 3, 12, 23, 42)]; // Example for the ticket (#1756) yield ['2 jours 3 heures', 'fr', new CarbonInterval(0, 0, 0, 2, 3, 0, 0)]; } #[TestWith(['1q', '1q', 'en'])] #[TestWith(['about 12..14m', '12..', 'en'])] #[TestWith(['4h 13', '13', 'en'])] public function testThrowsExceptionForUnknownValues(string $string, string $part, string $locale) { $message = null; try { CarbonInterval::parseFromLocale($string, $locale); } catch (InvalidArgumentException $exception) { $message = $exception->getMessage(); } $this->assertStringContainsString($part, $message); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonInterval/CascadeTest.php
tests/CarbonInterval/CascadeTest.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonInterval; use Carbon\Carbon; use Carbon\CarbonInterval; use Generator; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use Tests\AbstractTestCase; class CascadeTest extends AbstractTestCase { protected function assertIntervalSpec(CarbonInterval $interval, string $spec, bool|int $inverted = false): void { $this->assertSame( ($inverted ? '- ' : '+ ').$spec, ($interval->invert ? '- ' : '+ ').$interval->spec(), ); } #[TestWith(['3600s', 'PT1H'])] #[TestWith(['10000s', 'PT2H46M40S'])] #[TestWith(['1276d', 'P3Y9M16D'])] #[TestWith(['47d 14h', 'P1M19DT14H'])] #[TestWith(['2y 123mo 5w 6d 47h 160m 217s', 'P12Y4M15DT1H43M37S'])] public function testCascadesOverflowedValues($spec, $expected) { $interval = CarbonInterval::fromString($spec)->cascade(); $this->assertIntervalSpec($interval, $expected); $interval = CarbonInterval::fromString($spec)->invert()->cascade(); $this->assertIntervalSpec($interval, $expected, true); } #[DataProvider('dataForMixedSignsIntervalSpecs')] public function testMixedSignsCascadesOverflowedValues($units, $expected, $expectingInversion) { $interval = new CarbonInterval(0); foreach ($units as $unit => $value) { $interval->$unit($value); } $interval->cascade(); $this->assertIntervalSpec($interval, $expected, $expectingInversion); $interval = new CarbonInterval(0); foreach ($units as $unit => $value) { $interval->$unit($value); } $interval->invert()->cascade(); $this->assertIntervalSpec($interval, $expected, 1 - $expectingInversion); } public static function dataForMixedSignsIntervalSpecs(): Generator { yield [ [ 'hours' => 1, 'minutes' => -30, ], 'PT30M', 0, ]; yield [ [ 'hours' => 1, 'minutes' => -90, ], 'PT30M', 1, ]; yield [ [ 'hours' => 1, 'minutes' => -90, 'seconds' => 3660, ], 'PT31M', 0, ]; yield [ [ 'hours' => 1, 'minutes' => -90, 'seconds' => 3540, ], 'PT29M', 0, ]; yield [ [ 'hours' => 1, 'minutes' => 90, 'seconds' => -3540, ], 'PT1H31M', 0, ]; yield [ [ 'hours' => 1, 'minutes' => 90, 'seconds' => -3660, ], 'PT1H29M', 0, ]; yield [ [ 'hours' => -1, 'minutes' => 90, 'seconds' => -3660, ], 'PT31M', 1, ]; yield [ [ 'hours' => -1, 'minutes' => 61, 'seconds' => -120, ], 'PT1M', 1, ]; yield [ [ 'days' => 48, 'hours' => -8, ], 'P1M19DT16H', 0, ]; yield [ [ 'days' => 48, 'hours' => -28, ], 'P1M18DT20H', 0, ]; yield [ [ 'hours' => 1, 'seconds' => -3615, ], 'PT15S', 1, ]; yield [ [ 'hours' => -1, 'seconds' => 3615, ], 'PT15S', 0, ]; yield [ [ 'hours' => 1, 'seconds' => -59, ], 'PT59M1S', 0, ]; yield [ [ 'hours' => -1, 'seconds' => 59, ], 'PT59M1S', 1, ]; yield [ [ 'years' => 94, 'months' => 11, 'days' => 24, 'hours' => 3848, 'microseconds' => 7991, ], 'P95Y5M16DT8H', 0, ]; } public function testCascadesWithMicroseconds() { $interval = CarbonInterval::fromString('1040ms 3012µs')->cascade(); $this->assertSame('PT1S', $interval->spec()); $this->assertSame(43, $interval->milliseconds); $this->assertSame(43012, $interval->microseconds); } #[TestWith(['3600s', '1h'])] #[TestWith(['10000s', '2h 46m 40s'])] #[TestWith(['1276d', '255w 1d'])] #[TestWith(['47d 14h', '9w 3d 6h'])] #[TestWith(['2y 123mo 5w 6d 47h 160m 217s', '2yrs 123mos 7w 2d 1h 43m 37s'])] public function testCustomCascadesOverflowedValues($spec, $expected) { $cascades = CarbonInterval::getCascadeFactors(); CarbonInterval::setCascadeFactors([ 'minutes' => [Carbon::SECONDS_PER_MINUTE, 'seconds'], 'hours' => [Carbon::MINUTES_PER_HOUR, 'minutes'], 'dayz' => [8, 'hours'], 'weeks' => [5, 'dayz'], ]); $actual = CarbonInterval::fromString($spec)->cascade()->forHumans(true); CarbonInterval::setCascadeFactors($cascades); $this->assertSame($expected, $actual); } #[TestWith(['3600s', '1 hour'])] #[TestWith(['10000s', '2 hours 46 minutes 40 seconds'])] #[TestWith(['1276d', '255 weeks 1 day'])] #[TestWith(['47d 14h', '9 weeks 3 days 6 hours'])] #[TestWith(['2y 123mo 5w 6d 47h 160m 217s', '2 years 123 months 7 weeks 2 days 1 hour 43 minutes 37 seconds'])] public function testCustomCascadesOverflowedValuesLongFormat($spec, $expected) { $cascades = CarbonInterval::getCascadeFactors(); CarbonInterval::setCascadeFactors([ 'minutes' => [Carbon::SECONDS_PER_MINUTE, 'seconds'], 'hours' => [Carbon::MINUTES_PER_HOUR, 'minutes'], 'dayz' => [8, 'hours'], 'weeks' => [5, 'dayz'], ]); $actual = CarbonInterval::fromString($spec)->cascade()->forHumans(false); CarbonInterval::setCascadeFactors($cascades); $this->assertSame($expected, $actual); } public function testMultipleAdd() { $cascades = CarbonInterval::getCascadeFactors(); CarbonInterval::setCascadeFactors([ 'minutes' => [Carbon::SECONDS_PER_MINUTE, 'seconds'], 'hours' => [Carbon::MINUTES_PER_HOUR, 'minutes'], 'days' => [8, 'hours'], 'weeks' => [5, 'days'], ]); $actual = CarbonInterval::fromString('3d') ->add(CarbonInterval::fromString('1d 5h')) ->add(CarbonInterval::fromString('7h')) ->cascade() ->forHumans(true); CarbonInterval::setCascadeFactors($cascades); $this->assertSame('1w 4h', $actual); } public function testFactorsGroups() { $cascades = CarbonInterval::getCascadeFactors(); CarbonInterval::setCascadeFactors([ 'hours' => [Carbon::MINUTES_PER_HOUR, 'minutes'], 'weeks' => [5, 'days'], ]); $actual = CarbonInterval::fromString('3d 50m') ->add(CarbonInterval::fromString('1d 5h 30m')) ->add(CarbonInterval::fromString('7h 45m')) ->add(CarbonInterval::fromString('1w 15m')) ->cascade() ->forHumans(true); CarbonInterval::setCascadeFactors($cascades); $this->assertSame('1w 4d 14h 20m', $actual); } public function testGetFactor() { $this->assertSame(28, CarbonInterval::getFactor('day', 'months')); $this->assertSame(28, CarbonInterval::getFactor('day', 'month')); $this->assertSame(28, CarbonInterval::getFactor('days', 'month')); $this->assertSame(28, CarbonInterval::getFactor('day', 'month')); $this->assertSame(28, CarbonInterval::getFactor('dayz', 'months')); } public function testComplexInterval() { $interval = CarbonInterval::create(0); $this->assertFalse($interval->hasNegativeValues()); $this->assertFalse($interval->hasPositiveValues()); $interval->days = -6; $this->assertTrue($interval->hasNegativeValues()); $this->assertFalse($interval->hasPositiveValues()); $interval->days = 6; $this->assertFalse($interval->hasNegativeValues()); $this->assertTrue($interval->hasPositiveValues()); $interval->hours = -40; $this->assertTrue($interval->hasNegativeValues()); $this->assertTrue($interval->hasPositiveValues()); $interval = CarbonInterval::create() ->years(-714)->months(-101)->days(-737) ->seconds(442)->microseconds(-19) ->cascade(); $this->assertFalse($interval->hasNegativeValues()); $this->assertTrue($interval->hasPositiveValues()); $interval = CarbonInterval::create(0)->hours(-7024)->cascade(); $this->assertLessThan(0, $interval->totalDays); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonInterval/ToPeriodTest.php
tests/CarbonInterval/ToPeriodTest.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonInterval; use Carbon\Carbon; use Carbon\CarbonInterval; use Carbon\CarbonPeriod; use Carbon\Exceptions\InvalidFormatException; use DateTimeZone; use Generator; use PHPUnit\Framework\Attributes\DataProvider; use Tests\AbstractTestCase; class ToPeriodTest extends AbstractTestCase { #[DataProvider('dataForToPeriodParameters')] public function testConvertToDatePeriod($interval, $arguments, $expected) { $period = ([$interval, 'toPeriod'])(...$arguments); $this->assertInstanceOf(CarbonPeriod::class, $period); $this->assertSame($expected, $period->spec()); } public static function dataForToPeriodParameters(): Generator { yield [ CarbonInterval::days(3), ['2017-10-15', 4], 'R4/2017-10-15T00:00:00-04:00/P3D', ]; yield [ CarbonInterval::hours(7), ['2017-10-15', '2017-10-17'], '2017-10-15T00:00:00-04:00/PT7H/2017-10-17T00:00:00-04:00', ]; yield [ CarbonInterval::months(3)->days(2)->hours(10)->minutes(20), ['2017-10-15'], '2017-10-15T00:00:00-04:00/P3M2DT10H20M', ]; yield [ CarbonInterval::minutes(30), [new Carbon('2018-05-14 17:30 UTC'), new Carbon('2018-05-14 18:00 Europe/Oslo')], '2018-05-14T17:30:00+00:00/PT30M/2018-05-14T18:00:00+02:00', ]; } public function testToDatePeriodWithTimezone(): void { $period = CarbonInterval::minutes(30) ->setTimezone('Asia/Tokyo') ->toPeriod('2021-08-14 00:00', '2021-08-14 02:00'); $this->assertSame('2021-08-14 00:00 Asia/Tokyo', $period->start()->format('Y-m-d H:i e')); $this->assertSame('2021-08-14 02:00 Asia/Tokyo', $period->end()->format('Y-m-d H:i e')); $period = CarbonInterval::minutes(30) ->setTimezone(new DateTimeZone('America/New_York')) ->toPeriod('2021-08-14 00:00', '2021-08-14 02:00'); $this->assertSame('2021-08-14 00:00 America/New_York', $period->start()->format('Y-m-d H:i e')); $this->assertSame('2021-08-14 02:00 America/New_York', $period->end()->format('Y-m-d H:i e')); } public function testStepBy(): void { $days = []; foreach (Carbon::parse('2020-08-29')->diff('2020-09-02')->stepBy('day') as $day) { $days[] = "$day"; } $this->assertSame([ '2020-08-29 00:00:00', '2020-08-30 00:00:00', '2020-08-31 00:00:00', '2020-09-01 00:00:00', '2020-09-02 00:00:00', ], $days); $times = []; foreach (Carbon::parse('2020-08-29')->diff('2020-08-31')->stepBy('12 hours') as $time) { $times[] = "$time"; } $this->assertSame([ '2020-08-29 00:00:00', '2020-08-29 12:00:00', '2020-08-30 00:00:00', '2020-08-30 12:00:00', '2020-08-31 00:00:00', ], $times); $days = []; /** @var CarbonPeriod $period */ $period = Carbon::parse('2020-08-29')->diff('2020-09-02')->stepBy('day'); foreach ($period->excludeEndDate() as $day) { $days[] = "$day"; } $this->assertSame([ '2020-08-29 00:00:00', '2020-08-30 00:00:00', '2020-08-31 00:00:00', '2020-09-01 00:00:00', ], $days); Carbon::setTestNow('2020-08-12 06:00:50'); $days = []; foreach (CarbonInterval::week()->stepBy('day') as $day) { $days[] = "$day"; } $this->assertSame([ '2020-08-12 06:00:50', '2020-08-13 06:00:50', '2020-08-14 06:00:50', '2020-08-15 06:00:50', '2020-08-16 06:00:50', '2020-08-17 06:00:50', '2020-08-18 06:00:50', '2020-08-19 06:00:50', ], $days); Carbon::setTestNow(null); } public function testStepByError() { $this->expectExceptionObject(new InvalidFormatException( 'Could not create interval from: '.var_export('1/2 days', true), )); CarbonInterval::week()->stepBy('1/2 days'); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonInterval/GettersTest.php
tests/CarbonInterval/GettersTest.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonInterval; use Carbon\Carbon; use Carbon\CarbonInterval; use Carbon\Translator; use DateTimeZone; use InvalidArgumentException; use Tests\AbstractTestCase; class GettersTest extends AbstractTestCase { public function testGettersThrowExceptionOnUnknownGetter() { $this->expectExceptionObject(new InvalidArgumentException( 'Unknown getter \'doesNotExit\'', )); /** @var mixed $interval */ $interval = CarbonInterval::year(); $interval->doesNotExit; } public function testGet() { $ci = CarbonInterval::create(4, 5, 6, 5, 8, 9, 10); $this->assertSame(4, $ci->get('years')); } public function testYearsGetter() { $ci = CarbonInterval::create(4, 5, 6, 5, 8, 9, 10); $this->assertSame(4, $ci->years); } public function testMonthsGetter() { $ci = CarbonInterval::create(4, 5, 6, 5, 8, 9, 10); $this->assertSame(5, $ci->months); } public function testWeeksGetter() { $ci = CarbonInterval::create(4, 5, 6, 5, 8, 9, 10); $this->assertSame(6, $ci->weeks); } public function testDayzExcludingWeeksGetter() { $ci = CarbonInterval::create(4, 5, 6, 5, 8, 9, 10); $this->assertSame(5, $ci->daysExcludeWeeks); $this->assertSame(5, $ci->dayzExcludeWeeks); } public function testDayzGetter() { $ci = CarbonInterval::create(4, 5, 6, 5, 8, 9, 10); $this->assertSame(6 * 7 + 5, $ci->dayz); } public function testHoursGetter() { $ci = CarbonInterval::create(4, 5, 6, 5, 8, 9, 10); $this->assertSame(8, $ci->hours); } public function testMinutesGetter() { $ci = CarbonInterval::create(4, 5, 6, 5, 8, 9, 10); $this->assertSame(9, $ci->minutes); } public function testSecondsGetter() { $ci = CarbonInterval::create(4, 5, 6, 5, 8, 9, 10); $this->assertSame(10, $ci->seconds); } public function testStartAndEnd() { $interval = Carbon::parse('2020-08-10')->diff('2020-09-30'); $this->assertSame('2020-08-10 00:00:00', $interval->start()->format('Y-m-d H:i:s')); $this->assertSame('2020-09-30 00:00:00', $interval->end()->format('Y-m-d H:i:s')); $interval = CarbonInterval::fromString('1 month 20 days'); $this->assertNull($interval->start()); $this->assertNull($interval->end()); } public function testDebugInfo() { $ci = CarbonInterval::create(4, 0, 6, 5, 0, 9, 10); $this->assertSame([ 'y' => 4, 'd' => 47, 'i' => 9, 's' => 10, ], $ci->__debugInfo()); $ci->locale('it_IT'); $this->assertSame([ 'localTranslator' => Translator::get('it_IT'), 'y' => 4, 'd' => 47, 'i' => 9, 's' => 10, ], $ci->__debugInfo()); } public function testGetTimezone() { $this->assertNull(CarbonInterval::day()->tzName); $this->assertSame( 'America/New_York', CarbonInterval::day()->setTimezone('America/New_York')->tzName, ); $this->assertSame( 'America/New_York', CarbonInterval::day()->setTimezone( new DateTimeZone('America/New_York'), )->tzName, ); $this->assertSame( '+05:00', CarbonInterval::day()->setTimezone(5)->tzName, ); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonInterval/AddTest.php
tests/CarbonInterval/AddTest.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonInterval; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterval; use DateInterval; use DateTime; use DateTimeImmutable; use InvalidArgumentException; use PHPUnit\Framework\Attributes\TestWith; use Tests\AbstractTestCase; use Tests\Carbon\Fixtures\MyCarbon; class AddTest extends AbstractTestCase { public function testAdd() { $ci = CarbonInterval::create(4, 3, 6, 7, 8, 10, 11)->add(new DateInterval('P2Y1M5DT22H33M44S')); $this->assertCarbonInterval($ci, 6, 4, 54, 30, 43, 55); } public function testNamedParameters() { $ci = CarbonInterval::years(years: 3)->addYears(years: 4); $this->assertCarbonInterval($ci, 7); $ci = CarbonInterval::months(months: 3)->addMonths(months: 4); $this->assertCarbonInterval($ci, 0, 7); $ci = CarbonInterval::weeks(weeks: 3)->addWeeks(weeks: 4); $this->assertCarbonInterval($ci, 0, 0, 7 * 7); $ci = CarbonInterval::days(days: 3)->addDays(days: 4); $this->assertCarbonInterval($ci, 0, 0, 7); $ci = CarbonInterval::hours(hours: 3)->addHours(hours: 4); $this->assertCarbonInterval($ci, 0, 0, 0, 7); $ci = CarbonInterval::minutes(minutes: 3)->addMinutes(minutes: 4); $this->assertCarbonInterval($ci, 0, 0, 0, 0, 7); $ci = CarbonInterval::seconds(seconds: 3)->addSeconds(seconds: 4); $this->assertCarbonInterval($ci, 0, 0, 0, 0, 0, 7); $ci = CarbonInterval::milliseconds(milliseconds: 3)->addMilliseconds(milliseconds: 4); $this->assertCarbonInterval($ci, 0, 0, 0, 0, 0, 0, 7000); $ci = CarbonInterval::microseconds(microseconds: 3)->addMicroseconds(microseconds: 4); $this->assertCarbonInterval($ci, 0, 0, 0, 0, 0, 0, 7); } public function testAddWithDiffDateInterval() { $diff = Carbon::now()->diff(Carbon::now()->addWeeks(3)); $ci = CarbonInterval::create(4, 3, 6, 7, 8, 10, 11)->add($diff); $this->assertCarbonInterval($ci, 4, 3, 70, 8, 10, 11); } public function testAddWithNegativeDiffDateInterval() { $diff = Carbon::now()->diff(Carbon::now()->subWeeks(3)); $ci = CarbonInterval::create(4, 3, 6, 7, 8, 10, 11)->add($diff); $this->assertCarbonInterval($ci, 4, 3, 28, 8, 10, 11); } public function testAddMicroseconds() { $diff = Carbon::now()->diff(Carbon::now()->addDays(3)->addMicroseconds(111222)); $ci = CarbonInterval::create(1, 0, 0, 2, 0, 0, 0, 222333)->add($diff); if ($ci->seconds === 1) { $ci->seconds--; $ci->microseconds += 1000000; } $this->assertCarbonInterval($ci, 1, 0, 5, 0, 0, 0, 333555); $diff = Carbon::now()->diff(Carbon::now()->addDays(3)); $ci = CarbonInterval::create(1, 0, 0, 2, 0, 0, 0, 222333)->add($diff); $this->assertCarbonInterval($ci, 1, 0, 5, 0, 0, 0, 222333); $diff = Carbon::now()->diff(Carbon::now()->addDays(3)->addMicroseconds(111222)); $ci = CarbonInterval::create(1, 0, 0, 2, 0, 0, 0)->add($diff); if ($ci->seconds === 1) { $ci->seconds--; $ci->microseconds += 1000000; } $this->assertCarbonInterval($ci, 1, 0, 5, 0, 0, 0, 111222); } public function testAddWithRawDiffDateInterval() { date_default_timezone_set('UTC'); $date = new DateTime(); $diff = $date->diff((clone $date)->modify('3 weeks')); $ci = CarbonInterval::create(4, 3, 6, 7, 8, 10, 11)->add($diff); $this->assertCarbonInterval($ci, 4, 3, 70, 8, 10, 11); } public function testAddWithRawNegativeDiffDateInterval() { date_default_timezone_set('UTC'); $date = new DateTime(); $diff = $date->diff((clone $date)->modify('-3 weeks')); $ci = CarbonInterval::create(4, 3, 6, 7, 8, 10, 11)->add($diff); $this->assertCarbonInterval($ci, 4, 3, 28, 8, 10, 11); } #[TestWith([5, 2, 7])] #[TestWith([-5, -2, -7])] #[TestWith([-5, 2, -3])] #[TestWith([5, -2, 3])] #[TestWith([2, 5, 7])] #[TestWith([-2, -5, -7])] #[TestWith([-2, 5, 3])] #[TestWith([2, -5, -3])] public function testAddSign(int $base, int $increment, int $expectedResult) { $interval = new CarbonInterval(); $interval->hours(abs($base)); if ($base < 0) { $interval->invert(); } $add = new CarbonInterval(); $add->hours(abs($increment)); if ($increment < 0) { $add->invert(); } $interval->add($add); $this->assertGreaterThanOrEqual(0, $interval->hours); $actualResult = ($interval->invert ? -1 : 1) * $interval->hours; $this->assertSame($expectedResult, $actualResult); } public function testAddAndSubMultipleFormats() { $this->assertCarbonInterval(CarbonInterval::day()->add('hours', 3), 0, 0, 1, 3, 0, 0); $this->assertCarbonInterval(CarbonInterval::day()->add(5, 'hours'), 0, 0, 1, 5, 0, 0); $this->assertCarbonInterval(CarbonInterval::day()->add(3, '4 hours'), 0, 0, 1, 12, 0, 0); $this->assertCarbonInterval(CarbonInterval::day()->add(-5, 'hours'), 0, 0, 1, -5, 0, 0); $this->assertCarbonInterval(CarbonInterval::hours(4)->add('hour'), 0, 0, 0, 5, 0, 0); $this->assertCarbonInterval(CarbonInterval::hours(4)->add(new DateInterval('P5D')), 0, 0, 5, 4, 0, 0); $this->assertCarbonInterval(CarbonInterval::hours(4)->add(CarbonInterval::minutes(30)), 0, 0, 0, 4, 30, 0); $this->assertCarbonInterval(CarbonInterval::day()->sub('hours', 3), 0, 0, 1, -3, 0, 0); $this->assertCarbonInterval(CarbonInterval::day()->subtract(5, 'hours'), 0, 0, 1, -5, 0, 0); $this->assertCarbonInterval(CarbonInterval::day()->subtract(3, '4 hours'), 0, 0, 1, -12, 0, 0); $this->assertCarbonInterval(CarbonInterval::day()->subtract(-5, 'hours'), 0, 0, 1, 5, 0, 0); $this->assertCarbonInterval(CarbonInterval::hours(4)->sub('hour'), 0, 0, 0, 3, 0, 0); $this->assertCarbonInterval(CarbonInterval::hours(4)->subtract(new DateInterval('P5D')), 0, 0, -5, 4, 0, 0); $this->assertCarbonInterval(CarbonInterval::hours(4)->sub(CarbonInterval::minutes(30)), 0, 0, 0, 4, -30, 0); } public function testAddWrongFormat() { $this->expectExceptionObject(new InvalidArgumentException( 'This type of data cannot be added/subtracted.', )); CarbonInterval::day()->add(Carbon::now()); } public function testConvertDate() { $this->assertCarbon(CarbonInterval::days(3)->convertDate(new DateTime('2020-06-14')), 2020, 6, 17, 0, 0, 0); $this->assertCarbon(CarbonInterval::days(3)->convertDate(new DateTimeImmutable('2020-06-14')), 2020, 6, 17, 0, 0, 0); $this->assertCarbon(CarbonInterval::days(3)->convertDate(new DateTime('2020-06-14'), true), 2020, 6, 11, 0, 0, 0); $this->assertCarbon(CarbonInterval::days(3)->convertDate(new DateTimeImmutable('2020-06-14'), true), 2020, 6, 11, 0, 0, 0); $interval = new CarbonInterval(static fn (MyCarbon $carbon) => $carbon->addTwoHours()); $result = CarbonImmutable::parse('2024-01-18 08:00')->add($interval); $this->assertSame(CarbonImmutable::class, $result::class); $this->assertSame('2024-01-18 10:00:00', $result->format('Y-m-d H:i:s')); } public function testMagicAddAndSubMethods() { $this->assertCarbonInterval(CarbonInterval::days(3)->addWeeks(2), 0, 0, 17, 0, 0, 0); $this->assertCarbonInterval(CarbonInterval::weeks(3)->addDays(2), 0, 0, 23, 0, 0, 0); $this->assertCarbonInterval(CarbonInterval::weeks(3)->subDays(2), 0, 0, 19, 0, 0, 0); $this->assertCarbonInterval(CarbonInterval::hours(2)->subMinutes(15), 0, 0, 0, 2, -15, 0); $this->assertCarbonInterval(CarbonInterval::hours(2)->subMinutes(15)->cascade(), 0, 0, 0, 1, 45, 0); } public function testPlus() { $this->assertCarbonInterval(CarbonInterval::days(3)->plus(0, 0, 2, 0, 26), 0, 0, 17, 26, 0, 0); $this->assertCarbonInterval(CarbonInterval::days(3)->plus(0, 0, 0.25), 0, 0, 4, 18, 0, 0); $interval = CarbonInterval::days(3)->plus(0, 0, 0.25)->plus(0, 0, 0.25)->cascade(); $this->assertCarbonInterval($interval, 0, 0, 6, 12, 0, 0); } public function testPlusWithPHP8Syntax() { $interval = CarbonInterval::days(3)->plus(weeks: 2, hours: 26); $this->assertCarbonInterval($interval, 0, 0, 17, 26, 0, 0); $interval = CarbonInterval::days(3)->plus(hours: 1, minutes: 1.5); $this->assertCarbonInterval($interval, 0, 0, 3, 1, 1, 30); $interval = CarbonInterval::days(3)->plus(hours: 1, minutes: -1.5); $this->assertCarbonInterval($interval, 0, 0, 3, 1, -1, -30); } public function testMinus() { $this->assertCarbonInterval(CarbonInterval::days(3)->minus(0, 0, 2, 0, 26), 0, 0, 11, 26, 0, 0, 0, true); } public function testMinusWithPHP8Syntax() { $interval = CarbonInterval::days(3)->minus(weeks: 2, hours: 26); $this->assertCarbonInterval($interval, 0, 0, 11, 26, 0, 0, 0, true); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonInterval/ToDateIntervalTest.php
tests/CarbonInterval/ToDateIntervalTest.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonInterval; use Carbon\CarbonInterval; use DateInterval; use DateTime; use InvalidArgumentException; use Tests\AbstractTestCase; class ToDateIntervalTest extends AbstractTestCase { public function testConvertToDateInterval() { $interval = CarbonInterval::days(5)->hours(3)->minutes(50)->microseconds(123456)->invert()->toDateInterval(); $this->assertSame(DateInterval::class, \get_class($interval)); $this->assertSame(1, $interval->invert); $this->assertSame(5, $interval->d); $this->assertSame(3, $interval->h); $this->assertSame(50, $interval->i); $this->assertSame(0, $interval->s); $this->assertSame(0.123456, $interval->f); } public function testCastToDateInterval() { $interval = CarbonInterval::days(5)->hours(3)->minutes(50)->microseconds(123456)->invert()->cast(DateInterval::class); $this->assertSame(DateInterval::class, \get_class($interval)); $this->assertSame(1, $interval->invert); $this->assertSame(5, $interval->d); $this->assertSame(3, $interval->h); $this->assertSame(50, $interval->i); $this->assertSame(0, $interval->s); $this->assertSame(0.123456, $interval->f); } public function testBadCast() { $this->expectExceptionObject(new InvalidArgumentException( 'DateTime is not a sub-class of DateInterval.', )); CarbonInterval::days(5)->hours(3)->minutes(50)->microseconds(123456)->invert()->cast(DateTime::class); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonInterval/MacroTest.php
tests/CarbonInterval/MacroTest.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonInterval; use Carbon\CarbonInterval; use Tests\AbstractTestCaseWithOldNow; use Tests\CarbonInterval\Fixtures\Mixin; use Tests\CarbonInterval\Fixtures\MixinTrait; class MacroTest extends AbstractTestCaseWithOldNow { public function testCarbonIsMacroableWhenNotCalledStatically() { CarbonInterval::macro('twice', function () { /** @var CarbonInterval $interval */ $interval = $this; return $interval->times(2); }); /** @var mixed $interval */ $interval = CarbonInterval::day(); $this->assertSame('2 days', $interval->twice()->forHumans()); CarbonInterval::macro('repeatInvert', function ($count = 0) { /** @var CarbonInterval $interval */ $interval = $this; return $count % 2 ? $interval->invert() : $interval; }); /** @var mixed $interval */ $interval = CarbonInterval::day(); $this->assertSame(0, $interval->repeatInvert()->invert); /** @var mixed $interval */ $interval = CarbonInterval::day(); $this->assertSame(1, $interval->repeatInvert(3)->invert); /** @var mixed $interval */ $interval = CarbonInterval::day(); $this->assertSame(0, $interval->repeatInvert(4)->invert); CarbonInterval::macro('otherParameterName', function ($other = true) { return $other; }); /** @var mixed $interval */ $interval = CarbonInterval::day(); $this->assertTrue($interval->otherParameterName()); } public function testCarbonIsMacroableWhenNotCalledStaticallyUsingThis() { CarbonInterval::macro('repeatInvert2', function ($count = 0) { /** @var CarbonInterval $interval */ $interval = $this; return $count % 2 ? $interval->invert() : $interval; }); /** @var mixed $interval */ $interval = CarbonInterval::day(); $this->assertSame(0, $interval->repeatInvert2()->invert); /** @var mixed $interval */ $interval = CarbonInterval::day(); $this->assertSame(1, $interval->repeatInvert2(3)->invert); /** @var mixed $interval */ $interval = CarbonInterval::day(); $this->assertSame(0, $interval->repeatInvert2(4)->invert); } public function testCarbonIsMacroableWhenCalledStatically() { CarbonInterval::macro('quarter', function () { return CarbonInterval::months(3); }); $this->assertSame('3 months', CarbonInterval::quarter()->forHumans()); CarbonInterval::macro('quarterIfEven', function ($value = 0) { return $value % 2 ? CarbonInterval::day() : CarbonInterval::months(3); }); $this->assertSame('3 months', CarbonInterval::quarterIfEven()->forHumans()); $this->assertSame('1 day', CarbonInterval::quarterIfEven(7)->forHumans()); $this->assertSame('3 months', CarbonInterval::quarterIfEven(-6)->forHumans()); } public function testCarbonIsMacroableWithNonClosureCallables() { CarbonInterval::macro('lower', 'strtolower'); /** @var mixed $interval */ $interval = CarbonInterval::day(); $this->assertSame('abc', $interval->lower('ABC')); $this->assertSame('abc', CarbonInterval::lower('ABC')); } public function testCarbonIsMixinable() { include_once __DIR__.'/Fixtures/Mixin.php'; $mixin = new Mixin(); CarbonInterval::mixin($mixin); CarbonInterval::setFactor(3); /** @var mixed $interval */ $interval = CarbonInterval::hours(2); $this->assertSame('6 hours', $interval->doMultiply()->forHumans()); } public function testMixinInstance() { include_once __DIR__.'/Fixtures/MixinTrait.php'; CarbonInterval::mixin(MixinTrait::class); $input = CarbonInterval::days(2); $copy = $input->copyAndAgain(); $this->assertSame('2 days', $input->forHumans()); $mutated = $input->andAgain(); $this->assertSame('4 days', $input->forHumans()); $this->assertSame('4 days', $mutated->forHumans()); $this->assertSame('4 days', $copy->forHumans()); $this->assertSame($input, $mutated); $this->assertNotSame($copy, $mutated); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonInterval/AlternativeNumbersTest.php
tests/CarbonInterval/AlternativeNumbersTest.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonInterval; use Carbon\CarbonInterval; use Tests\AbstractTestCase; class AlternativeNumbersTest extends AbstractTestCase { public function testAlternativesNumbers() { $this->assertSame( '۵۲ ساعت', CarbonInterval::hours(52)->locale('fa')->forHumans(['altNumbers' => true]), ); $this->assertSame( '۰۱ ساعت', CarbonInterval::hour()->locale('fa')->forHumans(['altNumbers' => 'fa']), ); $this->assertSame( '1時間', CarbonInterval::hour()->locale('ja')->forHumans(['altNumbers' => 'fa']), ); $this->assertSame( '۰۱ ساعت', CarbonInterval::hour()->locale('fa')->forHumans(['altNumbers' => ['fa', 'ja']]), ); $this->assertSame( '52 ساعت', CarbonInterval::hours(52)->locale('fa')->forHumans(['altNumbers' => 'ja']), ); $this->assertSame( '52 ساعت', CarbonInterval::hours(52)->locale('fa')->forHumans(['altNumbers' => ['lzh', 'ja']]), ); $this->assertSame( '五十二時間', CarbonInterval::hours(52)->locale('ja')->forHumans(['altNumbers' => ['lzh', 'ja']]), ); $this->assertSame( '-6', CarbonInterval::hours(-6)->locale('fa')->translateNumber(-6), ); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonInterval/RoundingTest.php
tests/CarbonInterval/RoundingTest.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonInterval; use Carbon\Carbon; use Carbon\CarbonInterval; use DateInterval; use InvalidArgumentException; use Tests\AbstractTestCase; class RoundingTest extends AbstractTestCase { public function testThrowsExceptionForCompositeInterval() { $this->expectExceptionObject(new InvalidArgumentException( 'Rounding is only possible with single unit intervals.', )); CarbonInterval::days(2)->round('2 hours 50 minutes'); } public function testFloor() { $this->assertSame(21.0, CarbonInterval::days(21)->floorWeeks()->totalDays); $this->assertSame(21.0, CarbonInterval::days(24)->floorWeeks()->totalDays); $this->assertSame(21.0, CarbonInterval::days(25)->floorWeeks()->totalDays); $this->assertSame(21.0, CarbonInterval::days(27)->floorWeeks()->totalDays); $this->assertSame(28.0, CarbonInterval::days(28)->floorWeeks()->totalDays); $this->assertSame(1000.0, CarbonInterval::milliseconds(1234)->floor()->totalMilliseconds); $this->assertSame(1000.0, CarbonInterval::milliseconds(1834)->floor()->totalMilliseconds); $this->assertSame(20.0, CarbonInterval::days(21)->floor('2 days')->totalDays); $this->assertSame(18.0, CarbonInterval::days(21)->floor(CarbonInterval::days(6))->totalDays); $this->assertSame(18.0, CarbonInterval::days(22)->floorUnit('day', 6)->totalDays); } public function testRound() { $this->assertSame(21.0, CarbonInterval::days(21)->roundWeeks()->totalDays); $this->assertSame(21.0, CarbonInterval::days(24)->roundWeeks()->totalDays); $this->assertSame(28.0, CarbonInterval::days(25)->roundWeeks()->totalDays); $this->assertSame(28.0, CarbonInterval::days(27)->roundWeeks()->totalDays); $this->assertSame(28.0, CarbonInterval::days(28)->roundWeeks()->totalDays); $this->assertSame(-7.0, CarbonInterval::make('7 days 23 hours 34 minutes')->invert()->roundWeeks()->totalDays); $this->assertSame(-7.0, CarbonInterval::make('-7 days 23 hours 34 minutes')->roundWeeks()->totalDays); $this->assertSame(7.0, CarbonInterval::make('-7 days 23 hours 34 minutes')->invert()->roundWeeks()->totalDays); $this->assertSame(1000.0, CarbonInterval::milliseconds(1234)->round()->totalMilliseconds); $this->assertSame(2000.0, CarbonInterval::milliseconds(1834)->round()->totalMilliseconds); $this->assertSame(20.0, CarbonInterval::days(20)->round('2 days')->totalDays); $this->assertSame(18.0, CarbonInterval::days(20)->round(CarbonInterval::days(6))->totalDays); $this->assertSame(22.0, CarbonInterval::days(21)->round('2 days')->totalDays); $this->assertSame(24.0, CarbonInterval::days(21)->round(CarbonInterval::days(6))->totalDays); $this->assertSame(22.0, CarbonInterval::days(22)->round('2 days')->totalDays); $this->assertSame(24.0, CarbonInterval::days(22)->round(CarbonInterval::days(6))->totalDays); $this->assertSame(24.0, CarbonInterval::days(22)->roundUnit('day', 6)->totalDays); } public function testTotalAfterRound() { $this->assertSame(19, CarbonInterval::make('43h3m6s')->roundMinutes()->hours); $this->assertSame(43.05, CarbonInterval::make('43h3m6s')->roundMinutes()->totalHours); } public function testWithCascadeFactors() { $cascades = CarbonInterval::getCascadeFactors(); CarbonInterval::setCascadeFactors([ 'millisecond' => [1000, 'microseconds'], 'second' => [1000, 'milliseconds'], 'minute' => [60, 'seconds'], 'hour' => [60, 'minutes'], ]); $this->assertVeryClose( 43.166666666666664, CarbonInterval::make('43h3m6s') ->ceilMinutes(10) ->totalHours, ); $this->assertSame( 43.0, CarbonInterval::make('43h3m6s') ->floorMinutes(6) ->totalHours ); $this->assertSame( 43.05, CarbonInterval::make('43h3m6s') ->roundMinutes() ->totalHours ); $this->assertVeryClose( 43.05833333333333, CarbonInterval::make('43h3m26s') ->roundMinutes(0.5) ->totalHours, ); $this->assertSame( -43.05, CarbonInterval::make('43h3m6s') ->invert() ->roundMinutes(0.5) ->totalHours ); CarbonInterval::setCascadeFactors($cascades); } public function testCeil() { $this->assertSame(21.0, CarbonInterval::days(21)->ceilWeeks()->totalDays); $this->assertSame(28.0, CarbonInterval::days(24)->ceilWeeks()->totalDays); $this->assertSame(28.0, CarbonInterval::days(25)->ceilWeeks()->totalDays); $this->assertSame(28.0, CarbonInterval::days(27)->ceilWeeks()->totalDays); $this->assertSame(28.0, CarbonInterval::days(28)->ceilWeeks()->totalDays); $this->assertSame(2000.0, CarbonInterval::milliseconds(1234)->ceil()->totalMilliseconds); $this->assertSame(2000.0, CarbonInterval::milliseconds(1834)->ceil()->totalMilliseconds); $this->assertSame(20.0, CarbonInterval::days(20)->ceil('2 days')->totalDays); $this->assertSame(24.0, CarbonInterval::days(20)->ceil(CarbonInterval::days(6))->totalDays); $this->assertSame(22.0, CarbonInterval::days(21)->ceil('2 days')->totalDays); $this->assertSame(24.0, CarbonInterval::days(21)->ceil(CarbonInterval::days(6))->totalDays); $this->assertSame(22.0, CarbonInterval::days(22)->ceil('2 days')->totalDays); $this->assertSame(24.0, CarbonInterval::days(22)->ceil(CarbonInterval::days(6))->totalDays); $this->assertSame(24.0, CarbonInterval::days(22)->ceilUnit('day', 6)->totalDays); } public function testRoundCarbonInstanceToIntervalInNonDefaultLocale() { $interval15m = CarbonInterval::fromString('PT15M')->locale('es'); $this->assertSame( '19:30', Carbon::parse('2024-04-15T19:36:12')->floor($interval15m)->format('H:i') ); $this->assertSame( '19:45', Carbon::parse('2024-04-15T19:36:12')->ceil($interval15m)->format('H:i') ); $this->assertSame('15 minutos', $interval15m->forHumans()); $interval1h = DateInterval::createFromDateString('1 hour'); Carbon::setLocale('zh'); $this->assertSame('1小时', CarbonInterval::make($interval1h)->forHumans()); $this->assertSame( '19:00', Carbon::parse('2024-04-15T19:36:12')->floor($interval1h)->format('H:i') ); $this->assertSame( '20:00', Carbon::parse('2024-04-15T19:36:12')->ceil($interval1h)->format('H:i') ); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonInterval/TotalTest.php
tests/CarbonInterval/TotalTest.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonInterval; use Carbon\Carbon; use Carbon\CarbonInterval; use DateTimeImmutable; use Generator; use InvalidArgumentException; use PHPUnit\Framework\Attributes\DataProvider; use Tests\AbstractTestCase; class TotalTest extends AbstractTestCase { #[DataProvider('dataForIntervalSpecs')] public function testReturnsTotalValue($spec, $unit, $expected) { $this->assertSame( (float) $expected, CarbonInterval::fromString($spec)->total($unit), "$spec as $unit did not get the expected total", ); } public static function dataForIntervalSpecs(): Generator { yield ['10s', 'seconds', 10]; yield ['100s', 'seconds', 100]; yield ['2d 4h 17m 35s', 'seconds', ((2 * 24 + 4) * 60 + 17) * 60 + 35]; yield ['1y', 'Seconds', 12 * 4 * 7 * 24 * 60 * 60]; yield ['1000y', 'SECONDS', 1000 * 12 * 4 * 7 * 24 * 60 * 60]; yield ['235s', 'minutes', 235 / 60]; yield ['3h 14m 235s', 'minutes', 3 * 60 + 14 + 235 / 60]; yield ['27h 150m 4960s', 'hours', 27 + (150 + 4960 / 60) / 60]; yield ['1w', 'days', 7]; yield ['2w 15d', 'weeks', 29 / 7]; yield ['5mo 54d 185h 7680m', 'days', 5 * 4 * 7 + 54 + (185 + 7680 / 60) / 24]; yield ['4y 2mo', 'days', (4 * 12 + 2) * 4 * 7]; yield ['165d', 'weeks', 165 / 7]; yield ['5mo', 'weeks', 5 * 4]; yield ['6897d', 'months', 6897 / 7 / 4]; yield ['35mo', 'years', 35 / 12]; } public function testThrowsExceptionForInvalidUnits() { $this->expectExceptionObject(new InvalidArgumentException( 'Unknown unit \'foo\'.', )); CarbonInterval::create()->total('foo'); } public function testGetTotalsViaGetters() { $interval = CarbonInterval::create(0, 0, 0, 0, 150, 0, 0); $this->assertSame(150.0 * 60 * 60 * 1000 * 1000, $interval->totalMicroseconds); $this->assertSame(150.0 * 60 * 60 * 1000, $interval->totalMilliseconds); $this->assertSame(150.0 * 60 * 60, $interval->totalSeconds); $this->assertSame(150.0 * 60, $interval->totalMinutes); $this->assertSame(150.0, $interval->totalHours); $this->assertSame(150.0 / 24, $interval->totalDays); $this->assertSame(150.0 / 24 / 7, $interval->totalWeeks); $this->assertSame(150.0 / 24 / 7 / 4, $interval->totalMonths); $this->assertSame(150.0 / 24 / 7 / 4 / 12, $interval->totalYears); $interval = CarbonInterval::milliseconds(12312); $this->assertSame(12312000.0, $interval->totalMicroseconds); $this->assertSame(12312.0, $interval->totalMilliseconds); $interval = CarbonInterval::milliseconds(-12312); $this->assertSame(-12312000.0, $interval->totalMicroseconds); $this->assertSame(-12312.0, $interval->totalMilliseconds); } public static function dataForNegativeIntervals(): Generator { yield [-1, CarbonInterval::hours(0)->hours(-150)]; yield [-1, CarbonInterval::hours(150)->invert()]; yield [1, CarbonInterval::hours(0)->hours(-150)->invert()]; } #[DataProvider('dataForNegativeIntervals')] public function testGetNegativeTotalsViaGetters($factor, $interval) { $this->assertSame($factor * 150.0 * 60 * 60 * 1000 * 1000, $interval->totalMicroseconds); $this->assertSame($factor * 150.0 * 60 * 60 * 1000, $interval->totalMilliseconds); $this->assertSame($factor * 150.0 * 60 * 60, $interval->totalSeconds); $this->assertSame($factor * 150.0 * 60, $interval->totalMinutes); $this->assertSame($factor * 150.0, $interval->totalHours); $this->assertSame($factor * 150.0 / 24, $interval->totalDays); $this->assertSame($factor * 150.0 / 24 / 7, $interval->totalWeeks); $this->assertSame($factor * 150.0 / 24 / 7 / 4, $interval->totalMonths); $this->assertSame($factor * 150.0 / 24 / 7 / 4 / 12, $interval->totalYears); } public function testTotalsWithCustomFactors() { $factors = CarbonInterval::getCascadeFactors(); CarbonInterval::setCascadeFactors([ 'minute' => [60, 'seconds'], 'hour' => [60, 'minutes'], 'day' => [8, 'hours'], 'week' => [5, 'days'], ]); $this->assertSame(1.0, CarbonInterval::make('1d')->totalDays); $this->assertSame(5.0, CarbonInterval::make('1w')->totalDays); $this->assertSame(1.0, CarbonInterval::make('1w')->totalWeeks); CarbonInterval::setCascadeFactors($factors); } public function testFloatHoursFactors() { $factors = CarbonInterval::getCascadeFactors(); CarbonInterval::setCascadeFactors([ 'minute' => [60, 'seconds'], 'hour' => [60, 'minutes'], 'day' => [7.5, 'hours'], 'week' => [5, 'days'], ]); $this->assertSame( '2 weeks 1 day 5 hours 45 minutes', CarbonInterval::minutes(11 * (7.5 * 60) + (5 * 60) + 45)->cascade()->forHumans() ); CarbonInterval::setCascadeFactors($factors); } public function testFloatDaysFactors() { $factors = CarbonInterval::getCascadeFactors(); CarbonInterval::setCascadeFactors([ 'minute' => [60, 'seconds'], 'hour' => [60, 'minutes'], 'day' => [8, 'hours'], 'week' => [5.5, 'days'], ]); $this->assertSame( '3 weeks 1 day 5 hours 45 minutes', CarbonInterval::minutes(17.5 * (8 * 60) + (5 * 60) + 45)->cascade()->forHumans() ); CarbonInterval::setCascadeFactors($factors); } public function testFloatInMultipleFactors() { $factors = CarbonInterval::getCascadeFactors(); CarbonInterval::setCascadeFactors([ 'minute' => [23.2, 'seconds'], 'hour' => [25.662, 'minutes'], 'day' => [10 / 3, 'hours'], 'week' => [pi(), 'days'], ]); $interval = CarbonInterval::minutes(50000)->cascade(); $this->assertSame( '185 weeks 2 days 3 hours 35 minutes 35 seconds', $interval->forHumans() ); // Show how we (approximately) get back to initial values $this->assertEqualsWithDelta( 50000 * 23.2, 35 + (35 * 23.2) + (3 * 25.662 * 23.2) + (2 * (10 / 3) * 25.662 * 23.2) + (185 * pi() * (10 / 3) * 25.662 * 23.2), 3 ); // Show how total uncascade $this->assertEqualsWithDelta(50000 / 25.662, $interval->totalHours, 0.05); $this->assertEqualsWithDelta(50000, $interval->totalMinutes, 0.1); $this->assertEqualsWithDelta(50000 * 23.2, $interval->totalSeconds, 1); CarbonInterval::setCascadeFactors($factors); } public function testGetTotalsViaGettersWithCustomFactors() { $cascades = CarbonInterval::getCascadeFactors(); CarbonInterval::setCascadeFactors([ 'minutes' => [Carbon::SECONDS_PER_MINUTE, 'seconds'], 'hours' => [Carbon::MINUTES_PER_HOUR, 'minutes'], 'days' => [8, 'hours'], 'weeks' => [5, 'days'], ]); $interval = CarbonInterval::create(0, 0, 0, 0, 150, 0, 0); $totalSeconds = $interval->totalSeconds; $totalMinutes = $interval->totalMinutes; $totalHours = $interval->totalHours; $totalDays = $interval->totalDays; $totalWeeks = $interval->totalWeeks; $monthsError = null; try { $interval->totalMonths; } catch (InvalidArgumentException $exception) { $monthsError = $exception->getMessage(); } $yearsError = null; try { $interval->totalYears; } catch (InvalidArgumentException $exception) { $yearsError = $exception->getMessage(); } CarbonInterval::setCascadeFactors($cascades); $this->assertSame(150.0 * 60 * 60, $totalSeconds); $this->assertSame(150.0 * 60, $totalMinutes); $this->assertSame(150.0, $totalHours); $this->assertSame(150.0 / 8, $totalDays); $this->assertSame(150.0 / 8 / 5, $totalWeeks); $this->assertSame('Unit months have no configuration to get total from other units.', $monthsError); $this->assertSame('Unit years have no configuration to get total from other units.', $yearsError); } public function testGetTotalsViaGettersWithFalseFactor() { $cascades = CarbonInterval::getCascadeFactors(); CarbonInterval::setCascadeFactors([ 'minutes' => [Carbon::SECONDS_PER_MINUTE, 'seconds'], 'hours' => [Carbon::MINUTES_PER_HOUR, 'minutes'], 'days' => [false, 'hours'], // soft break 'months' => [30, 'days'], 'years' => [Carbon::MONTHS_PER_YEAR, 'months'], ]); $interval = CarbonInterval::create(3, 2, 0, 6, 150, 0, 0); $totalSeconds = $interval->totalSeconds; $totalMinutes = $interval->totalMinutes; $totalHours = $interval->totalHours; $totalDays = $interval->totalDays; $totalMonths = $interval->totalMonths; $totalYears = $interval->totalYears; CarbonInterval::setCascadeFactors($cascades); $this->assertSame(150.0 * 60 * 60, $totalSeconds); $this->assertSame(150.0 * 60, $totalMinutes); $this->assertSame(150.0, $totalHours); $this->assertSame(1146.0, $totalDays); $this->assertSame(1146.0 / 30, $totalMonths); $this->assertSame(1146.0 / 30 / 12, $totalYears); } public function testMicrosecondsInterval() { $interval = CarbonInterval::milliseconds(500); $this->assertSame(0.5, $interval->totalSeconds); $this->assertSame(1 / 2 / 60, $interval->totalMinutes); $this->assertSame(1 / 2 / 3600, $interval->totalHours); $interval = CarbonInterval::milliseconds(600000)->cascade(); $this->assertSame(600000000.0, $interval->totalMicroseconds); $this->assertSame(600000.0, $interval->totalMilliseconds); $this->assertSame(600.0, $interval->totalSeconds); $this->assertSame(10.0, $interval->totalMinutes); $this->assertSame(1 / 6, $interval->totalHours); } public function testWithDiffInterval() { $this->assertSame(51.0, Carbon::parse('2020-08-10')->diff('2020-09-30')->totalDays); } public function testAlterationAfterDiff() { $t1 = Carbon::now(); $t2 = $t1->copy()->addMinutes(2); $p = $t1->diffAsCarbonInterval($t2); $p->addSeconds(10); $this->assertSame(130.0, $p->totalSeconds); } public function testAbsoluteDiff() { Carbon::setTestNowAndTimezone(new DateTimeImmutable('now UTC')); $diff = Carbon::now()->addDays(15)->diff('now'); $this->assertSame(-1296000000000.0, $diff->totalMicroseconds); $this->assertTrue($diff->lte(CarbonInterval::minutes(30))); $diff = Carbon::now()->addDays(15)->diff('now', true); $this->assertSame(1296000000000.0, $diff->totalMicroseconds); $this->assertFalse($diff->lte(CarbonInterval::minutes(30))); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonInterval/CompareTest.php
tests/CarbonInterval/CompareTest.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonInterval; use Carbon\CarbonInterval; use Tests\AbstractTestCase; class CompareTest extends AbstractTestCase { public function testNegative() { $first = CarbonInterval::minute(); $second = CarbonInterval::minutes(2); $result = $first->compare($second); $this->assertSame(-1, $result); } public function testPositive() { $first = CarbonInterval::day(); $second = CarbonInterval::hour(); $result = $first->compare($second); $this->assertSame(1, $result); } public function testEqual() { $first = CarbonInterval::year(); $second = CarbonInterval::year(); $result = $first->compare($second); $this->assertSame(0, $result); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonInterval/CreateFromFormatTest.php
tests/CarbonInterval/CreateFromFormatTest.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonInterval; use Carbon\CarbonInterval; use Carbon\Exceptions\ParseErrorException; use Tests\AbstractTestCase; class CreateFromFormatTest extends AbstractTestCase { public function testDefaults() { $this->expectExceptionObject(new ParseErrorException( 'number', '', )); CarbonInterval::createFromFormat('H:i:s', ''); } public function testNulls() { $this->expectExceptionObject(new ParseErrorException( 'number', '', )); CarbonInterval::createFromFormat('H:i:s', null); } public function testTrailingData() { $this->expectExceptionObject(new ParseErrorException( 'end of string', ':25', )); CarbonInterval::createFromFormat('H:i', '01:30:25'); } public function testInvalidSubstitute() { $this->expectExceptionObject( new ParseErrorException( "'N'", '4', 'Allowed substitutes for interval formats are y, Y, o, m, n, W, d, j, z, h, g, H, G, i, s, u, v'. "\n". 'See https://php.net/manual/en/function.date.php for their meaning', ), ); CarbonInterval::createFromFormat('N', '4'); } public function testYears() { $ci = CarbonInterval::createFromFormat('Y', '1'); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 1, 0, 0, 0, 0, 0); $ci = CarbonInterval::createFromFormat('Y', '2'); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 2, 0, 0, 0, 0, 0); } public function testMonths() { $ci = CarbonInterval::createFromFormat('m', '1'); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 1, 0, 0, 0, 0); $ci = CarbonInterval::createFromFormat('m', '2'); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 2, 0, 0, 0, 0); } public function testWeeks() { $ci = CarbonInterval::createFromFormat('W', '1'); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 7, 0, 0, 0); $ci = CarbonInterval::createFromFormat('W', '2'); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 14, 0, 0, 0); } public function testDays() { $ci = CarbonInterval::createFromFormat('d', '1'); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 1, 0, 0, 0); $ci = CarbonInterval::createFromFormat('d', '2'); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 2, 0, 0, 0); } public function testWeeksAndDays() { $ci = CarbonInterval::createFromFormat('W d', '3 5'); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 26, 0, 0, 0); $ci = CarbonInterval::createFromFormat('W d', '2 -6'); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 8, 0, 0, 0); } public function testHours() { $ci = CarbonInterval::createFromFormat('H', '1'); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 0, 1, 0, 0); $ci = CarbonInterval::createFromFormat('H', '2'); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 0, 2, 0, 0); } public function testMinutes() { $ci = CarbonInterval::createFromFormat('i', '01'); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 0, 0, 1, 0); $ci = CarbonInterval::createFromFormat('i', '02'); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 0, 0, 2, 0); } public function testSeconds() { $ci = CarbonInterval::createFromFormat('s', '01'); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 0, 0, 0, 1); $ci = CarbonInterval::createFromFormat('s', '02'); $this->assertCarbonInterval($ci, 0, 0, 0, 0, 0, 2); } public function testDecimalSeconds() { $ci = CarbonInterval::createFromFormat('s.v', '1.5'); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 0, 0, 0, 1, 500000); $ci = CarbonInterval::createFromFormat('s.u', '1.2534'); $this->assertCarbonInterval($ci, 0, 0, 0, 0, 0, 1, 253400); } public function testMilliseconds() { $ci = CarbonInterval::createFromFormat('v', '100'); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 0, 0, 0, 0, 100000); $this->assertSame(100000, $ci->microseconds); $ci = CarbonInterval::createFromFormat('v', '200'); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 0, 0, 0, 0, 200000); } public function testMicroseconds() { $ci = CarbonInterval::createFromFormat('u', '100000'); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 0, 0, 0, 0, 100000); $this->assertSame(100000, $ci->microseconds); $ci = CarbonInterval::createFromFormat('u', '200000'); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 0, 0, 0, 0, 200000); } public function testTime() { $ci = CarbonInterval::createFromFormat('H:i:s', '00:05:00'); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 0, 0, 0, 0, 5, 0, 0); } public function testAll() { $ci = CarbonInterval::createFromFormat('Y-m-d H:i:s.u', '2000-01-02 3:04:05.500000'); $this->assertInstanceOfCarbonInterval($ci); $this->assertCarbonInterval($ci, 2000, 1, 2, 3, 4, 5, 500000); } public function testCopy() { $one = CarbonInterval::createFromFormat('H:i:s', '10:10:10'); $two = $one->copy()->hours(3)->minutes(3)->seconds(3); $this->assertCarbonInterval($one, 0, 0, 0, 10, 10, 10); $this->assertCarbonInterval($two, 0, 0, 0, 3, 3, 3); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false
briannesbitt/Carbon
https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonInterval/SharesTest.php
tests/CarbonInterval/SharesTest.php
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\CarbonInterval; use Carbon\CarbonInterval; use Tests\AbstractTestCase; class SharesTest extends AbstractTestCase { public function testSharesMoreThanOne() { $ci = CarbonInterval::create(4, 3, 2, 5, 5, 10, 11)->shares(1 / 2.75); $this->assertCarbonInterval($ci, 11, 8, 52, 14, 28, 30); } public function testSharesOne() { $ci = CarbonInterval::create(4, 3, 2, 5, 5, 10, 11)->shares(1); $this->assertCarbonInterval($ci, 4, 3, 19, 5, 10, 11); } public function testSharesLessThanOne() { $ci = CarbonInterval::create(4, 3, 2, 5, 5, 10, 11)->shares(3); $this->assertCarbonInterval($ci, 1, 1, 6, 2, 3, 4); } public function testSharesLessThanZero() { $ci = CarbonInterval::create(4, 3, 2, 5, 5, 10, 11)->shares(-1); $this->assertCarbonInterval($ci, 4, 3, 19, 5, 10, 11); $this->assertSame(1, $ci->invert); } public function testSharesLessThanZeroWithInvertedInterval() { $ci = CarbonInterval::create(4, 3, 2, 5, 5, 10, 11); $ci->invert = 1; $ci->shares(-1); $this->assertCarbonInterval($ci, 4, 3, 19, 5, 10, 11); $this->assertSame(0, $ci->invert); } }
php
MIT
6e037cd6239a150d74a54c62e300b269e88a89e3
2026-01-04T15:02:34.459238Z
false