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