1
<?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
 */
11
namespace Carbon;
12

13
use Closure;
14
use 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 Carbon                                             disableHumanDiffOption($humanDiffOption)                                                                                           @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
56
 *                                                                                                                                                                                                           You should rather use the ->settings() method.
57
 * @method Carbon                                             enableHumanDiffOption($humanDiffOption)                                                                                            @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
58
 *                                                                                                                                                                                                           You should rather use the ->settings() method.
59
 * @method mixed                                              executeWithLocale($locale, $func)                                                                                                  Set the current locale to the given, execute the passed function, reset the locale to previous one,
60
 *                                                                                                                                                                                               then return the result of the closure (or null if the closure was void).
61
 * @method Carbon                                             fromSerialized($value)                                                                                                             Create an instance from a serialized string.
62
 * @method void                                               genericMacro($macro, $priority = 0)                                                                                                Register a custom macro.
63
 * @method array                                              getAvailableLocales()                                                                                                              Returns the list of internally available locales and already loaded custom locales.
64
 *                                                                                                                                                                                               (It will ignore custom translator dynamic loading.)
65
 * @method Language[]                                         getAvailableLocalesInfo()                                                                                                          Returns list of Language object for each available locale. This object allow you to get the ISO name, native
66
 *                                                                                                                                                                                               name, region and variant of the locale.
67
 * @method array                                              getDays()                                                                                                                          Get the days of the week
68
 * @method string|null                                        getFallbackLocale()                                                                                                                Get the fallback locale.
69
 * @method array                                              getFormatsToIsoReplacements()                                                                                                      List of replacements from date() format to isoFormat().
70
 * @method int                                                getHumanDiffOptions()                                                                                                              Return default humanDiff() options (merged flags as integer).
71
 * @method array                                              getIsoUnits()                                                                                                                      Returns list of locale units for ISO formatting.
72
 * @method Carbon                                             getLastErrors()                                                                                                                    {@inheritdoc}
73
 * @method string                                             getLocale()                                                                                                                        Get the current translator locale.
74
 * @method callable|null                                      getMacro($name)                                                                                                                    Get the raw callable macro registered globally for a given name.
75
 * @method int                                                getMidDayAt()                                                                                                                      get midday/noon hour
76
 * @method Closure|Carbon                                     getTestNow()                                                                                                                       Get the Carbon instance (real or mock) to be returned when a "now"
77
 *                                                                                                                                                                                               instance is created.
78
 * @method string                                             getTimeFormatByPrecision($unitPrecision)                                                                                           Return a format from H:i to H:i:s.u according to given unit precision.
79
 * @method string                                             getTranslationMessageWith($translator, string $key, string $locale = null, string $default = null)                                 Returns raw translation message for a given key.
80
 * @method \Symfony\Component\Translation\TranslatorInterface getTranslator()                                                                                                                    Get the default translator instance in use.
81
 * @method int                                                getWeekEndsAt()                                                                                                                    Get the last day of week
82
 * @method int                                                getWeekStartsAt()                                                                                                                  Get the first day of week
83
 * @method array                                              getWeekendDays()                                                                                                                   Get weekend days
84
 * @method bool                                               hasFormat($date, $format)                                                                                                          Checks if the (date)time string is in a given format.
85
 * @method bool                                               hasFormatWithModifiers($date, $format)                                                                                             Checks if the (date)time string is in a given format.
86
 * @method bool                                               hasMacro($name)                                                                                                                    Checks if macro is registered globally.
87
 * @method bool                                               hasRelativeKeywords($time)                                                                                                         Determine if a time string will produce a relative date.
88
 * @method bool                                               hasTestNow()                                                                                                                       Determine if there is a valid test instance set. A valid test instance
89
 *                                                                                                                                                                                               is anything that is not null.
90
 * @method Carbon                                             instance($date)                                                                                                                    Create a Carbon instance from a DateTime one.
91
 * @method bool                                               isImmutable()                                                                                                                      Returns true if the current class/instance is immutable.
92
 * @method bool                                               isModifiableUnit($unit)                                                                                                            Returns true if a property can be changed via setter.
93
 * @method bool                                               isMutable()                                                                                                                        Returns true if the current class/instance is mutable.
94
 * @method bool                                               isStrictModeEnabled()                                                                                                              Returns true if the strict mode is globally in use, false else.
95
 *                                                                                                                                                                                               (It can be overridden in specific instances.)
96
 * @method bool                                               localeHasDiffOneDayWords($locale)                                                                                                  Returns true if the given locale is internally supported and has words for 1-day diff (just now, yesterday, tomorrow).
97
 *                                                                                                                                                                                               Support is considered enabled if the 3 words are translated in the given locale.
98
 * @method bool                                               localeHasDiffSyntax($locale)                                                                                                       Returns true if the given locale is internally supported and has diff syntax support (ago, from now, before, after).
