Factory.php 56 KB

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