blob: f8c72890cbcb0fd603f866e290024998a6c53c02 [file] [log] [blame]
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +02001<?php
2
3/**
4 * This file is part of the Carbon package.
5 *
6 * (c) Brian Nesbitt <brian@nesbot.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
Matthias Andreas Benkard1ba53812022-12-27 17:32:58 +010011
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +020012namespace Carbon;
13
14use Closure;
Matthias Andreas Benkard1ba53812022-12-27 17:32:58 +010015use DateTimeInterface;
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +020016use ReflectionMethod;
17
18/**
19 * A factory to generate Carbon instances with common settings.
20 *
21 * <autodoc generated by `composer phpdoc`>
22 *
Matthias Andreas Benkard1ba53812022-12-27 17:32:58 +010023 * @method bool canBeCreatedFromFormat($date, $format) Checks if the (date)time string is in a given format and valid to create a
24 * new instance.
25 * @method Carbon|false create($year = 0, $month = 1, $day = 1, $hour = 0, $minute = 0, $second = 0, $tz = null) Create a new Carbon instance from a specific date and time.
26 * If any of $year, $month or $day are set to null their now() values will
27 * be used.
28 * If $hour is null it will be set to its now() value and the default
29 * values for $minute and $second will be their now() values.
30 * If $hour is not null then the default values for $minute and $second
31 * will be 0.
32 * @method Carbon createFromDate($year = null, $month = null, $day = null, $tz = null) Create a Carbon instance from just a date. The time portion is set to now.
33 * @method Carbon|false createFromFormat($format, $time, $tz = null) Create a Carbon instance from a specific format.
34 * @method Carbon|false createFromIsoFormat($format, $time, $tz = null, $locale = 'en', $translator = null) Create a Carbon instance from a specific ISO format (same replacements as ->isoFormat()).
35 * @method Carbon|false createFromLocaleFormat($format, $locale, $time, $tz = null) Create a Carbon instance from a specific format and a string in a given language.
36 * @method Carbon|false createFromLocaleIsoFormat($format, $locale, $time, $tz = null) Create a Carbon instance from a specific ISO format and a string in a given language.
37 * @method Carbon createFromTime($hour = 0, $minute = 0, $second = 0, $tz = null) Create a Carbon instance from just a time. The date portion is set to today.
38 * @method Carbon createFromTimeString($time, $tz = null) Create a Carbon instance from a time string. The date portion is set to today.
39 * @method Carbon createFromTimestamp($timestamp, $tz = null) Create a Carbon instance from a timestamp and set the timezone (use default one if not specified).
40 * Timestamp input can be given as int, float or a string containing one or more numbers.
41 * @method Carbon createFromTimestampMs($timestamp, $tz = null) Create a Carbon instance from a timestamp in milliseconds.
42 * Timestamp input can be given as int, float or a string containing one or more numbers.
43 * @method Carbon createFromTimestampMsUTC($timestamp) Create a Carbon instance from a timestamp in milliseconds.
44 * Timestamp input can be given as int, float or a string containing one or more numbers.
45 * @method Carbon createFromTimestampUTC($timestamp) Create a Carbon instance from an timestamp keeping the timezone to UTC.
46 * Timestamp input can be given as int, float or a string containing one or more numbers.
47 * @method Carbon createMidnightDate($year = null, $month = null, $day = null, $tz = null) Create a Carbon instance from just a date. The time portion is set to midnight.
48 * @method Carbon|false createSafe($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $tz = null) Create a new safe Carbon instance from a specific date and time.
49 * If any of $year, $month or $day are set to null their now() values will
50 * be used.
51 * If $hour is null it will be set to its now() value and the default
52 * values for $minute and $second will be their now() values.
53 * If $hour is not null then the default values for $minute and $second
54 * will be 0.
55 * If one of the set values is not valid, an InvalidDateException
56 * will be thrown.
57 * @method CarbonInterface createStrict(?int $year = 0, ?int $month = 1, ?int $day = 1, ?int $hour = 0, ?int $minute = 0, ?int $second = 0, $tz = null) Create a new Carbon instance from a specific date and time using strict validation.
58 * @method Carbon disableHumanDiffOption($humanDiffOption) @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
59 * You should rather use the ->settings() method.
60 * @method Carbon enableHumanDiffOption($humanDiffOption) @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
61 * You should rather use the ->settings() method.
62 * @method mixed executeWithLocale($locale, $func) Set the current locale to the given, execute the passed function, reset the locale to previous one,
63 * then return the result of the closure (or null if the closure was void).
64 * @method Carbon fromSerialized($value) Create an instance from a serialized string.
65 * @method void genericMacro($macro, $priority = 0) Register a custom macro.
66 * @method array getAvailableLocales() Returns the list of internally available locales and already loaded custom locales.
67 * (It will ignore custom translator dynamic loading.)
68 * @method Language[] getAvailableLocalesInfo() Returns list of Language object for each available locale. This object allow you to get the ISO name, native
69 * name, region and variant of the locale.
70 * @method array getDays() Get the days of the week
71 * @method string|null getFallbackLocale() Get the fallback locale.
72 * @method array getFormatsToIsoReplacements() List of replacements from date() format to isoFormat().
73 * @method int getHumanDiffOptions() Return default humanDiff() options (merged flags as integer).
74 * @method array getIsoUnits() Returns list of locale units for ISO formatting.
75 * @method array getLastErrors() {@inheritdoc}
76 * @method string getLocale() Get the current translator locale.
77 * @method callable|null getMacro($name) Get the raw callable macro registered globally for a given name.
78 * @method int getMidDayAt() get midday/noon hour
79 * @method Closure|Carbon getTestNow() Get the Carbon instance (real or mock) to be returned when a "now"
80 * instance is created.
81 * @method string getTimeFormatByPrecision($unitPrecision) Return a format from H:i to H:i:s.u according to given unit precision.
82 * @method string getTranslationMessageWith($translator, string $key, ?string $locale = null, ?string $default = null) Returns raw translation message for a given key.
83 * @method \Symfony\Component\Translation\TranslatorInterface getTranslator() Get the default translator instance in use.
84 * @method int getWeekEndsAt() Get the last day of week
85 * @method int getWeekStartsAt() Get the first day of week
86 * @method array getWeekendDays() Get weekend days
87 * @method bool hasFormat($date, $format) Checks if the (date)time string is in a given format.
88 * @method bool hasFormatWithModifiers($date, $format) Checks if the (date)time string is in a given format.
89 * @method bool hasMacro($name) Checks if macro is registered globally.
90 * @method bool hasRelativeKeywords($time) Determine if a time string will produce a relative date.
91 * @method bool hasTestNow() Determine if there is a valid test instance set. A valid test instance
92 * is anything that is not null.
93 * @method Carbon instance($date) Create a Carbon instance from a DateTime one.
94 * @method bool isImmutable() Returns true if the current class/instance is immutable.
95 * @method bool isModifiableUnit($unit) Returns true if a property can be changed via setter.
96 * @method bool isMutable() Returns true if the current class/instance is mutable.
97 * @method bool isStrictModeEnabled() Returns true if the strict mode is globally in use, false else.
98 * (It can be overridden in specific instances.)
99 * @method bool localeHasDiffOneDayWords($locale) Returns true if the given locale is internally supported and has words for 1-day diff (just now, yesterday, tomorrow).
100 * Support is considered enabled if the 3 words are translated in the given locale.
101 * @method bool localeHasDiffSyntax($locale) Returns true if the given locale is internally supported and has diff syntax support (ago, from now, before, after).
102 * Support is considered enabled if the 4 sentences are translated in the given locale.
103 * @method bool localeHasDiffTwoDayWords($locale) Returns true if the given locale is internally supported and has words for 2-days diff (before yesterday, after tomorrow).
104 * Support is considered enabled if the 2 words are translated in the given locale.
105 * @method bool localeHasPeriodSyntax($locale) Returns true if the given locale is internally supported and has period syntax support (X times, every X, from X, to X).
106 * Support is considered enabled if the 4 sentences are translated in the given locale.
107 * @method bool localeHasShortUnits($locale) Returns true if the given locale is internally supported and has short-units support.
108 * Support is considered enabled if either year, day or hour has a short variant translated.
109 * @method void macro($name, $macro) Register a custom macro.
110 * @method Carbon|null make($var) Make a Carbon instance from given variable if possible.
111 * Always return a new instance. Parse only strings and only these likely to be dates (skip intervals
112 * and recurrences). Throw an exception for invalid format, but otherwise return null.
113 * @method Carbon maxValue() Create a Carbon instance for the greatest supported date.
114 * @method Carbon minValue() Create a Carbon instance for the lowest supported date.
115 * @method void mixin($mixin) Mix another object into the class.
116 * @method Carbon now($tz = null) Get a Carbon instance for the current date and time.
117 * @method Carbon parse($time = null, $tz = null) Create a carbon instance from a string.
118 * This is an alias for the constructor that allows better fluent syntax
119 * as it allows you to do Carbon::parse('Monday next week')->fn() rather
120 * than (new Carbon('Monday next week'))->fn().
121 * @method Carbon parseFromLocale($time, $locale = null, $tz = null) Create a carbon instance from a localized string (in French, Japanese, Arabic, etc.).
122 * @method string pluralUnit(string $unit) Returns standardized plural of a given singular/plural unit name (in English).
123 * @method Carbon|false rawCreateFromFormat($format, $time, $tz = null) Create a Carbon instance from a specific format.
124 * @method Carbon rawParse($time = null, $tz = null) Create a carbon instance from a string.
125 * This is an alias for the constructor that allows better fluent syntax
126 * as it allows you to do Carbon::parse('Monday next week')->fn() rather
127 * than (new Carbon('Monday next week'))->fn().
128 * @method Carbon resetMacros() Remove all macros and generic macros.
129 * @method void resetMonthsOverflow() @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
130 * You should rather use the ->settings() method.
131 * Or you can use method variants: addMonthsWithOverflow/addMonthsNoOverflow, same variants
132 * are available for quarters, years, decade, centuries, millennia (singular and plural forms).
133 * @method void resetToStringFormat() Reset the format used to the default when type juggling a Carbon instance to a string
134 * @method void resetYearsOverflow() @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
135 * You should rather use the ->settings() method.
136 * Or you can use method variants: addYearsWithOverflow/addYearsNoOverflow, same variants
137 * are available for quarters, years, decade, centuries, millennia (singular and plural forms).
138 * @method void serializeUsing($callback) @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
139 * You should rather transform Carbon object before the serialization.
140 * JSON serialize all Carbon instances using the given callback.
141 * @method Carbon setFallbackLocale($locale) Set the fallback locale.
142 * @method Carbon setHumanDiffOptions($humanDiffOptions) @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
143 * You should rather use the ->settings() method.
144 * @method bool setLocale($locale) Set the current translator locale and indicate if the source locale file exists.
145 * Pass 'auto' as locale to use closest language from the current LC_TIME locale.
146 * @method void setMidDayAt($hour) @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
147 * You should rather consider mid-day is always 12pm, then if you need to test if it's an other
148 * hour, test it explicitly:
149 * $date->format('G') == 13
150 * or to set explicitly to a given hour:
151 * $date->setTime(13, 0, 0, 0)
152 * Set midday/noon hour
153 * @method Carbon setTestNow($testNow = null) Set a Carbon instance (real or mock) to be returned when a "now"
154 * instance is created. The provided instance will be returned
155 * specifically under the following conditions:
156 * - A call to the static now() method, ex. Carbon::now()
157 * - When a null (or blank string) is passed to the constructor or parse(), ex. new Carbon(null)
158 * - When the string "now" is passed to the constructor or parse(), ex. new Carbon('now')
159 * - When a string containing the desired time is passed to Carbon::parse().
160 * Note the timezone parameter was left out of the examples above and
161 * has no affect as the mock value will be returned regardless of its value.
162 * Only the moment is mocked with setTestNow(), the timezone will still be the one passed
163 * as parameter of date_default_timezone_get() as a fallback (see setTestNowAndTimezone()).
164 * To clear the test instance call this method using the default
165 * parameter of null.
166 * /!\ Use this method for unit tests only.
167 * @method Carbon setTestNowAndTimezone($testNow = null, $tz = null) Set a Carbon instance (real or mock) to be returned when a "now"
168 * instance is created. The provided instance will be returned
169 * specifically under the following conditions:
170 * - A call to the static now() method, ex. Carbon::now()
171 * - When a null (or blank string) is passed to the constructor or parse(), ex. new Carbon(null)
172 * - When the string "now" is passed to the constructor or parse(), ex. new Carbon('now')
173 * - When a string containing the desired time is passed to Carbon::parse().
174 * It will also align default timezone (e.g. call date_default_timezone_set()) with
175 * the second argument or if null, with the timezone of the given date object.
176 * To clear the test instance call this method using the default
177 * parameter of null.
178 * /!\ Use this method for unit tests only.
179 * @method void setToStringFormat($format) @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
180 * You should rather let Carbon object being casted to string with DEFAULT_TO_STRING_FORMAT, and
181 * use other method or custom format passed to format() method if you need to dump an other string
182 * format.
183 * Set the default format used when type juggling a Carbon instance to a string
184 * @method void setTranslator(TranslatorInterface $translator) Set the default translator instance to use.
185 * @method Carbon setUtf8($utf8) @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
186 * You should rather use UTF-8 language packages on every machine.
187 * Set if UTF8 will be used for localized date/time.
188 * @method void setWeekEndsAt($day) @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
189 * Use $weekStartsAt optional parameter instead when using startOfWeek, floorWeek, ceilWeek
190 * or roundWeek method. You can also use the 'first_day_of_week' locale setting to change the
191 * start of week according to current locale selected and implicitly the end of week.
192 * Set the last day of week
193 * @method void setWeekStartsAt($day) @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
194 * Use $weekEndsAt optional parameter instead when using endOfWeek method. You can also use the
195 * 'first_day_of_week' locale setting to change the start of week according to current locale
196 * selected and implicitly the end of week.
197 * Set the first day of week
198 * @method void setWeekendDays($days) @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
199 * You should rather consider week-end is always saturday and sunday, and if you have some custom
200 * week-end days to handle, give to those days an other name and create a macro for them:
201 * ```
202 * Carbon::macro('isDayOff', function ($date) {
203 * return $date->isSunday() || $date->isMonday();
204 * });
205 * Carbon::macro('isNotDayOff', function ($date) {
206 * return !$date->isDayOff();
207 * });
208 * if ($someDate->isDayOff()) ...
209 * if ($someDate->isNotDayOff()) ...
210 * // Add 5 not-off days
211 * $count = 5;
212 * while ($someDate->isDayOff() || ($count-- > 0)) {
213 * $someDate->addDay();
214 * }
215 * ```
216 * Set weekend days
217 * @method bool shouldOverflowMonths() Get the month overflow global behavior (can be overridden in specific instances).
218 * @method bool shouldOverflowYears() Get the month overflow global behavior (can be overridden in specific instances).
219 * @method string singularUnit(string $unit) Returns standardized singular of a given singular/plural unit name (in English).
220 * @method Carbon today($tz = null) Create a Carbon instance for today.
221 * @method Carbon tomorrow($tz = null) Create a Carbon instance for tomorrow.
222 * @method string translateTimeString($timeString, $from = null, $to = null, $mode = CarbonInterface::TRANSLATE_ALL) Translate a time string from a locale to an other.
223 * @method string translateWith(TranslatorInterface $translator, string $key, array $parameters = [], $number = null) Translate using translation string or callback available.
224 * @method void useMonthsOverflow($monthsOverflow = true) @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
225 * You should rather use the ->settings() method.
226 * Or you can use method variants: addMonthsWithOverflow/addMonthsNoOverflow, same variants
227 * are available for quarters, years, decade, centuries, millennia (singular and plural forms).
228 * @method Carbon useStrictMode($strictModeEnabled = true) @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
229 * You should rather use the ->settings() method.
230 * @method void useYearsOverflow($yearsOverflow = true) @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
231 * You should rather use the ->settings() method.
232 * Or you can use method variants: addYearsWithOverflow/addYearsNoOverflow, same variants
233 * are available for quarters, years, decade, centuries, millennia (singular and plural forms).
234 * @method mixed withTestNow($testNow = null, $callback = null) Temporarily sets a static date to be used within the callback.
235 * Using setTestNow to set the date, executing the callback, then
236 * clearing the test instance.
237 * /!\ Use this method for unit tests only.
238 * @method Carbon yesterday($tz = null) Create a Carbon instance for yesterday.
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +0200239 *
240 * </autodoc>
241 */
242class Factory
243{
244 protected $className = Carbon::class;
245
246 protected $settings = [];
247
248 public function __construct(array $settings = [], ?string $className = null)
249 {
250 if ($className) {
251 $this->className = $className;
252 }
253
254 $this->settings = $settings;
255 }
256
257 public function getClassName()
258 {
259 return $this->className;
260 }
261
262 public function setClassName(string $className)
263 {
264 $this->className = $className;
265
266 return $this;
267 }
268
269 public function className(string $className = null)
270 {
271 return $className === null ? $this->getClassName() : $this->setClassName($className);
272 }
273
274 public function getSettings()
275 {
276 return $this->settings;
277 }
278
279 public function setSettings(array $settings)
280 {
281 $this->settings = $settings;
282
283 return $this;
284 }
285
286 public function settings(array $settings = null)
287 {
288 return $settings === null ? $this->getSettings() : $this->setSettings($settings);
289 }
290
291 public function mergeSettings(array $settings)
292 {
293 $this->settings = array_merge($this->settings, $settings);
294
295 return $this;
296 }
297
298 public function __call($name, $arguments)
299 {
300 $method = new ReflectionMethod($this->className, $name);
301 $settings = $this->settings;
302
303 if ($settings && isset($settings['timezone'])) {
304 $tzParameters = array_filter($method->getParameters(), function ($parameter) {
305 return \in_array($parameter->getName(), ['tz', 'timezone'], true);
306 });
307
Matthias Andreas Benkard1ba53812022-12-27 17:32:58 +0100308 if (isset($arguments[0]) && \in_array($name, ['instance', 'make', 'create', 'parse'], true)) {
309 if ($arguments[0] instanceof DateTimeInterface) {
310 $settings['innerTimezone'] = $settings['timezone'];
311 } elseif (\is_string($arguments[0]) && date_parse($arguments[0])['is_localtime']) {
312 unset($settings['timezone'], $settings['innerTimezone']);
313 }
314 } elseif (\count($tzParameters)) {
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +0200315 array_splice($arguments, key($tzParameters), 0, [$settings['timezone']]);
316 unset($settings['timezone']);
317 }
318 }
319
320 $result = $this->className::$name(...$arguments);
321
322 return $result instanceof CarbonInterface && !empty($settings)
323 ? $result->settings($settings)
324 : $result;
325 }
326}