99
 *                                                                                                                                                                                               Support is considered enabled if the 4 sentences are translated in the given locale.
100
 * @method bool                                               localeHasDiffTwoDayWords($locale)                                                                                                  Returns true if the given locale is internally supported and has words for 2-days diff (before yesterday, after tomorrow).
101
 *                                                                                                                                                                                               Support is considered enabled if the 2 words are translated in the given locale.
102
 * @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).
103
 *                                                                                                                                                                                               Support is considered enabled if the 4 sentences are translated in the given locale.
104
 * @method bool                                               localeHasShortUnits($locale)                                                                                                       Returns true if the given locale is internally supported and has short-units support.
105
 *                                                                                                                                                                                               Support is considered enabled if either year, day or hour has a short variant translated.
106
 * @method void                                               macro($name, $macro)                                                                                                               Register a custom macro.
107
 * @method Carbon|null                                        make($var)                                                                                                                         Make a Carbon instance from given variable if possible.
108
 *                                                                                                                                                                                               Always return a new instance. Parse only strings and only these likely to be dates (skip intervals
109
 *                                                                                                                                                                                               and recurrences). Throw an exception for invalid format, but otherwise return null.
110
 * @method Carbon                                             maxValue()                                                                                                                         Create a Carbon instance for the greatest supported date.
111
 * @method Carbon                                             minValue()                                                                                                                         Create a Carbon instance for the lowest supported date.
112
 * @method void                                               mixin($mixin)                                                                                                                      Mix another object into the class.
113
 * @method Carbon                                             now($tz = null)                                                                                                                    Get a Carbon instance for the current date and time.
114
 * @method Carbon                                             parse($time = null, $tz = null)                                                                                                    Create a carbon instance from a string.
115
 *                                                                                                                                                                                               This is an alias for the constructor that allows better fluent syntax
116
 *                                                                                                                                                                                               as it allows you to do Carbon::parse('Monday next week')->fn() rather
117
 *                                                                                                                                                                                               than (new Carbon('Monday next week'))->fn().
118
 * @method Carbon                                             parseFromLocale($time, $locale = null, $tz = null)                                                                                 Create a carbon instance from a localized string (in French, Japanese, Arabic, etc.).
119
 * @method string                                             pluralUnit(string $unit)                                                                                                           Returns standardized plural of a given singular/plural unit name (in English).
120
 * @method Carbon|false                                       rawCreateFromFormat($format, $time, $tz = null)                                                                                    Create a Carbon instance from a specific format.
121
 * @method Carbon                                             rawParse($time = null, $tz = null)                                                                                                 Create a carbon instance from a string.
122
 *                                                                                                                                                                                               This is an alias for the constructor that allows better fluent syntax
123
 *                                                                                                                                                                                               as it allows you to do Carbon::parse('Monday next week')->fn() rather
124
 *                                                                                                                                                                                               than (new Carbon('Monday next week'))->fn().
125
 * @method Carbon                                             resetMacros()                                                                                                                      Remove all macros and generic macros.
126
 * @method void                                               resetMonthsOverflow()                                                                                                              @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
127
 *                                                                                                                                                                                                           You should rather use the ->settings() method.
128
 *                                                                                                                                                                                                           Or you can use method variants: addMonthsWithOverflow/addMonthsNoOverflow, same variants
129
 *                                                                                                                                                                                                           are available for quarters, years, decade, centuries, millennia (singular and plural forms).
130
 * @method void                                               resetToStringFormat()                                                                                                              Reset the format used to the default when type juggling a Carbon instance to a string
131
 * @method void                                               resetYearsOverflow()                                                                                                               @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
132
 *                                                                                                                                                                                                           You should rather use the ->settings() method.
133
 *                                                                                                                                                                                                           Or you can use method variants: addYearsWithOverflow/addYearsNoOverflow, same variants
134
 *                                                                                                                                                                                                           are available for quarters, years, decade, centuries, millennia (singular and plural forms).
135
 * @method void                                               serializeUsing($callback)                                                                                                          @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
136
 *                                                                                                                                                                                                           You should rather transform Carbon object before the serialization.
137
 *                                                                                                                                                                                               JSON serialize all Carbon instances using the given callback.
138
 * @method Carbon                                             setFallbackLocale($locale)                                                                                                         Set the fallback locale.
139
 * @method Carbon                                             setHumanDiffOptions($humanDiffOptions)                                                                                             @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
140
 *                                                                                                                                                                                                           You should rather use the ->settings() method.
141
 * @method bool                                               setLocale($locale)                                                                                                                 Set the current translator locale and indicate if the source locale file exists.
142
 *                                                                                                                                                                                               Pass 'auto' as locale to use closest language from the current LC_TIME locale.
143
 * @method void                                               setMidDayAt($hour)                                                                                                                 @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
