resolved conflicts

This commit is contained in:
2025-03-31 03:46:05 +03:00
6454 changed files with 1520539 additions and 9 deletions
@@ -0,0 +1,400 @@
<?php
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Carbon;
use Carbon\MessageFormatter\MessageFormatterMapper;
use Closure;
use ReflectionException;
use ReflectionFunction;
use Symfony\Component\Translation;
use Symfony\Component\Translation\Formatter\MessageFormatterInterface;
use Symfony\Component\Translation\Loader\ArrayLoader;
abstract class AbstractTranslator extends Translation\Translator
{
/**
* Translator singletons for each language.
*
* @var array
*/
protected static $singletons = [];
/**
* List of custom localized messages.
*
* @var array
*/
protected $messages = [];
/**
* List of custom directories that contain translation files.
*
* @var string[]
*/
protected $directories = [];
/**
* Set to true while constructing.
*
* @var bool
*/
protected $initializing = false;
/**
* List of locales aliases.
*
* @var array<string, string>
*/
protected $aliases = [
'me' => 'sr_Latn_ME',
'scr' => 'sh',
];
/**
* Return a singleton instance of Translator.
*
* @param string|null $locale optional initial locale ("en" - english by default)
*
* @return static
*/
public static function get($locale = null)
{
$locale = $locale ?: 'en';
$key = static::class === Translator::class ? $locale : static::class.'|'.$locale;
if (!isset(static::$singletons[$key])) {
static::$singletons[$key] = new static($locale);
}
return static::$singletons[$key];
}
public function __construct($locale, MessageFormatterInterface $formatter = null, $cacheDir = null, $debug = false)
{
parent::setLocale($locale);
$this->initializing = true;
$this->directories = [__DIR__.'/Lang'];
$this->addLoader('array', new ArrayLoader());
parent::__construct($locale, new MessageFormatterMapper($formatter), $cacheDir, $debug);
$this->initializing = false;
}
/**
* Returns the list of directories translation files are searched in.
*
* @return array
*/
public function getDirectories(): array
{
return $this->directories;
}
/**
* Set list of directories translation files are searched in.
*
* @param array $directories new directories list
*
* @return $this
*/
public function setDirectories(array $directories)
{
$this->directories = $directories;
return $this;
}
/**
* Add a directory to the list translation files are searched in.
*
* @param string $directory new directory
*
* @return $this
*/
public function addDirectory(string $directory)
{
$this->directories[] = $directory;
return $this;
}
/**
* Remove a directory from the list translation files are searched in.
*
* @param string $directory directory path
*
* @return $this
*/
public function removeDirectory(string $directory)
{
$search = rtrim(strtr($directory, '\\', '/'), '/');
return $this->setDirectories(array_filter($this->getDirectories(), function ($item) use ($search) {
return rtrim(strtr($item, '\\', '/'), '/') !== $search;
}));
}
/**
* Reset messages of a locale (all locale if no locale passed).
* Remove custom messages and reload initial messages from matching
* file in Lang directory.
*
* @param string|null $locale
*
* @return bool
*/
public function resetMessages($locale = null)
{
if ($locale === null) {
$this->messages = [];
return true;
}
$this->assertValidLocale($locale);
foreach ($this->getDirectories() as $directory) {
$data = @include sprintf('%s/%s.php', rtrim($directory, '\\/'), $locale);
if ($data !== false) {
$this->messages[$locale] = $data;
$this->addResource('array', $this->messages[$locale], $locale);
return true;
}
}
return false;
}
/**
* Returns the list of files matching a given locale prefix (or all if empty).
*
* @param string $prefix prefix required to filter result
*
* @return array
*/
public function getLocalesFiles($prefix = '')
{
$files = [];
foreach ($this->getDirectories() as $directory) {
$directory = rtrim($directory, '\\/');
foreach (glob("$directory/$prefix*.php") as $file) {
$files[] = $file;
}
}
return array_unique($files);
}
/**
* Returns the list of internally available locales and already loaded custom locales.
* (It will ignore custom translator dynamic loading.)
*
* @param string $prefix prefix required to filter result
*
* @return array
*/
public function getAvailableLocales($prefix = '')
{
$locales = [];
foreach ($this->getLocalesFiles($prefix) as $file) {
$locales[] = substr($file, strrpos($file, '/') + 1, -4);
}
return array_unique(array_merge($locales, array_keys($this->messages)));
}
protected function translate(?string $id, array $parameters = [], ?string $domain = null, ?string $locale = null): string
{
if ($domain === null) {
$domain = 'messages';
}
$catalogue = $this->getCatalogue($locale);
$format = $this instanceof TranslatorStrongTypeInterface
? $this->getFromCatalogue($catalogue, (string) $id, $domain)
: $this->getCatalogue($locale)->get((string) $id, $domain); // @codeCoverageIgnore
if ($format instanceof Closure) {
// @codeCoverageIgnoreStart
try {
$count = (new ReflectionFunction($format))->getNumberOfRequiredParameters();
} catch (ReflectionException $exception) {
$count = 0;
}
// @codeCoverageIgnoreEnd
return $format(
...array_values($parameters),
...array_fill(0, max(0, $count - \count($parameters)), null)
);
}
return parent::trans($id, $parameters, $domain, $locale);
}
/**
* Init messages language from matching file in Lang directory.
*
* @param string $locale
*
* @return bool
*/
protected function loadMessagesFromFile($locale)
{
return isset($this->messages[$locale]) || $this->resetMessages($locale);
}
/**
* Set messages of a locale and take file first if present.
*
* @param string $locale
* @param array $messages
*
* @return $this
*/
public function setMessages($locale, $messages)
{
$this->loadMessagesFromFile($locale);
$this->addResource('array', $messages, $locale);
$this->messages[$locale] = array_merge(
$this->messages[$locale] ?? [],
$messages
);
return $this;
}
/**
* Set messages of the current locale and take file first if present.
*
* @param array $messages
*
* @return $this
*/
public function setTranslations($messages)
{
return $this->setMessages($this->getLocale(), $messages);
}
/**
* Get messages of a locale, if none given, return all the
* languages.
*
* @param string|null $locale
*
* @return array
*/
public function getMessages($locale = null)
{
return $locale === null ? $this->messages : $this->messages[$locale];
}
/**
* Set the current translator locale and indicate if the source locale file exists
*
* @param string $locale locale ex. en
*
* @return bool
*/
public function setLocale($locale)
{
$locale = preg_replace_callback('/[-_]([a-z]{2,}|\d{2,})/', function ($matches) {
// _2-letters or YUE is a region, _3+-letters is a variant
$upper = strtoupper($matches[1]);
if ($upper === 'YUE' || $upper === 'ISO' || \strlen($upper) < 3) {
return "_$upper";
}
return '_'.ucfirst($matches[1]);
}, strtolower($locale));
$previousLocale = $this->getLocale();
if ($previousLocale === $locale && isset($this->messages[$locale])) {
return true;
}
unset(static::$singletons[$previousLocale]);
if ($locale === 'auto') {
$completeLocale = setlocale(LC_TIME, '0');
$locale = preg_replace('/^([^_.-]+).*$/', '$1', $completeLocale);
$locales = $this->getAvailableLocales($locale);
$completeLocaleChunks = preg_split('/[_.-]+/', $completeLocale);
$getScore = function ($language) use ($completeLocaleChunks) {
return self::compareChunkLists($completeLocaleChunks, preg_split('/[_.-]+/', $language));
};
usort($locales, function ($first, $second) use ($getScore) {
return $getScore($second) <=> $getScore($first);
});
$locale = $locales[0];
}
if (isset($this->aliases[$locale])) {
$locale = $this->aliases[$locale];
}
// If subtag (ex: en_CA) first load the macro (ex: en) to have a fallback
if (str_contains($locale, '_') &&
$this->loadMessagesFromFile($macroLocale = preg_replace('/^([^_]+).*$/', '$1', $locale))
) {
parent::setLocale($macroLocale);
}
if (!$this->loadMessagesFromFile($locale) && !$this->initializing) {
return false;
}
parent::setLocale($locale);
return true;
}
/**
* Show locale on var_dump().
*
* @return array
*/
public function __debugInfo()
{
return [
'locale' => $this->getLocale(),
];
}
private static function compareChunkLists($referenceChunks, $chunks)
{
$score = 0;
foreach ($referenceChunks as $index => $chunk) {
if (!isset($chunks[$index])) {
$score++;
continue;
}
if (strtolower($chunks[$index]) === strtolower($chunk)) {
$score += 10;
}
}
return $score;
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,471 @@
<?php
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Carbon\Traits;
use Carbon\CarbonInterface;
use DateTimeInterface;
use Throwable;
/**
* Trait Options.
*
* Embed base methods to change settings of Carbon classes.
*
* Depends on the following methods:
*
* @method static shiftTimezone($timezone) Set the timezone
*/
trait Options
{
use Localization;
/**
* Customizable PHP_INT_SIZE override.
*
* @var int
*/
public static $PHPIntSize = PHP_INT_SIZE;
/**
* First day of week.
*
* @var int|string
*/
protected static $weekStartsAt = CarbonInterface::MONDAY;
/**
* Last day of week.
*
* @var int|string
*/
protected static $weekEndsAt = CarbonInterface::SUNDAY;
/**
* Days of weekend.
*
* @var array
*/
protected static $weekendDays = [
CarbonInterface::SATURDAY,
CarbonInterface::SUNDAY,
];
/**
* Format regex patterns.
*
* @var array<string, string>
*/
protected static $regexFormats = [
'd' => '(3[01]|[12][0-9]|0[1-9])',
'D' => '(Sun|Mon|Tue|Wed|Thu|Fri|Sat)',
'j' => '([123][0-9]|[1-9])',
'l' => '([a-zA-Z]{2,})',
'N' => '([1-7])',
'S' => '(st|nd|rd|th)',
'w' => '([0-6])',
'z' => '(36[0-5]|3[0-5][0-9]|[12][0-9]{2}|[1-9]?[0-9])',
'W' => '(5[012]|[1-4][0-9]|0?[1-9])',
'F' => '([a-zA-Z]{2,})',
'm' => '(1[012]|0[1-9])',
'M' => '([a-zA-Z]{3})',
'n' => '(1[012]|[1-9])',
't' => '(2[89]|3[01])',
'L' => '(0|1)',
'o' => '([1-9][0-9]{0,4})',
'Y' => '([1-9]?[0-9]{4})',
'y' => '([0-9]{2})',
'a' => '(am|pm)',
'A' => '(AM|PM)',
'B' => '([0-9]{3})',
'g' => '(1[012]|[1-9])',
'G' => '(2[0-3]|1?[0-9])',
'h' => '(1[012]|0[1-9])',
'H' => '(2[0-3]|[01][0-9])',
'i' => '([0-5][0-9])',
's' => '([0-5][0-9])',
'u' => '([0-9]{1,6})',
'v' => '([0-9]{1,3})',
'e' => '([a-zA-Z]{1,5})|([a-zA-Z]*\\/[a-zA-Z]*)',
'I' => '(0|1)',
'O' => '([+-](1[0123]|0[0-9])[0134][05])',
'P' => '([+-](1[0123]|0[0-9]):[0134][05])',
'p' => '(Z|[+-](1[0123]|0[0-9]):[0134][05])',
'T' => '([a-zA-Z]{1,5})',
'Z' => '(-?[1-5]?[0-9]{1,4})',
'U' => '([0-9]*)',
// The formats below are combinations of the above formats.
'c' => '(([1-9]?[0-9]{4})-(1[012]|0[1-9])-(3[01]|[12][0-9]|0[1-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])[+-](1[012]|0[0-9]):([0134][05]))', // Y-m-dTH:i:sP
'r' => '(([a-zA-Z]{3}), ([123][0-9]|0[1-9]) ([a-zA-Z]{3}) ([1-9]?[0-9]{4}) (2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9]) [+-](1[012]|0[0-9])([0134][05]))', // D, d M Y H:i:s O
];
/**
* Format modifiers (such as available in createFromFormat) regex patterns.
*
* @var array
*/
protected static $regexFormatModifiers = [
'*' => '.+',
' ' => '[ ]',
'#' => '[;:\\/.,()-]',
'?' => '([^a]|[a])',
'!' => '',
'|' => '',
'+' => '',
];
/**
* Indicates if months should be calculated with overflow.
* Global setting.
*
* @var bool
*/
protected static $monthsOverflow = true;
/**
* Indicates if years should be calculated with overflow.
* Global setting.
*
* @var bool
*/
protected static $yearsOverflow = true;
/**
* Indicates if the strict mode is in use.
* Global setting.
*
* @var bool
*/
protected static $strictModeEnabled = true;
/**
* Function to call instead of format.
*
* @var string|callable|null
*/
protected static $formatFunction;
/**
* Function to call instead of createFromFormat.
*
* @var string|callable|null
*/
protected static $createFromFormatFunction;
/**
* Function to call instead of parse.
*
* @var string|callable|null
*/
protected static $parseFunction;
/**
* Indicates if months should be calculated with overflow.
* Specific setting.
*
* @var bool|null
*/
protected $localMonthsOverflow;
/**
* Indicates if years should be calculated with overflow.
* Specific setting.
*
* @var bool|null
*/
protected $localYearsOverflow;
/**
* Indicates if the strict mode is in use.
* Specific setting.
*
* @var bool|null
*/
protected $localStrictModeEnabled;
/**
* Options for diffForHumans and forHumans methods.
*
* @var bool|null
*/
protected $localHumanDiffOptions;
/**
* Format to use on string cast.
*
* @var string|null
*/
protected $localToStringFormat;
/**
* Format to use on JSON serialization.
*
* @var string|null
*/
protected $localSerializer;
/**
* Instance-specific macros.
*
* @var array|null
*/
protected $localMacros;
/**
* Instance-specific generic macros.
*
* @var array|null
*/
protected $localGenericMacros;
/**
* Function to call instead of format.
*
* @var string|callable|null
*/
protected $localFormatFunction;
/**
* @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
* You should rather use the ->settings() method.
* @see settings
*
* Enable the strict mode (or disable with passing false).
*
* @param bool $strictModeEnabled
*/
public static function useStrictMode($strictModeEnabled = true)
{
static::$strictModeEnabled = $strictModeEnabled;
}
/**
* Returns true if the strict mode is globally in use, false else.
* (It can be overridden in specific instances.)
*
* @return bool
*/
public static function isStrictModeEnabled()
{
return static::$strictModeEnabled;
}
/**
* @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
* You should rather use the ->settings() method.
* Or you can use method variants: addMonthsWithOverflow/addMonthsNoOverflow, same variants
* are available for quarters, years, decade, centuries, millennia (singular and plural forms).
* @see settings
*
* Indicates if months should be calculated with overflow.
*
* @param bool $monthsOverflow
*
* @return void
*/
public static function useMonthsOverflow($monthsOverflow = true)
{
static::$monthsOverflow = $monthsOverflow;
}
/**
* @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
* You should rather use the ->settings() method.
* Or you can use method variants: addMonthsWithOverflow/addMonthsNoOverflow, same variants
* are available for quarters, years, decade, centuries, millennia (singular and plural forms).
* @see settings
*
* Reset the month overflow behavior.
*
* @return void
*/
public static function resetMonthsOverflow()
{
static::$monthsOverflow = true;
}
/**
* Get the month overflow global behavior (can be overridden in specific instances).
*
* @return bool
*/
public static function shouldOverflowMonths()
{
return static::$monthsOverflow;
}
/**
* @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
* You should rather use the ->settings() method.
* Or you can use method variants: addYearsWithOverflow/addYearsNoOverflow, same variants
* are available for quarters, years, decade, centuries, millennia (singular and plural forms).
* @see settings
*
* Indicates if years should be calculated with overflow.
*
* @param bool $yearsOverflow
*
* @return void
*/
public static function useYearsOverflow($yearsOverflow = true)
{
static::$yearsOverflow = $yearsOverflow;
}
/**
* @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
* You should rather use the ->settings() method.
* Or you can use method variants: addYearsWithOverflow/addYearsNoOverflow, same variants
* are available for quarters, years, decade, centuries, millennia (singular and plural forms).
* @see settings
*
* Reset the month overflow behavior.
*
* @return void
*/
public static function resetYearsOverflow()
{
static::$yearsOverflow = true;
}
/**
* Get the month overflow global behavior (can be overridden in specific instances).
*
* @return bool
*/
public static function shouldOverflowYears()
{
return static::$yearsOverflow;
}
/**
* Set specific options.
* - strictMode: true|false|null
* - monthOverflow: true|false|null
* - yearOverflow: true|false|null
* - humanDiffOptions: int|null
* - toStringFormat: string|Closure|null
* - toJsonFormat: string|Closure|null
* - locale: string|null
* - timezone: \DateTimeZone|string|int|null
* - macros: array|null
* - genericMacros: array|null
*
* @param array $settings
*
* @return $this|static
*/
public function settings(array $settings)
{
$this->localStrictModeEnabled = $settings['strictMode'] ?? null;
$this->localMonthsOverflow = $settings['monthOverflow'] ?? null;
$this->localYearsOverflow = $settings['yearOverflow'] ?? null;
$this->localHumanDiffOptions = $settings['humanDiffOptions'] ?? null;
$this->localToStringFormat = $settings['toStringFormat'] ?? null;
$this->localSerializer = $settings['toJsonFormat'] ?? null;
$this->localMacros = $settings['macros'] ?? null;
$this->localGenericMacros = $settings['genericMacros'] ?? null;
$this->localFormatFunction = $settings['formatFunction'] ?? null;
if (isset($settings['locale'])) {
$locales = $settings['locale'];
if (!\is_array($locales)) {
$locales = [$locales];
}
$this->locale(...$locales);
}
if (isset($settings['innerTimezone'])) {
return $this->setTimezone($settings['innerTimezone']);
}
if (isset($settings['timezone'])) {
return $this->shiftTimezone($settings['timezone']);
}
return $this;
}
/**
* Returns current local settings.
*
* @return array
*/
public function getSettings()
{
$settings = [];
$map = [
'localStrictModeEnabled' => 'strictMode',
'localMonthsOverflow' => 'monthOverflow',
'localYearsOverflow' => 'yearOverflow',
'localHumanDiffOptions' => 'humanDiffOptions',
'localToStringFormat' => 'toStringFormat',
'localSerializer' => 'toJsonFormat',
'localMacros' => 'macros',
'localGenericMacros' => 'genericMacros',
'locale' => 'locale',
'tzName' => 'timezone',
'localFormatFunction' => 'formatFunction',
];
foreach ($map as $property => $key) {
$value = $this->$property ?? null;
if ($value !== null && ($key !== 'locale' || $value !== 'en' || $this->localTranslator)) {
$settings[$key] = $value;
}
}
return $settings;
}
/**
* Show truthy properties on var_dump().
*
* @return array
*/
public function __debugInfo()
{
$infos = array_filter(get_object_vars($this), static function ($var) {
return $var;
});
foreach (['dumpProperties', 'constructedObjectId', 'constructed'] as $property) {
if (isset($infos[$property])) {
unset($infos[$property]);
}
}
$this->addExtraDebugInfos($infos);
return $infos;
}
protected function addExtraDebugInfos(&$infos): void
{
if ($this instanceof DateTimeInterface) {
try {
if (!isset($infos['date'])) {
$infos['date'] = $this->format(CarbonInterface::MOCK_DATETIME_FORMAT);
}
if (!isset($infos['timezone'])) {
$infos['timezone'] = $this->tzName;
}
} catch (Throwable $exception) {
// noop
}
}
}
}