144
 *                                                                                                                                                                                                           You should rather consider mid-day is always 12pm, then if you need to test if it's an other
145
 *                                                                                                                                                                                                           hour, test it explicitly:
146
 *                                                                                                                                                                                                               $date->format('G') == 13
147
 *                                                                                                                                                                                                           or to set explicitly to a given hour:
148
 *                                                                                                                                                                                                               $date->setTime(13, 0, 0, 0)
149
 *                                                                                                                                                                                               Set midday/noon hour
150
 * @method Carbon                                             setTestNow($testNow = null)                                                                                                        Set a Carbon instance (real or mock) to be returned when a "now"
151
 *                                                                                                                                                                                               instance is created.  The provided instance will be returned
152
 *                                                                                                                                                                                               specifically under the following conditions:
153
 *                                                                                                                                                                                                 - A call to the static now() method, ex. Carbon::now()
154
 *                                                                                                                                                                                                 - When a null (or blank string) is passed to the constructor or parse(), ex. new Carbon(null)
155
 *                                                                                                                                                                                                 - When the string "now" is passed to the constructor or parse(), ex. new Carbon('now')
156
 *                                                                                                                                                                                                 - When a string containing the desired time is passed to Carbon::parse().
157
 *                                                                                                                                                                                               Note the timezone parameter was left out of the examples above and
158
 *                                                                                                                                                                                               has no affect as the mock value will be returned regardless of its value.
159
 *                                                                                                                                                                                               To clear the test instance call this method using the default
160
 *                                                                                                                                                                                               parameter of null.
161
 *                                                                                                                                                                                               /!\ Use this method for unit tests only.
162
 * @method void                                               setToStringFormat($format)                                                                                                         @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
163
 *                                                                                                                                                                                                           You should rather let Carbon object being casted to string with DEFAULT_TO_STRING_FORMAT, and
164
 *                                                                                                                                                                                                           use other method or custom format passed to format() method if you need to dump an other string
165
 *                                                                                                                                                                                                           format.
166
 *                                                                                                                                                                                               Set the default format used when type juggling a Carbon instance to a string
167
 * @method void                                               setTranslator(\Symfony\Component\Translation\TranslatorInterface $translator)                                                      Set the default translator instance to use.
168
 * @method Carbon                                             setUtf8($utf8)                                                                                                                     @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
169
 *                                                                                                                                                                                                           You should rather use UTF-8 language packages on every machine.
170
 *                                                                                                                                                                                               Set if UTF8 will be used for localized date/time.
171
 * @method void                                               setWeekEndsAt($day)                                                                                                                @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
172
 *                                                                                                                                                                                                           Use $weekStartsAt optional parameter instead when using startOfWeek, floorWeek, ceilWeek
173
 *                                                                                                                                                                                                           or roundWeek method. You can also use the 'first_day_of_week' locale setting to change the
174
 *                                                                                                                                                                                                           start of week according to current locale selected and implicitly the end of week.
175
 *                                                                                                                                                                                               Set the last day of week
176
 * @method void                                               setWeekStartsAt($day)                                                                                                              @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
177
 *                                                                                                                                                                                                           Use $weekEndsAt optional parameter instead when using endOfWeek method. You can also use the
178
 *                                                                                                                                                                                                           'first_day_of_week' locale setting to change the start of week according to current locale
179
 *                                                                                                                                                                                                           selected and implicitly the end of week.
180
 *                                                                                                                                                                                               Set the first day of week
181
 * @method void                                               setWeekendDays($days)                                                                                                              @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
182
 *                                                                                                                                                                                                           You should rather consider week-end is always saturday and sunday, and if you have some custom
183
 *                                                                                                                                                                                                           week-end days to handle, give to those days an other name and create a macro for them:
184
 *                                                                                                                                                                                                           ```
185
 *                                                                                                                                                                                                           Carbon::macro('isDayOff', function ($date) {
186
 *                                                                                                                                                                                                               return $date->isSunday() || $date->isMonday();
187
 *                                                                                                                                                                                                           });
188
 *                                                                                                                                                                                                           Carbon::macro('isNotDayOff', function ($date) {
189
 *                                                                                                                                                                                                               return !$date->isDayOff();
190
 *                                                                                                                                                                                                           });
191
 *                                                                                                                                                                                                           if ($someDate->isDayOff()) ...
192
 *                                                                                                                                                                                                           if ($someDate->isNotDayOff()) ...
193
 *                                                                                                                                                                                                           // Add 5 not-off days
194
 *                                                                                                                                                                                                           $count = 5;
195
 *                                                                                                                                                                                                           while ($someDate->isDayOff() || ($count-- > 0)) {
196
 *                                                                                                                                                                                                               $someDate->addDay();
197
 *                                                                                                                                                                                                           }
198
 *                                                                                                                                                                                                           ```
199
 *                                                                                                                                                                                               Set weekend days
200
 * @method bool                                               shouldOverflowMonths()                                                                                                             Get the month overflow global behavior (can be overridden in specific instances).
201
 * @method bool                                               shouldOverflowYears()                                                                                                              Get the month overflow global behavior (can be overridden in specific instances).
202
 * @method string                                             singularUnit(string $unit)                                                                                                         Returns standardized singular of a given singular/plural unit name (in English).
203
 * @method Carbon                                             today($tz = null)                                                                                                                  Create a Carbon instance for today.
204
 * @method Carbon                                             tomorrow($tz = null)                                                                                                               Create a Carbon instance for tomorrow.
205
 * @method string                                             translateTimeString($timeString, $from = null, $to = null, $mode = CarbonInterface::TRANSLATE_ALL)                                 Translate a time string from a locale to an other.
206
 * @method string                                             translateWith(\Symfony\Component\Translation\TranslatorInterface $translator, string $key, array $parameters = [], $number = null) Translate using translation string or callback available.
207
 * @method void                                               useMonthsOverflow($monthsOverflow = true)                                                                                          @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
208
 *                                                                                                                                                                                                           You should rather use the ->settings() method.
209
 *                                                                                                                                                                                                           Or you can use method variants: addMonthsWithOverflow/addMonthsNoOverflow, same variants
210
 *                                                                                                                                                                                                           are available for quarters, years, decade, centuries, millennia (singular and plural forms).
211
 * @method Carbon                                             useStrictMode($strictModeEnabled = true)                                                                                           @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
212
 *                                                                                                                                                                                                           You should rather use the ->settings() method.
213
 * @method void                                               useYearsOverflow($yearsOverflow = true)                                                                                            @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
214
 *                                                                                                                                                                                                           You should rather use the ->settings() method.
215
 *                                                                                                                                                                                                           Or you can use method variants: addYearsWithOverflow/addYearsNoOverflow, same variants
216
 *                                                                                                                                                                                                           are available for quarters, years, decade, centuries, millennia (singular and plural forms).
217
 * @method Carbon                                             withTestNow($testNow = null, $callback = null)                                                                                     Temporarily sets a static date to be used within the callback.
218
 *                                                                                                                                                                                               Using setTestNow to set the date, executing the callback, then
219
 *                                                                                                                                                                                               clearing the test instance.
220
 *                                                                                                                                                                                               /!\ Use this method for unit tests only.
221
 * @method Carbon                                             yesterday($tz = null)                                                                                                              Create a Carbon instance for yesterday.
222
 *
223
 * </autodoc>
224
 */
225
class Factory
226
{
227
    protected $className = Carbon::class;
228

229
    protected $settings = [];
230

231 1
    public function __construct(array $settings = [], string $className = null)
232
    {
233 1
        if ($className) {
234 1
            $this->className = $className;
235
        }
236

237 1
        $this->settings = $settings;
238
    }
239

240 1
    public function getClassName()
241
    {
242 1
        return $this->className;
243
    }
244

245 1
    public function setClassName(string $className)
246
    {
247 1
        $this->className = $className;
248

249 1
        return $this;
250
    }
251

252 1
    public function className(string $className = null)
253
    {
254 1
        return $className === null ? $this->getClassName() : $this->setClassName($className);
255
    }
256

257 1
    public function getSettings()
258
    {
259 1
        return $this->settings;
260
    }
261

262 1
    public function setSettings(array $settings)
263
    {
264 1
        $this->settings = $settings;
265

266 1
        return $this;
267
    }
268

269 1
    public function settings(array $settings = null)
270
    {
271 1
        return $settings === null ? $this->getSettings() : $this->setSettings($settings);
272
    }
273

274 1
    public function mergeSettings(array $settings)
275
    {
276 1
        $this->settings = array_merge($this->settings, $settings);
277

278 1
        return $this;
279
    }
280

281 1
    public function __call($name, $arguments)
282
    {
283 1
        $method = new ReflectionMethod($this->className, $name);
284 1
        $settings = $this->settings;
285

286 1
        if ($settings && isset($settings['timezone'])) {
287
            $tzParameters = array_filter($method->getParameters(), function ($parameter) {
288 1
                return \in_array($parameter->getName(), ['tz', 'timezone'], true);
289 1
            });
290

291 1
            if (\count($tzParameters)) {
292 1
                array_splice($arguments, key($tzParameters), 0, [$settings['timezone']]);
293 1
                unset($settings['timezone']);
294
            }
295
        }
296

297 1
        $result = $this->className::$name(...$arguments);
298

299 1
        return $result instanceof CarbonInterface && !empty($settings)
300 1
            ? $result->settings($settings)
301 1
            : $result;
302
    }
303
}

Read our documentation on viewing source code .

Loading