Update dependencies

This commit is contained in:
Chris Hunt
2024-02-16 21:36:54 +00:00
parent 22d7a59e59
commit d52ae0d3c3
9569 changed files with 460443 additions and 282416 deletions

View File

@@ -39,8 +39,8 @@ abstract class AbstractString implements \Stringable, \JsonSerializable
public const PREG_SPLIT_DELIM_CAPTURE = \PREG_SPLIT_DELIM_CAPTURE;
public const PREG_SPLIT_OFFSET_CAPTURE = \PREG_SPLIT_OFFSET_CAPTURE;
protected $string = '';
protected $ignoreCase = false;
protected string $string = '';
protected ?bool $ignoreCase = false;
abstract public function __construct(string $string = '');
@@ -74,7 +74,7 @@ abstract class AbstractString implements \Stringable, \JsonSerializable
foreach ($values as $k => $v) {
if (\is_string($k) && '' !== $k && $k !== $j = (string) new static($k)) {
$keys = $keys ?? array_keys($values);
$keys ??= array_keys($values);
$keys[$i] = $j;
}
@@ -92,15 +92,17 @@ abstract class AbstractString implements \Stringable, \JsonSerializable
/**
* @param string|string[] $needle
*
* @return static
*/
public function after($needle, bool $includeNeedle = false, int $offset = 0): self
public function after(string|iterable $needle, bool $includeNeedle = false, int $offset = 0): static
{
$str = clone $this;
$i = \PHP_INT_MAX;
foreach ((array) $needle as $n) {
if (\is_string($needle)) {
$needle = [$needle];
}
foreach ($needle as $n) {
$n = (string) $n;
$j = $this->indexOf($n, $offset);
@@ -123,15 +125,17 @@ abstract class AbstractString implements \Stringable, \JsonSerializable
/**
* @param string|string[] $needle
*
* @return static
*/
public function afterLast($needle, bool $includeNeedle = false, int $offset = 0): self
public function afterLast(string|iterable $needle, bool $includeNeedle = false, int $offset = 0): static
{
$str = clone $this;
$i = null;
foreach ((array) $needle as $n) {
if (\is_string($needle)) {
$needle = [$needle];
}
foreach ($needle as $n) {
$n = (string) $n;
$j = $this->indexOfLast($n, $offset);
@@ -152,22 +156,21 @@ abstract class AbstractString implements \Stringable, \JsonSerializable
return $this->slice($i);
}
/**
* @return static
*/
abstract public function append(string ...$suffix): self;
abstract public function append(string ...$suffix): static;
/**
* @param string|string[] $needle
*
* @return static
*/
public function before($needle, bool $includeNeedle = false, int $offset = 0): self
public function before(string|iterable $needle, bool $includeNeedle = false, int $offset = 0): static
{
$str = clone $this;
$i = \PHP_INT_MAX;
foreach ((array) $needle as $n) {
if (\is_string($needle)) {
$needle = [$needle];
}
foreach ($needle as $n) {
$n = (string) $n;
$j = $this->indexOf($n, $offset);
@@ -190,15 +193,17 @@ abstract class AbstractString implements \Stringable, \JsonSerializable
/**
* @param string|string[] $needle
*
* @return static
*/
public function beforeLast($needle, bool $includeNeedle = false, int $offset = 0): self
public function beforeLast(string|iterable $needle, bool $includeNeedle = false, int $offset = 0): static
{
$str = clone $this;
$i = null;
foreach ((array) $needle as $n) {
if (\is_string($needle)) {
$needle = [$needle];
}
foreach ($needle as $n) {
$n = (string) $n;
$j = $this->indexOfLast($n, $offset);
@@ -229,20 +234,14 @@ abstract class AbstractString implements \Stringable, \JsonSerializable
return '' === $str->string ? [] : array_values(unpack('C*', $str->string));
}
/**
* @return static
*/
abstract public function camel(): self;
abstract public function camel(): static;
/**
* @return static[]
*/
abstract public function chunk(int $length = 1): array;
/**
* @return static
*/
public function collapseWhitespace(): self
public function collapseWhitespace(): static
{
$str = clone $this;
$str->string = trim(preg_replace("/(?:[ \n\r\t\x0C]{2,}+|[\n\r\t\x0C])/", ' ', $str->string), " \n\r\t\x0C");
@@ -253,7 +252,7 @@ abstract class AbstractString implements \Stringable, \JsonSerializable
/**
* @param string|string[] $needle
*/
public function containsAny($needle): bool
public function containsAny(string|iterable $needle): bool
{
return null !== $this->indexOf($needle);
}
@@ -261,9 +260,9 @@ abstract class AbstractString implements \Stringable, \JsonSerializable
/**
* @param string|string[] $suffix
*/
public function endsWith($suffix): bool
public function endsWith(string|iterable $suffix): bool
{
if (!\is_array($suffix) && !$suffix instanceof \Traversable) {
if (\is_string($suffix)) {
throw new \TypeError(sprintf('Method "%s()" must be overridden by class "%s" to deal with non-iterable values.', __FUNCTION__, static::class));
}
@@ -276,10 +275,7 @@ abstract class AbstractString implements \Stringable, \JsonSerializable
return false;
}
/**
* @return static
*/
public function ensureEnd(string $suffix): self
public function ensureEnd(string $suffix): static
{
if (!$this->endsWith($suffix)) {
return $this->append($suffix);
@@ -291,10 +287,7 @@ abstract class AbstractString implements \Stringable, \JsonSerializable
return $this->replaceMatches($regex.($this->ignoreCase ? 'i' : ''), '$1');
}
/**
* @return static
*/
public function ensureStart(string $prefix): self
public function ensureStart(string $prefix): static
{
$prefix = new static($prefix);
@@ -316,9 +309,9 @@ abstract class AbstractString implements \Stringable, \JsonSerializable
/**
* @param string|string[] $string
*/
public function equalsTo($string): bool
public function equalsTo(string|iterable $string): bool
{
if (!\is_array($string) && !$string instanceof \Traversable) {
if (\is_string($string)) {
throw new \TypeError(sprintf('Method "%s()" must be overridden by class "%s" to deal with non-iterable values.', __FUNCTION__, static::class));
}
@@ -331,15 +324,9 @@ abstract class AbstractString implements \Stringable, \JsonSerializable
return false;
}
/**
* @return static
*/
abstract public function folded(): self;
abstract public function folded(): static;
/**
* @return static
*/
public function ignoreCase(): self
public function ignoreCase(): static
{
$str = clone $this;
$str->ignoreCase = true;
@@ -350,9 +337,9 @@ abstract class AbstractString implements \Stringable, \JsonSerializable
/**
* @param string|string[] $needle
*/
public function indexOf($needle, int $offset = 0): ?int
public function indexOf(string|iterable $needle, int $offset = 0): ?int
{
if (!\is_array($needle) && !$needle instanceof \Traversable) {
if (\is_string($needle)) {
throw new \TypeError(sprintf('Method "%s()" must be overridden by class "%s" to deal with non-iterable values.', __FUNCTION__, static::class));
}
@@ -372,9 +359,9 @@ abstract class AbstractString implements \Stringable, \JsonSerializable
/**
* @param string|string[] $needle
*/
public function indexOfLast($needle, int $offset = 0): ?int
public function indexOfLast(string|iterable $needle, int $offset = 0): ?int
{
if (!\is_array($needle) && !$needle instanceof \Traversable) {
if (\is_string($needle)) {
throw new \TypeError(sprintf('Method "%s()" must be overridden by class "%s" to deal with non-iterable values.', __FUNCTION__, static::class));
}
@@ -396,10 +383,7 @@ abstract class AbstractString implements \Stringable, \JsonSerializable
return '' === $this->string;
}
/**
* @return static
*/
abstract public function join(array $strings, string $lastGlue = null): self;
abstract public function join(array $strings, ?string $lastGlue = null): static;
public function jsonSerialize(): string
{
@@ -408,10 +392,7 @@ abstract class AbstractString implements \Stringable, \JsonSerializable
abstract public function length(): int;
/**
* @return static
*/
abstract public function lower(): self;
abstract public function lower(): static;
/**
* Matches the string using a regular expression.
@@ -422,30 +403,15 @@ abstract class AbstractString implements \Stringable, \JsonSerializable
*/
abstract public function match(string $regexp, int $flags = 0, int $offset = 0): array;
/**
* @return static
*/
abstract public function padBoth(int $length, string $padStr = ' '): self;
abstract public function padBoth(int $length, string $padStr = ' '): static;
/**
* @return static
*/
abstract public function padEnd(int $length, string $padStr = ' '): self;
abstract public function padEnd(int $length, string $padStr = ' '): static;
/**
* @return static
*/
abstract public function padStart(int $length, string $padStr = ' '): self;
abstract public function padStart(int $length, string $padStr = ' '): static;
/**
* @return static
*/
abstract public function prepend(string ...$prefix): self;
abstract public function prepend(string ...$prefix): static;
/**
* @return static
*/
public function repeat(int $multiplier): self
public function repeat(int $multiplier): static
{
if (0 > $multiplier) {
throw new InvalidArgumentException(sprintf('Multiplier must be positive, %d given.', $multiplier));
@@ -457,42 +423,22 @@ abstract class AbstractString implements \Stringable, \JsonSerializable
return $str;
}
/**
* @return static
*/
abstract public function replace(string $from, string $to): self;
abstract public function replace(string $from, string $to): static;
/**
* @param string|callable $to
*
* @return static
*/
abstract public function replaceMatches(string $fromRegexp, $to): self;
abstract public function replaceMatches(string $fromRegexp, string|callable $to): static;
/**
* @return static
*/
abstract public function reverse(): self;
abstract public function reverse(): static;
/**
* @return static
*/
abstract public function slice(int $start = 0, int $length = null): self;
abstract public function slice(int $start = 0, ?int $length = null): static;
/**
* @return static
*/
abstract public function snake(): self;
abstract public function snake(): static;
/**
* @return static
*/
abstract public function splice(string $replacement, int $start = 0, int $length = null): self;
abstract public function splice(string $replacement, int $start = 0, ?int $length = null): static;
/**
* @return static[]
*/
public function split(string $delimiter, int $limit = null, int $flags = null): array
public function split(string $delimiter, ?int $limit = null, ?int $flags = null): array
{
if (null === $flags) {
throw new \TypeError('Split behavior when $flags is null must be implemented by child classes.');
@@ -502,19 +448,11 @@ abstract class AbstractString implements \Stringable, \JsonSerializable
$delimiter .= 'i';
}
set_error_handler(static function ($t, $m) { throw new InvalidArgumentException($m); });
set_error_handler(static fn ($t, $m) => throw new InvalidArgumentException($m));
try {
if (false === $chunks = preg_split($delimiter, $this->string, $limit, $flags)) {
$lastError = preg_last_error();
foreach (get_defined_constants(true)['pcre'] as $k => $v) {
if ($lastError === $v && '_ERROR' === substr($k, -6)) {
throw new RuntimeException('Splitting failed with '.$k.'.');
}
}
throw new RuntimeException('Splitting failed with unknown error code.');
throw new RuntimeException('Splitting failed with error: '.preg_last_error_msg());
}
} finally {
restore_error_handler();
@@ -540,9 +478,9 @@ abstract class AbstractString implements \Stringable, \JsonSerializable
/**
* @param string|string[] $prefix
*/
public function startsWith($prefix): bool
public function startsWith(string|iterable $prefix): bool
{
if (!\is_array($prefix) && !$prefix instanceof \Traversable) {
if (\is_string($prefix)) {
throw new \TypeError(sprintf('Method "%s()" must be overridden by class "%s" to deal with non-iterable values.', __FUNCTION__, static::class));
}
@@ -555,12 +493,9 @@ abstract class AbstractString implements \Stringable, \JsonSerializable
return false;
}
/**
* @return static
*/
abstract public function title(bool $allWords = false): self;
abstract public function title(bool $allWords = false): static;
public function toByteString(string $toEncoding = null): ByteString
public function toByteString(?string $toEncoding = null): ByteString
{
$b = new ByteString();
@@ -572,20 +507,14 @@ abstract class AbstractString implements \Stringable, \JsonSerializable
return $b;
}
set_error_handler(static function ($t, $m) { throw new InvalidArgumentException($m); });
try {
try {
$b->string = mb_convert_encoding($this->string, $toEncoding, 'UTF-8');
} catch (InvalidArgumentException $e) {
if (!\function_exists('iconv')) {
throw $e;
}
$b->string = iconv('UTF-8', $toEncoding, $this->string);
$b->string = mb_convert_encoding($this->string, $toEncoding, 'UTF-8');
} catch (\ValueError $e) {
if (!\function_exists('iconv')) {
throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e);
}
} finally {
restore_error_handler();
$b->string = iconv('UTF-8', $toEncoding, $this->string);
}
return $b;
@@ -606,24 +535,16 @@ abstract class AbstractString implements \Stringable, \JsonSerializable
return new UnicodeString($this->string);
}
/**
* @return static
*/
abstract public function trim(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): self;
abstract public function trim(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): static;
/**
* @return static
*/
abstract public function trimEnd(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): self;
abstract public function trimEnd(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): static;
/**
* @param string|string[] $prefix
*
* @return static
*/
public function trimPrefix($prefix): self
public function trimPrefix($prefix): static
{
if (\is_array($prefix) || $prefix instanceof \Traversable) {
if (\is_array($prefix) || $prefix instanceof \Traversable) { // don't use is_iterable(), it's slow
foreach ($prefix as $s) {
$t = $this->trimPrefix($s);
@@ -650,19 +571,14 @@ abstract class AbstractString implements \Stringable, \JsonSerializable
return $str;
}
/**
* @return static
*/
abstract public function trimStart(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): self;
abstract public function trimStart(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): static;
/**
* @param string|string[] $suffix
*
* @return static
*/
public function trimSuffix($suffix): self
public function trimSuffix($suffix): static
{
if (\is_array($suffix) || $suffix instanceof \Traversable) {
if (\is_array($suffix) || $suffix instanceof \Traversable) { // don't use is_iterable(), it's slow
foreach ($suffix as $s) {
$t = $this->trimSuffix($s);
@@ -689,10 +605,7 @@ abstract class AbstractString implements \Stringable, \JsonSerializable
return $str;
}
/**
* @return static
*/
public function truncate(int $length, string $ellipsis = '', bool $cut = true): self
public function truncate(int $length, string $ellipsis = '', bool $cut = true): static
{
$stringLength = $this->length();
@@ -719,20 +632,14 @@ abstract class AbstractString implements \Stringable, \JsonSerializable
return $ellipsisLength ? $str->trimEnd()->append($ellipsis) : $str;
}
/**
* @return static
*/
abstract public function upper(): self;
abstract public function upper(): static;
/**
* Returns the printable length on a terminal.
*/
abstract public function width(bool $ignoreAnsiDecoration = true): int;
/**
* @return static
*/
public function wordwrap(int $width = 75, string $break = "\n", bool $cut = false): self
public function wordwrap(int $width = 75, string $break = "\n", bool $cut = false): static
{
$lines = '' !== $break ? $this->split($break) : [clone $this];
$chars = [];

View File

@@ -37,25 +37,18 @@ abstract class AbstractUnicodeString extends AbstractString
private const ASCII = "\x20\x65\x69\x61\x73\x6E\x74\x72\x6F\x6C\x75\x64\x5D\x5B\x63\x6D\x70\x27\x0A\x67\x7C\x68\x76\x2E\x66\x62\x2C\x3A\x3D\x2D\x71\x31\x30\x43\x32\x2A\x79\x78\x29\x28\x4C\x39\x41\x53\x2F\x50\x22\x45\x6A\x4D\x49\x6B\x33\x3E\x35\x54\x3C\x44\x34\x7D\x42\x7B\x38\x46\x77\x52\x36\x37\x55\x47\x4E\x3B\x4A\x7A\x56\x23\x48\x4F\x57\x5F\x26\x21\x4B\x3F\x58\x51\x25\x59\x5C\x09\x5A\x2B\x7E\x5E\x24\x40\x60\x7F\x00\x01\x02\x03\x04\x05\x06\x07\x08\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F";
// the subset of folded case mappings that is not in lower case mappings
private const FOLD_FROM = ['İ', 'µ', 'ſ', "\xCD\x85", 'ς', 'ϐ', 'ϑ', 'ϕ', 'ϖ', 'ϰ', 'ϱ', 'ϵ', 'ẛ', "\xE1\xBE\xBE", 'ß', 'İ', 'ʼn', 'ǰ', 'ΐ', 'ΰ', 'և', 'ẖ', 'ẗ', 'ẘ', 'ẙ', 'ẚ', 'ẞ', 'ὐ', 'ὒ', 'ὔ', 'ὖ', 'ᾀ', 'ᾁ', 'ᾂ', 'ᾃ', 'ᾄ', 'ᾅ', 'ᾆ', 'ᾇ', 'ᾈ', 'ᾉ', 'ᾊ', 'ᾋ', 'ᾌ', 'ᾍ', 'ᾎ', 'ᾏ', 'ᾐ', 'ᾑ', 'ᾒ', 'ᾓ', 'ᾔ', 'ᾕ', 'ᾖ', 'ᾗ', 'ᾘ', 'ᾙ', 'ᾚ', 'ᾛ', 'ᾜ', 'ᾝ', 'ᾞ', 'ᾟ', 'ᾠ', 'ᾡ', 'ᾢ', 'ᾣ', 'ᾤ', 'ᾥ', 'ᾦ', 'ᾧ', 'ᾨ', 'ᾩ', 'ᾪ', 'ᾫ', 'ᾬ', 'ᾭ', 'ᾮ', 'ᾯ', 'ᾲ', 'ᾳ', 'ᾴ', 'ᾶ', 'ᾷ', 'ᾼ', 'ῂ', 'ῃ', 'ῄ', 'ῆ', 'ῇ', 'ῌ', 'ῒ', 'ΐ', 'ῖ', 'ῗ', 'ῢ', 'ΰ', 'ῤ', 'ῦ', 'ῧ', 'ῲ', 'ῳ', 'ῴ', 'ῶ', 'ῷ', 'ῼ', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'ſt', 'st', 'ﬓ', 'ﬔ', 'ﬕ', 'ﬖ', 'ﬗ'];
private const FOLD_TO = ['i̇', 'μ', 's', 'ι', 'σ', 'β', 'θ', 'φ', 'π', 'κ', 'ρ', 'ε', 'ṡ', 'ι', 'ss', 'i̇', 'ʼn', 'ǰ', 'ΐ', 'ΰ', 'եւ', 'ẖ', 'ẗ', 'ẘ', 'ẙ', 'aʾ', 'ss', 'ὐ', 'ὒ', 'ὔ', 'ὖ', 'ἀι', 'ἁι', 'ἂι', 'ἃι', 'ἄι', 'ἅι', 'ἆι', 'ἇι', 'ἀι', 'ἁι', 'ἂι', 'ἃι', 'ἄι', 'ἅι', 'ἆι', 'ἇι', 'ἠι', 'ἡι', 'ἢι', 'ἣι', 'ἤι', 'ἥι', 'ἦι', 'ἧι', 'ἠι', 'ἡι', 'ἢι', 'ἣι', 'ἤι', 'ἥι', 'ἦι', 'ἧι', 'ὠι', 'ὡι', 'ὢι', 'ὣι', 'ὤι', 'ὥι', 'ὦι', 'ὧι', 'ὠι', 'ὡι', 'ὢι', 'ὣι', 'ὤι', 'ὥι', 'ὦι', 'ὧι', 'ὰι', 'αι', 'άι', 'ᾶ', 'ᾶι', 'αι', 'ὴι', 'ηι', 'ήι', 'ῆ', 'ῆι', 'ηι', 'ῒ', 'ΐ', 'ῖ', 'ῗ', 'ῢ', 'ΰ', 'ῤ', 'ῦ', 'ῧ', 'ὼι', 'ωι', 'ώι', 'ῶ', 'ῶι', 'ωι', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'st', 'st', 'մն', 'մե', 'մի', 'վն', 'մխ'];
// the subset of upper case mappings that map one code point to many code points
private const UPPER_FROM = ['ß', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'ſt', 'st', 'և', 'ﬓ', 'ﬔ', 'ﬕ', 'ﬖ', 'ﬗ', 'ʼn', 'ΐ', 'ΰ', 'ǰ', 'ẖ', 'ẗ', 'ẘ', 'ẙ', 'ẚ', 'ὐ', 'ὒ', 'ὔ', 'ὖ', 'ᾶ', 'ῆ', 'ῒ', 'ΐ', 'ῖ', 'ῗ', 'ῢ', 'ΰ', 'ῤ', 'ῦ', 'ῧ', 'ῶ'];
private const UPPER_TO = ['SS', 'FF', 'FI', 'FL', 'FFI', 'FFL', 'ST', 'ST', 'ԵՒ', 'ՄՆ', 'ՄԵ', 'ՄԻ', 'ՎՆ', 'ՄԽ', 'ʼN', 'Ϊ́', 'Ϋ́', 'J̌', 'H̱', 'T̈', 'W̊', 'Y̊', 'Aʾ', 'Υ̓', 'Υ̓̀', 'Υ̓́', 'Υ̓͂', 'Α͂', 'Η͂', 'Ϊ̀', 'Ϊ́', 'Ι͂', 'Ϊ͂', 'Ϋ̀', 'Ϋ́', 'Ρ̓', 'Υ͂', 'Ϋ͂', 'Ω͂'];
private const FOLD_FROM = ['İ', 'µ', 'ſ', "\xCD\x85", 'ς', 'ϐ', 'ϑ', 'ϕ', 'ϖ', 'ϰ', 'ϱ', 'ϵ', 'ẛ', "\xE1\xBE\xBE", 'ß', 'ʼn', 'ǰ', 'ΐ', 'ΰ', 'և', 'ẖ', 'ẗ', 'ẘ', 'ẙ', 'ẚ', 'ẞ', 'ὐ', 'ὒ', 'ὔ', 'ὖ', 'ᾀ', 'ᾁ', 'ᾂ', 'ᾃ', 'ᾄ', 'ᾅ', 'ᾆ', 'ᾇ', 'ᾈ', 'ᾉ', 'ᾊ', 'ᾋ', 'ᾌ', 'ᾍ', 'ᾎ', 'ᾏ', 'ᾐ', 'ᾑ', 'ᾒ', 'ᾓ', 'ᾔ', 'ᾕ', 'ᾖ', 'ᾗ', 'ᾘ', 'ᾙ', 'ᾚ', 'ᾛ', 'ᾜ', 'ᾝ', 'ᾞ', 'ᾟ', 'ᾠ', 'ᾡ', 'ᾢ', 'ᾣ', 'ᾤ', 'ᾥ', 'ᾦ', 'ᾧ', 'ᾨ', 'ᾩ', 'ᾪ', 'ᾫ', 'ᾬ', 'ᾭ', 'ᾮ', 'ᾯ', 'ᾲ', 'ᾳ', 'ᾴ', 'ᾶ', 'ᾷ', 'ᾼ', 'ῂ', 'ῃ', 'ῄ', 'ῆ', 'ῇ', 'ῌ', 'ῒ', 'ῖ', 'ῗ', 'ῢ', 'ῤ', 'ῦ', 'ῧ', 'ῲ', 'ῳ', 'ῴ', 'ῶ', 'ῷ', 'ῼ', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'ſt', 'st', 'ﬓ', 'ﬔ', 'ﬕ', 'ﬖ', 'ﬗ'];
private const FOLD_TO = ['i̇', 'μ', 's', 'ι', 'σ', 'β', 'θ', 'φ', 'π', 'κ', 'ρ', 'ε', 'ṡ', 'ι', 'ss', 'ʼn', 'ǰ', 'ΐ', 'ΰ', 'եւ', 'ẖ', 'ẗ', 'ẘ', 'ẙ', 'aʾ', 'ss', 'ὐ', 'ὒ', 'ὔ', 'ὖ', 'ἀι', 'ἁι', 'ἂι', 'ἃι', 'ἄι', 'ἅι', 'ἆι', 'ἇι', 'ἀι', 'ἁι', 'ἂι', 'ἃι', 'ἄι', 'ἅι', 'ἆι', 'ἇι', 'ἠι', 'ἡι', 'ἢι', 'ἣι', 'ἤι', 'ἥι', 'ἦι', 'ἧι', 'ἠι', 'ἡι', 'ἢι', 'ἣι', 'ἤι', 'ἥι', 'ἦι', 'ἧι', 'ὠι', 'ὡι', 'ὢι', 'ὣι', 'ὤι', 'ὥι', 'ὦι', 'ὧι', 'ὠι', 'ὡι', 'ὢι', 'ὣι', 'ὤι', 'ὥι', 'ὦι', 'ὧι', 'ὰι', 'αι', 'άι', 'ᾶ', 'ᾶι', 'αι', 'ὴι', 'ηι', 'ήι', 'ῆ', 'ῆι', 'ηι', 'ῒ', 'ῖ', 'ῗ', 'ῢ', 'ῤ', 'ῦ', 'ῧ', 'ὼι', 'ωι', 'ώι', 'ῶ', 'ῶι', 'ωι', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'st', 'st', 'մն', 'մե', 'մի', 'վն', 'մխ'];
// the subset of https://github.com/unicode-org/cldr/blob/master/common/transforms/Latin-ASCII.xml that is not in NFKD
private const TRANSLIT_FROM = ['Æ', 'Ð', 'Ø', 'Þ', 'ß', 'æ', 'ð', 'ø', 'þ', 'Đ', 'đ', 'Ħ', 'ħ', 'ı', 'ĸ', 'Ŀ', 'ŀ', 'Ł', 'ł', 'ʼn', 'Ŋ', 'ŋ', 'Œ', 'œ', 'Ŧ', 'ŧ', 'ƀ', 'Ɓ', 'Ƃ', 'ƃ', 'Ƈ', 'ƈ', 'Ɖ', 'Ɗ', 'Ƌ', 'ƌ', 'Ɛ', 'Ƒ', 'ƒ', 'Ɠ', 'ƕ', 'Ɩ', 'Ɨ', 'Ƙ', 'ƙ', 'ƚ', 'Ɲ', 'ƞ', 'Ƣ', 'ƣ', 'Ƥ', 'ƥ', 'ƫ', 'Ƭ', 'ƭ', 'Ʈ', 'Ʋ', 'Ƴ', 'ƴ', 'Ƶ', 'ƶ', 'DŽ', 'Dž', 'dž', 'Ǥ', 'ǥ', 'ȡ', 'Ȥ', 'ȥ', 'ȴ', 'ȵ', 'ȶ', 'ȷ', 'ȸ', 'ȹ', 'Ⱥ', 'Ȼ', 'ȼ', 'Ƚ', 'Ⱦ', 'ȿ', 'ɀ', 'Ƀ', 'Ʉ', 'Ɇ', 'ɇ', 'Ɉ', 'ɉ', 'Ɍ', 'ɍ', 'Ɏ', 'ɏ', 'ɓ', 'ɕ', 'ɖ', 'ɗ', 'ɛ', 'ɟ', 'ɠ', 'ɡ', 'ɢ', 'ɦ', 'ɧ', 'ɨ', 'ɪ', 'ɫ', 'ɬ', 'ɭ', 'ɱ', 'ɲ', 'ɳ', 'ɴ', 'ɶ', 'ɼ', 'ɽ', 'ɾ', 'ʀ', 'ʂ', 'ʈ', 'ʉ', 'ʋ', 'ʏ', 'ʐ', 'ʑ', 'ʙ', 'ʛ', 'ʜ', 'ʝ', 'ʟ', 'ʠ', 'ʣ', 'ʥ', 'ʦ', 'ʪ', 'ʫ', 'ᴀ', 'ᴁ', 'ᴃ', '', 'ᴅ', 'ᴆ', 'ᴇ', 'ᴊ', 'ᴋ', 'ᴌ', 'ᴍ', '', 'ᴘ', 'ᴛ', '', '', '', '', 'ᵫ', 'ᵬ', 'ᵭ', 'ᵮ', 'ᵯ', 'ᵰ', 'ᵱ', 'ᵲ', 'ᵳ', 'ᵴ', 'ᵵ', 'ᵶ', 'ᵺ', 'ᵻ', 'ᵽ', 'ᵾ', 'ᶀ', 'ᶁ', 'ᶂ', '', 'ᶄ', 'ᶅ', 'ᶆ', 'ᶇ', 'ᶈ', 'ᶉ', 'ᶊ', '', 'ᶍ', 'ᶎ', 'ᶏ', 'ᶑ', 'ᶒ', 'ᶓ', 'ᶖ', 'ᶙ', 'ẚ', 'ẜ', '', 'ẞ', 'Ỻ', 'ỻ', 'Ỽ', 'ỽ', 'Ỿ', 'ỿ', '©', '®', '₠', '₢', '₣', '₤', '₧', '₺', '₹', '', '℞', '㎧', '㎮', '㏆', '㏗', '㏞', '㏟', '¼', '½', '¾', '⅓', '⅔', '⅕', '⅖', '⅗', '⅘', '⅙', '⅚', '⅛', '⅜', '⅝', '⅞', '⅟', '', '', '', '', '', '“', '”', '„', '‟', '', '″', '〝', '〞', '«', '»', '', '', '', '', '', '', '—', '―', '︱', '︲', '', '‖', '', '⁅', '⁆', '', '、', '。', '〈', '〉', '《', '》', '', '', '〘', '〙', '〚', '〛', '︑', '︒', '︹', '︺', '︽', '︾', '︿', '﹀', '﹑', '﹝', '﹞', '⦅', '⦆', '。', '、', '×', '÷', '', '', '', '', '∥', '≪', '≫', '⦅', '⦆'];
private const TRANSLIT_TO = ['AE', 'D', 'O', 'TH', 'ss', 'ae', 'd', 'o', 'th', 'D', 'd', 'H', 'h', 'i', 'q', 'L', 'l', 'L', 'l', '\'n', 'N', 'n', 'OE', 'oe', 'T', 't', 'b', 'B', 'B', 'b', 'C', 'c', 'D', 'D', 'D', 'd', 'E', 'F', 'f', 'G', 'hv', 'I', 'I', 'K', 'k', 'l', 'N', 'n', 'OI', 'oi', 'P', 'p', 't', 'T', 't', 'T', 'V', 'Y', 'y', 'Z', 'z', 'DZ', 'Dz', 'dz', 'G', 'g', 'd', 'Z', 'z', 'l', 'n', 't', 'j', 'db', 'qp', 'A', 'C', 'c', 'L', 'T', 's', 'z', 'B', 'U', 'E', 'e', 'J', 'j', 'R', 'r', 'Y', 'y', 'b', 'c', 'd', 'd', 'e', 'j', 'g', 'g', 'G', 'h', 'h', 'i', 'I', 'l', 'l', 'l', 'm', 'n', 'n', 'N', 'OE', 'r', 'r', 'r', 'R', 's', 't', 'u', 'v', 'Y', 'z', 'z', 'B', 'G', 'H', 'j', 'L', 'q', 'dz', 'dz', 'ts', 'ls', 'lz', 'A', 'AE', 'B', 'C', 'D', 'D', 'E', 'J', 'K', 'L', 'M', 'O', 'P', 'T', 'U', 'V', 'W', 'Z', 'ue', 'b', 'd', 'f', 'm', 'n', 'p', 'r', 'r', 's', 't', 'z', 'th', 'I', 'p', 'U', 'b', 'd', 'f', 'g', 'k', 'l', 'm', 'n', 'p', 'r', 's', 'v', 'x', 'z', 'a', 'd', 'e', 'e', 'i', 'u', 'a', 's', 's', 'SS', 'LL', 'll', 'V', 'v', 'Y', 'y', '(C)', '(R)', 'CE', 'Cr', 'Fr.', 'L.', 'Pts', 'TL', 'Rs', 'x', 'Rx', 'm/s', 'rad/s', 'C/kg', 'pH', 'V/m', 'A/m', ' 1/4', ' 1/2', ' 3/4', ' 1/3', ' 2/3', ' 1/5', ' 2/5', ' 3/5', ' 4/5', ' 1/6', ' 5/6', ' 1/8', ' 3/8', ' 5/8', ' 7/8', ' 1/', '0', '\'', '\'', ',', '\'', '"', '"', ',,', '"', '\'', '"', '"', '"', '<<', '>>', '<', '>', '-', '-', '-', '-', '-', '-', '-', '-', '-', '||', '/', '[', ']', '*', ',', '.', '<', '>', '<<', '>>', '[', ']', '[', ']', '[', ']', ',', '.', '[', ']', '<<', '>>', '<', '>', ',', '[', ']', '((', '))', '.', ',', '*', '/', '-', '/', '\\', '|', '||', '<<', '>>', '((', '))'];
private static $transliterators = [];
private static $tableZero;
private static $tableWide;
private static array $transliterators = [];
private static array $tableZero;
private static array $tableWide;
/**
* @return static
*/
public static function fromCodePoints(int ...$codes): self
public static function fromCodePoints(int ...$codes): static
{
$string = '';
@@ -124,10 +117,10 @@ abstract class AbstractUnicodeString extends AbstractString
$s = preg_replace("/([AUO])\u{0308}(?=\p{Ll})/u", '$1e', $s);
$s = str_replace(["a\u{0308}", "o\u{0308}", "u\u{0308}", "A\u{0308}", "O\u{0308}", "U\u{0308}"], ['ae', 'oe', 'ue', 'AE', 'OE', 'UE'], $s);
} elseif (\function_exists('transliterator_transliterate')) {
if (null === $transliterator = self::$transliterators[$rule] ?? self::$transliterators[$rule] = \Transliterator::create($rule)) {
if (null === $transliterator = self::$transliterators[$rule] ??= \Transliterator::create($rule)) {
if ('any-latin/bgn' === $rule) {
$rule = 'any-latin';
$transliterator = self::$transliterators[$rule] ?? self::$transliterators[$rule] = \Transliterator::create($rule);
$transliterator = self::$transliterators[$rule] ??= \Transliterator::create($rule);
}
if (null === $transliterator) {
@@ -159,10 +152,12 @@ abstract class AbstractUnicodeString extends AbstractString
return $str;
}
public function camel(): parent
public function camel(): static
{
$str = clone $this;
$str->string = str_replace(' ', '', preg_replace_callback('/\b.(?![A-Z]{2,})/u', static function ($m) use (&$i) {
$str->string = str_replace(' ', '', preg_replace_callback('/\b.(?![A-Z]{2,})/u', static function ($m) {
static $i = 0;
return 1 === ++$i ? ('İ' === $m[0] ? 'i̇' : mb_strtolower($m[0], 'UTF-8')) : mb_convert_case($m[0], \MB_CASE_TITLE, 'UTF-8');
}, preg_replace('/[^\pL0-9]++/u', ' ', $this->string)));
@@ -189,11 +184,11 @@ abstract class AbstractUnicodeString extends AbstractString
return $codePoints;
}
public function folded(bool $compat = true): parent
public function folded(bool $compat = true): static
{
$str = clone $this;
if (!$compat || \PHP_VERSION_ID < 70300 || !\defined('Normalizer::NFKC_CF')) {
if (!$compat || !\defined('Normalizer::NFKC_CF')) {
$str->string = normalizer_normalize($str->string, $compat ? \Normalizer::NFKC : \Normalizer::NFC);
$str->string = mb_strtolower(str_replace(self::FOLD_FROM, self::FOLD_TO, $this->string), 'UTF-8');
} else {
@@ -203,7 +198,7 @@ abstract class AbstractUnicodeString extends AbstractString
return $str;
}
public function join(array $strings, string $lastGlue = null): parent
public function join(array $strings, ?string $lastGlue = null): static
{
$str = clone $this;
@@ -217,7 +212,7 @@ abstract class AbstractUnicodeString extends AbstractString
return $str;
}
public function lower(): parent
public function lower(): static
{
$str = clone $this;
$str->string = mb_strtolower(str_replace('İ', 'i̇', $str->string), 'UTF-8');
@@ -233,19 +228,11 @@ abstract class AbstractUnicodeString extends AbstractString
$regexp .= 'i';
}
set_error_handler(static function ($t, $m) { throw new InvalidArgumentException($m); });
set_error_handler(static fn ($t, $m) => throw new InvalidArgumentException($m));
try {
if (false === $match($regexp.'u', $this->string, $matches, $flags | \PREG_UNMATCHED_AS_NULL, $offset)) {
$lastError = preg_last_error();
foreach (get_defined_constants(true)['pcre'] as $k => $v) {
if ($lastError === $v && '_ERROR' === substr($k, -6)) {
throw new RuntimeException('Matching failed with '.$k.'.');
}
}
throw new RuntimeException('Matching failed with unknown error code.');
throw new RuntimeException('Matching failed with error: '.preg_last_error_msg());
}
} finally {
restore_error_handler();
@@ -254,10 +241,7 @@ abstract class AbstractUnicodeString extends AbstractString
return $matches;
}
/**
* @return static
*/
public function normalize(int $form = self::NFC): self
public function normalize(int $form = self::NFC): static
{
if (!\in_array($form, [self::NFC, self::NFD, self::NFKC, self::NFKD])) {
throw new InvalidArgumentException('Unsupported normalization form.');
@@ -269,7 +253,7 @@ abstract class AbstractUnicodeString extends AbstractString
return $str;
}
public function padBoth(int $length, string $padStr = ' '): parent
public function padBoth(int $length, string $padStr = ' '): static
{
if ('' === $padStr || !preg_match('//u', $padStr)) {
throw new InvalidArgumentException('Invalid UTF-8 string.');
@@ -281,7 +265,7 @@ abstract class AbstractUnicodeString extends AbstractString
return $this->pad($length, $pad, \STR_PAD_BOTH);
}
public function padEnd(int $length, string $padStr = ' '): parent
public function padEnd(int $length, string $padStr = ' '): static
{
if ('' === $padStr || !preg_match('//u', $padStr)) {
throw new InvalidArgumentException('Invalid UTF-8 string.');
@@ -293,7 +277,7 @@ abstract class AbstractUnicodeString extends AbstractString
return $this->pad($length, $pad, \STR_PAD_RIGHT);
}
public function padStart(int $length, string $padStr = ' '): parent
public function padStart(int $length, string $padStr = ' '): static
{
if ('' === $padStr || !preg_match('//u', $padStr)) {
throw new InvalidArgumentException('Invalid UTF-8 string.');
@@ -305,17 +289,13 @@ abstract class AbstractUnicodeString extends AbstractString
return $this->pad($length, $pad, \STR_PAD_LEFT);
}
public function replaceMatches(string $fromRegexp, $to): parent
public function replaceMatches(string $fromRegexp, string|callable $to): static
{
if ($this->ignoreCase) {
$fromRegexp .= 'i';
}
if (\is_array($to) || $to instanceof \Closure) {
if (!\is_callable($to)) {
throw new \TypeError(sprintf('Argument 2 passed to "%s::replaceMatches()" must be callable, array given.', static::class));
}
$replace = 'preg_replace_callback';
$to = static function (array $m) use ($to): string {
$to = $to($m);
@@ -332,14 +312,14 @@ abstract class AbstractUnicodeString extends AbstractString
$replace = 'preg_replace';
}
set_error_handler(static function ($t, $m) { throw new InvalidArgumentException($m); });
set_error_handler(static fn ($t, $m) => throw new InvalidArgumentException($m));
try {
if (null === $string = $replace($fromRegexp.'u', $to, $this->string)) {
$lastError = preg_last_error();
foreach (get_defined_constants(true)['pcre'] as $k => $v) {
if ($lastError === $v && '_ERROR' === substr($k, -6)) {
if ($lastError === $v && str_ends_with($k, '_ERROR')) {
throw new RuntimeException('Matching failed with '.$k.'.');
}
}
@@ -356,7 +336,7 @@ abstract class AbstractUnicodeString extends AbstractString
return $str;
}
public function reverse(): parent
public function reverse(): static
{
$str = clone $this;
$str->string = implode('', array_reverse(preg_split('/(\X)/u', $str->string, -1, \PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_NO_EMPTY)));
@@ -364,7 +344,7 @@ abstract class AbstractUnicodeString extends AbstractString
return $str;
}
public function snake(): parent
public function snake(): static
{
$str = $this->camel();
$str->string = mb_strtolower(preg_replace(['/(\p{Lu}+)(\p{Lu}\p{Ll})/u', '/([\p{Ll}0-9])(\p{Lu})/u'], '\1_\2', $str->string), 'UTF-8');
@@ -372,20 +352,18 @@ abstract class AbstractUnicodeString extends AbstractString
return $str;
}
public function title(bool $allWords = false): parent
public function title(bool $allWords = false): static
{
$str = clone $this;
$limit = $allWords ? -1 : 1;
$str->string = preg_replace_callback('/\b./u', static function (array $m): string {
return mb_convert_case($m[0], \MB_CASE_TITLE, 'UTF-8');
}, $str->string, $limit);
$str->string = preg_replace_callback('/\b./u', static fn (array $m): string => mb_convert_case($m[0], \MB_CASE_TITLE, 'UTF-8'), $str->string, $limit);
return $str;
}
public function trim(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): parent
public function trim(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): static
{
if (" \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}" !== $chars && !preg_match('//u', $chars)) {
throw new InvalidArgumentException('Invalid UTF-8 chars.');
@@ -398,7 +376,7 @@ abstract class AbstractUnicodeString extends AbstractString
return $str;
}
public function trimEnd(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): parent
public function trimEnd(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): static
{
if (" \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}" !== $chars && !preg_match('//u', $chars)) {
throw new InvalidArgumentException('Invalid UTF-8 chars.');
@@ -411,7 +389,7 @@ abstract class AbstractUnicodeString extends AbstractString
return $str;
}
public function trimPrefix($prefix): parent
public function trimPrefix($prefix): static
{
if (!$this->ignoreCase) {
return parent::trimPrefix($prefix);
@@ -431,7 +409,7 @@ abstract class AbstractUnicodeString extends AbstractString
return $str;
}
public function trimStart(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): parent
public function trimStart(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): static
{
if (" \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}" !== $chars && !preg_match('//u', $chars)) {
throw new InvalidArgumentException('Invalid UTF-8 chars.');
@@ -444,7 +422,7 @@ abstract class AbstractUnicodeString extends AbstractString
return $str;
}
public function trimSuffix($suffix): parent
public function trimSuffix($suffix): static
{
if (!$this->ignoreCase) {
return parent::trimSuffix($suffix);
@@ -464,15 +442,11 @@ abstract class AbstractUnicodeString extends AbstractString
return $str;
}
public function upper(): parent
public function upper(): static
{
$str = clone $this;
$str->string = mb_strtoupper($str->string, 'UTF-8');
if (\PHP_VERSION_ID < 70300) {
$str->string = str_replace(self::UPPER_FROM, self::UPPER_TO, $str->string);
}
return $str;
}
@@ -481,7 +455,7 @@ abstract class AbstractUnicodeString extends AbstractString
$width = 0;
$s = str_replace(["\x00", "\x05", "\x07"], '', $this->string);
if (false !== strpos($s, "\r")) {
if (str_contains($s, "\r")) {
$s = str_replace(["\r\n", "\r"], "\n", $s);
}
@@ -508,10 +482,7 @@ abstract class AbstractUnicodeString extends AbstractString
return $width;
}
/**
* @return static
*/
private function pad(int $len, self $pad, int $type): parent
private function pad(int $len, self $pad, int $type): static
{
$sLen = $this->length();
@@ -575,9 +546,7 @@ abstract class AbstractUnicodeString extends AbstractString
return -1;
}
if (null === self::$tableZero) {
self::$tableZero = require __DIR__.'/Resources/data/wcswidth_table_zero.php';
}
self::$tableZero ??= require __DIR__.'/Resources/data/wcswidth_table_zero.php';
if ($codePoint >= self::$tableZero[0][0] && $codePoint <= self::$tableZero[$ubound = \count(self::$tableZero) - 1][1]) {
$lbound = 0;
@@ -594,9 +563,7 @@ abstract class AbstractUnicodeString extends AbstractString
}
}
if (null === self::$tableWide) {
self::$tableWide = require __DIR__.'/Resources/data/wcswidth_table_wide.php';
}
self::$tableWide ??= require __DIR__.'/Resources/data/wcswidth_table_wide.php';
if ($codePoint >= self::$tableWide[0][0] && $codePoint <= self::$tableWide[$ubound = \count(self::$tableWide) - 1][1]) {
$lbound = 0;

View File

@@ -42,13 +42,13 @@ class ByteString extends AbstractString
* Copyright (c) 2004-2020, Facebook, Inc. (https://www.facebook.com/)
*/
public static function fromRandom(int $length = 16, string $alphabet = null): self
public static function fromRandom(int $length = 16, ?string $alphabet = null): self
{
if ($length <= 0) {
throw new InvalidArgumentException(sprintf('A strictly positive length is expected, "%d" given.', $length));
}
$alphabet = $alphabet ?? self::ALPHABET_ALPHANUMERIC;
$alphabet ??= self::ALPHABET_ALPHANUMERIC;
$alphabetSize = \strlen($alphabet);
$bits = (int) ceil(log($alphabetSize, 2.0));
if ($bits <= 0 || $bits > 56) {
@@ -92,7 +92,7 @@ class ByteString extends AbstractString
return '' === $str ? [] : [\ord($str)];
}
public function append(string ...$suffix): parent
public function append(string ...$suffix): static
{
$str = clone $this;
$str->string .= 1 >= \count($suffix) ? ($suffix[0] ?? '') : implode('', $suffix);
@@ -100,7 +100,7 @@ class ByteString extends AbstractString
return $str;
}
public function camel(): parent
public function camel(): static
{
$str = clone $this;
@@ -132,27 +132,23 @@ class ByteString extends AbstractString
return $chunks;
}
public function endsWith($suffix): bool
public function endsWith(string|iterable|AbstractString $suffix): bool
{
if ($suffix instanceof parent) {
if ($suffix instanceof AbstractString) {
$suffix = $suffix->string;
} elseif (\is_array($suffix) || $suffix instanceof \Traversable) {
} elseif (!\is_string($suffix)) {
return parent::endsWith($suffix);
} else {
$suffix = (string) $suffix;
}
return '' !== $suffix && \strlen($this->string) >= \strlen($suffix) && 0 === substr_compare($this->string, $suffix, -\strlen($suffix), null, $this->ignoreCase);
}
public function equalsTo($string): bool
public function equalsTo(string|iterable|AbstractString $string): bool
{
if ($string instanceof parent) {
if ($string instanceof AbstractString) {
$string = $string->string;
} elseif (\is_array($string) || $string instanceof \Traversable) {
} elseif (!\is_string($string)) {
return parent::equalsTo($string);
} else {
$string = (string) $string;
}
if ('' !== $string && $this->ignoreCase) {
@@ -162,7 +158,7 @@ class ByteString extends AbstractString
return $string === $this->string;
}
public function folded(): parent
public function folded(): static
{
$str = clone $this;
$str->string = strtolower($str->string);
@@ -170,14 +166,12 @@ class ByteString extends AbstractString
return $str;
}
public function indexOf($needle, int $offset = 0): ?int
public function indexOf(string|iterable|AbstractString $needle, int $offset = 0): ?int
{
if ($needle instanceof parent) {
if ($needle instanceof AbstractString) {
$needle = $needle->string;
} elseif (\is_array($needle) || $needle instanceof \Traversable) {
} elseif (!\is_string($needle)) {
return parent::indexOf($needle, $offset);
} else {
$needle = (string) $needle;
}
if ('' === $needle) {
@@ -189,14 +183,12 @@ class ByteString extends AbstractString
return false === $i ? null : $i;
}
public function indexOfLast($needle, int $offset = 0): ?int
public function indexOfLast(string|iterable|AbstractString $needle, int $offset = 0): ?int
{
if ($needle instanceof parent) {
if ($needle instanceof AbstractString) {
$needle = $needle->string;
} elseif (\is_array($needle) || $needle instanceof \Traversable) {
} elseif (!\is_string($needle)) {
return parent::indexOfLast($needle, $offset);
} else {
$needle = (string) $needle;
}
if ('' === $needle) {
@@ -213,7 +205,7 @@ class ByteString extends AbstractString
return '' === $this->string || preg_match('//u', $this->string);
}
public function join(array $strings, string $lastGlue = null): parent
public function join(array $strings, ?string $lastGlue = null): static
{
$str = clone $this;
@@ -228,7 +220,7 @@ class ByteString extends AbstractString
return \strlen($this->string);
}
public function lower(): parent
public function lower(): static
{
$str = clone $this;
$str->string = strtolower($str->string);
@@ -244,19 +236,11 @@ class ByteString extends AbstractString
$regexp .= 'i';
}
set_error_handler(static function ($t, $m) { throw new InvalidArgumentException($m); });
set_error_handler(static fn ($t, $m) => throw new InvalidArgumentException($m));
try {
if (false === $match($regexp, $this->string, $matches, $flags | \PREG_UNMATCHED_AS_NULL, $offset)) {
$lastError = preg_last_error();
foreach (get_defined_constants(true)['pcre'] as $k => $v) {
if ($lastError === $v && '_ERROR' === substr($k, -6)) {
throw new RuntimeException('Matching failed with '.$k.'.');
}
}
throw new RuntimeException('Matching failed with unknown error code.');
throw new RuntimeException('Matching failed with error: '.preg_last_error_msg());
}
} finally {
restore_error_handler();
@@ -265,7 +249,7 @@ class ByteString extends AbstractString
return $matches;
}
public function padBoth(int $length, string $padStr = ' '): parent
public function padBoth(int $length, string $padStr = ' '): static
{
$str = clone $this;
$str->string = str_pad($this->string, $length, $padStr, \STR_PAD_BOTH);
@@ -273,7 +257,7 @@ class ByteString extends AbstractString
return $str;
}
public function padEnd(int $length, string $padStr = ' '): parent
public function padEnd(int $length, string $padStr = ' '): static
{
$str = clone $this;
$str->string = str_pad($this->string, $length, $padStr, \STR_PAD_RIGHT);
@@ -281,7 +265,7 @@ class ByteString extends AbstractString
return $str;
}
public function padStart(int $length, string $padStr = ' '): parent
public function padStart(int $length, string $padStr = ' '): static
{
$str = clone $this;
$str->string = str_pad($this->string, $length, $padStr, \STR_PAD_LEFT);
@@ -289,7 +273,7 @@ class ByteString extends AbstractString
return $str;
}
public function prepend(string ...$prefix): parent
public function prepend(string ...$prefix): static
{
$str = clone $this;
$str->string = (1 >= \count($prefix) ? ($prefix[0] ?? '') : implode('', $prefix)).$str->string;
@@ -297,7 +281,7 @@ class ByteString extends AbstractString
return $str;
}
public function replace(string $from, string $to): parent
public function replace(string $from, string $to): static
{
$str = clone $this;
@@ -308,30 +292,22 @@ class ByteString extends AbstractString
return $str;
}
public function replaceMatches(string $fromRegexp, $to): parent
public function replaceMatches(string $fromRegexp, string|callable $to): static
{
if ($this->ignoreCase) {
$fromRegexp .= 'i';
}
if (\is_array($to)) {
if (!\is_callable($to)) {
throw new \TypeError(sprintf('Argument 2 passed to "%s::replaceMatches()" must be callable, array given.', static::class));
}
$replace = \is_array($to) || $to instanceof \Closure ? 'preg_replace_callback' : 'preg_replace';
$replace = 'preg_replace_callback';
} else {
$replace = $to instanceof \Closure ? 'preg_replace_callback' : 'preg_replace';
}
set_error_handler(static function ($t, $m) { throw new InvalidArgumentException($m); });
set_error_handler(static fn ($t, $m) => throw new InvalidArgumentException($m));
try {
if (null === $string = $replace($fromRegexp, $to, $this->string)) {
$lastError = preg_last_error();
foreach (get_defined_constants(true)['pcre'] as $k => $v) {
if ($lastError === $v && '_ERROR' === substr($k, -6)) {
if ($lastError === $v && str_ends_with($k, '_ERROR')) {
throw new RuntimeException('Matching failed with '.$k.'.');
}
}
@@ -348,7 +324,7 @@ class ByteString extends AbstractString
return $str;
}
public function reverse(): parent
public function reverse(): static
{
$str = clone $this;
$str->string = strrev($str->string);
@@ -356,7 +332,7 @@ class ByteString extends AbstractString
return $str;
}
public function slice(int $start = 0, int $length = null): parent
public function slice(int $start = 0, ?int $length = null): static
{
$str = clone $this;
$str->string = (string) substr($this->string, $start, $length ?? \PHP_INT_MAX);
@@ -364,7 +340,7 @@ class ByteString extends AbstractString
return $str;
}
public function snake(): parent
public function snake(): static
{
$str = $this->camel();
$str->string = strtolower(preg_replace(['/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'], '\1_\2', $str->string));
@@ -372,7 +348,7 @@ class ByteString extends AbstractString
return $str;
}
public function splice(string $replacement, int $start = 0, int $length = null): parent
public function splice(string $replacement, int $start = 0, ?int $length = null): static
{
$str = clone $this;
$str->string = substr_replace($this->string, $replacement, $start, $length ?? \PHP_INT_MAX);
@@ -380,9 +356,9 @@ class ByteString extends AbstractString
return $str;
}
public function split(string $delimiter, int $limit = null, int $flags = null): array
public function split(string $delimiter, ?int $limit = null, ?int $flags = null): array
{
if (1 > $limit = $limit ?? \PHP_INT_MAX) {
if (1 > $limit ??= \PHP_INT_MAX) {
throw new InvalidArgumentException('Split limit must be a positive integer.');
}
@@ -407,9 +383,9 @@ class ByteString extends AbstractString
return $chunks;
}
public function startsWith($prefix): bool
public function startsWith(string|iterable|AbstractString $prefix): bool
{
if ($prefix instanceof parent) {
if ($prefix instanceof AbstractString) {
$prefix = $prefix->string;
} elseif (!\is_string($prefix)) {
return parent::startsWith($prefix);
@@ -418,7 +394,7 @@ class ByteString extends AbstractString
return '' !== $prefix && 0 === ($this->ignoreCase ? strncasecmp($this->string, $prefix, \strlen($prefix)) : strncmp($this->string, $prefix, \strlen($prefix)));
}
public function title(bool $allWords = false): parent
public function title(bool $allWords = false): static
{
$str = clone $this;
$str->string = $allWords ? ucwords($str->string) : ucfirst($str->string);
@@ -426,12 +402,12 @@ class ByteString extends AbstractString
return $str;
}
public function toUnicodeString(string $fromEncoding = null): UnicodeString
public function toUnicodeString(?string $fromEncoding = null): UnicodeString
{
return new UnicodeString($this->toCodePointString($fromEncoding)->string);
}
public function toCodePointString(string $fromEncoding = null): CodePointString
public function toCodePointString(?string $fromEncoding = null): CodePointString
{
$u = new CodePointString();
@@ -441,7 +417,7 @@ class ByteString extends AbstractString
return $u;
}
set_error_handler(static function ($t, $m) { throw new InvalidArgumentException($m); });
set_error_handler(static fn ($t, $m) => throw new InvalidArgumentException($m));
try {
try {
@@ -468,7 +444,7 @@ class ByteString extends AbstractString
return $u;
}
public function trim(string $chars = " \t\n\r\0\x0B\x0C"): parent
public function trim(string $chars = " \t\n\r\0\x0B\x0C"): static
{
$str = clone $this;
$str->string = trim($str->string, $chars);
@@ -476,7 +452,7 @@ class ByteString extends AbstractString
return $str;
}
public function trimEnd(string $chars = " \t\n\r\0\x0B\x0C"): parent
public function trimEnd(string $chars = " \t\n\r\0\x0B\x0C"): static
{
$str = clone $this;
$str->string = rtrim($str->string, $chars);
@@ -484,7 +460,7 @@ class ByteString extends AbstractString
return $str;
}
public function trimStart(string $chars = " \t\n\r\0\x0B\x0C"): parent
public function trimStart(string $chars = " \t\n\r\0\x0B\x0C"): static
{
$str = clone $this;
$str->string = ltrim($str->string, $chars);
@@ -492,7 +468,7 @@ class ByteString extends AbstractString
return $str;
}
public function upper(): parent
public function upper(): static
{
$str = clone $this;
$str->string = strtoupper($str->string);

View File

@@ -1,6 +1,11 @@
CHANGELOG
=========
6.2
---
* Add support for emoji in `AsciiSlugger`
5.4
---

View File

@@ -33,7 +33,7 @@ class CodePointString extends AbstractUnicodeString
$this->string = $string;
}
public function append(string ...$suffix): AbstractString
public function append(string ...$suffix): static
{
$str = clone $this;
$str->string .= 1 >= \count($suffix) ? ($suffix[0] ?? '') : implode('', $suffix);
@@ -80,14 +80,12 @@ class CodePointString extends AbstractUnicodeString
return '' === $str->string ? [] : [mb_ord($str->string, 'UTF-8')];
}
public function endsWith($suffix): bool
public function endsWith(string|iterable|AbstractString $suffix): bool
{
if ($suffix instanceof AbstractString) {
$suffix = $suffix->string;
} elseif (\is_array($suffix) || $suffix instanceof \Traversable) {
} elseif (!\is_string($suffix)) {
return parent::endsWith($suffix);
} else {
$suffix = (string) $suffix;
}
if ('' === $suffix || !preg_match('//u', $suffix)) {
@@ -101,14 +99,12 @@ class CodePointString extends AbstractUnicodeString
return \strlen($this->string) >= \strlen($suffix) && 0 === substr_compare($this->string, $suffix, -\strlen($suffix));
}
public function equalsTo($string): bool
public function equalsTo(string|iterable|AbstractString $string): bool
{
if ($string instanceof AbstractString) {
$string = $string->string;
} elseif (\is_array($string) || $string instanceof \Traversable) {
} elseif (!\is_string($string)) {
return parent::equalsTo($string);
} else {
$string = (string) $string;
}
if ('' !== $string && $this->ignoreCase) {
@@ -118,14 +114,12 @@ class CodePointString extends AbstractUnicodeString
return $string === $this->string;
}
public function indexOf($needle, int $offset = 0): ?int
public function indexOf(string|iterable|AbstractString $needle, int $offset = 0): ?int
{
if ($needle instanceof AbstractString) {
$needle = $needle->string;
} elseif (\is_array($needle) || $needle instanceof \Traversable) {
} elseif (!\is_string($needle)) {
return parent::indexOf($needle, $offset);
} else {
$needle = (string) $needle;
}
if ('' === $needle) {
@@ -137,14 +131,12 @@ class CodePointString extends AbstractUnicodeString
return false === $i ? null : $i;
}
public function indexOfLast($needle, int $offset = 0): ?int
public function indexOfLast(string|iterable|AbstractString $needle, int $offset = 0): ?int
{
if ($needle instanceof AbstractString) {
$needle = $needle->string;
} elseif (\is_array($needle) || $needle instanceof \Traversable) {
} elseif (!\is_string($needle)) {
return parent::indexOfLast($needle, $offset);
} else {
$needle = (string) $needle;
}
if ('' === $needle) {
@@ -161,7 +153,7 @@ class CodePointString extends AbstractUnicodeString
return mb_strlen($this->string, 'UTF-8');
}
public function prepend(string ...$prefix): AbstractString
public function prepend(string ...$prefix): static
{
$str = clone $this;
$str->string = (1 >= \count($prefix) ? ($prefix[0] ?? '') : implode('', $prefix)).$this->string;
@@ -173,7 +165,7 @@ class CodePointString extends AbstractUnicodeString
return $str;
}
public function replace(string $from, string $to): AbstractString
public function replace(string $from, string $to): static
{
$str = clone $this;
@@ -194,7 +186,7 @@ class CodePointString extends AbstractUnicodeString
return $str;
}
public function slice(int $start = 0, int $length = null): AbstractString
public function slice(int $start = 0, ?int $length = null): static
{
$str = clone $this;
$str->string = mb_substr($this->string, $start, $length, 'UTF-8');
@@ -202,7 +194,7 @@ class CodePointString extends AbstractUnicodeString
return $str;
}
public function splice(string $replacement, int $start = 0, int $length = null): AbstractString
public function splice(string $replacement, int $start = 0, ?int $length = null): static
{
if (!preg_match('//u', $replacement)) {
throw new InvalidArgumentException('Invalid UTF-8 string.');
@@ -216,9 +208,9 @@ class CodePointString extends AbstractUnicodeString
return $str;
}
public function split(string $delimiter, int $limit = null, int $flags = null): array
public function split(string $delimiter, ?int $limit = null, ?int $flags = null): array
{
if (1 > $limit = $limit ?? \PHP_INT_MAX) {
if (1 > $limit ??= \PHP_INT_MAX) {
throw new InvalidArgumentException('Split limit must be a positive integer.');
}
@@ -247,14 +239,12 @@ class CodePointString extends AbstractUnicodeString
return $chunks;
}
public function startsWith($prefix): bool
public function startsWith(string|iterable|AbstractString $prefix): bool
{
if ($prefix instanceof AbstractString) {
$prefix = $prefix->string;
} elseif (\is_array($prefix) || $prefix instanceof \Traversable) {
} elseif (!\is_string($prefix)) {
return parent::startsWith($prefix);
} else {
$prefix = (string) $prefix;
}
if ('' === $prefix || !preg_match('//u', $prefix)) {

View File

@@ -21,7 +21,7 @@ final class EnglishInflector implements InflectorInterface
private const PLURAL_MAP = [
// First entry: plural suffix, reversed
// Second entry: length of plural suffix
// Third entry: Whether the suffix may succeed a vocal
// Third entry: Whether the suffix may succeed a vowel
// Fourth entry: Whether the suffix may succeed a consonant
// Fifth entry: singular suffix, normal
@@ -55,6 +55,9 @@ final class EnglishInflector implements InflectorInterface
// indices (index), appendices (appendix), prices (price)
['seci', 4, false, true, ['ex', 'ix', 'ice']],
// codes (code)
['sedoc', 5, false, true, 'code'],
// selfies (selfie)
['seifles', 7, true, true, 'selfie'],
@@ -64,6 +67,9 @@ final class EnglishInflector implements InflectorInterface
// movies (movie)
['seivom', 6, true, true, 'movie'],
// names (name)
['seman', 5, true, false, 'name'],
// conspectuses (conspectus), prospectuses (prospectus)
['sesutcep', 8, true, true, 'pectus'],
@@ -88,6 +94,9 @@ final class EnglishInflector implements InflectorInterface
// accesses (access), addresses (address), kisses (kiss)
['sess', 4, true, false, 'ss'],
// statuses (status)
['sesutats', 8, true, true, 'status'],
// analyses (analysis), ellipses (ellipsis), fungi (fungus),
// neuroses (neurosis), theses (thesis), emphases (emphasis),
// oases (oasis), crises (crisis), houses (house), bases (base),
@@ -132,6 +141,9 @@ final class EnglishInflector implements InflectorInterface
// shoes (shoe)
['se', 2, true, true, ['', 'e']],
// status (status)
['sutats', 6, true, true, 'status'],
// tags (tag)
['s', 1, true, true, ''],
@@ -150,10 +162,13 @@ final class EnglishInflector implements InflectorInterface
private const SINGULAR_MAP = [
// First entry: singular suffix, reversed
// Second entry: length of singular suffix
// Third entry: Whether the suffix may succeed a vocal
// Third entry: Whether the suffix may succeed a vowel
// Fourth entry: Whether the suffix may succeed a consonant
// Fifth entry: plural suffix, normal
// axes (axis)
['sixa', 4, false, false, 'axes'],
// criterion (criteria)
['airetirc', 8, false, false, 'criterion'],
@@ -241,6 +256,9 @@ final class EnglishInflector implements InflectorInterface
// seasons (season), treasons (treason), poisons (poison), lessons (lesson)
['nos', 3, true, true, 'sons'],
// icons (icon)
['noc', 3, true, true, 'cons'],
// bacteria (bacterium), criteria (criterion), phenomena (phenomenon)
['no', 2, true, true, 'a'],
@@ -273,6 +291,9 @@ final class EnglishInflector implements InflectorInterface
// circuses (circus)
['suc', 3, true, true, 'cuses'],
// status (status)
['sutats', 6, true, true, ['status', 'statuses']],
// conspectuses (conspectus), prospectuses (prospectus)
['sutcep', 6, true, true, 'pectuses'],
@@ -328,15 +349,30 @@ final class EnglishInflector implements InflectorInterface
// deer
'reed',
// equipment
'tnempiuqe',
// feedback
'kcabdeef',
// fish
'hsif',
// health
'htlaeh',
// history
'yrotsih',
// info
'ofni',
// information
'noitamrofni',
// money
'yenom',
// moose
'esoom',
@@ -348,11 +384,14 @@ final class EnglishInflector implements InflectorInterface
// species
'seiceps',
// traffic
'ciffart',
// aircraft
'tfarcria',
];
/**
* {@inheritdoc}
*/
public function singularize(string $plural): array
{
$pluralRev = strrev($plural);
@@ -384,14 +423,14 @@ final class EnglishInflector implements InflectorInterface
if ($j === $suffixLength) {
// Is there any character preceding the suffix in the plural string?
if ($j < $pluralLength) {
$nextIsVocal = false !== strpos('aeiou', $lowerPluralRev[$j]);
$nextIsVowel = str_contains('aeiou', $lowerPluralRev[$j]);
if (!$map[2] && $nextIsVocal) {
// suffix may not succeed a vocal but next char is one
if (!$map[2] && $nextIsVowel) {
// suffix may not succeed a vowel but next char is one
break;
}
if (!$map[3] && !$nextIsVocal) {
if (!$map[3] && !$nextIsVowel) {
// suffix may not succeed a consonant but next char is one
break;
}
@@ -429,9 +468,6 @@ final class EnglishInflector implements InflectorInterface
return [$plural];
}
/**
* {@inheritdoc}
*/
public function pluralize(string $singular): array
{
$singularRev = strrev($singular);
@@ -464,14 +500,14 @@ final class EnglishInflector implements InflectorInterface
if ($j === $suffixLength) {
// Is there any character preceding the suffix in the plural string?
if ($j < $singularLength) {
$nextIsVocal = false !== strpos('aeiou', $lowerSingularRev[$j]);
$nextIsVowel = str_contains('aeiou', $lowerSingularRev[$j]);
if (!$map[2] && $nextIsVocal) {
// suffix may not succeed a vocal but next char is one
if (!$map[2] && $nextIsVowel) {
// suffix may not succeed a vowel but next char is one
break;
}
if (!$map[3] && !$nextIsVocal) {
if (!$map[3] && !$nextIsVowel) {
// suffix may not succeed a consonant but next char is one
break;
}

View File

@@ -110,9 +110,6 @@ final class FrenchInflector implements InflectorInterface
*/
private const UNINFLECTED = '/^(abcès|accès|abus|albatros|anchois|anglais|autobus|bois|brebis|carquois|cas|chas|colis|concours|corps|cours|cyprès|décès|devis|discours|dos|embarras|engrais|entrelacs|excès|fils|fois|gâchis|gars|glas|héros|intrus|jars|jus|kermès|lacis|legs|lilas|marais|mars|matelas|mépris|mets|mois|mors|obus|os|palais|paradis|parcours|pardessus|pays|plusieurs|poids|pois|pouls|printemps|processus|progrès|puits|pus|rabais|radis|recors|recours|refus|relais|remords|remous|rictus|rhinocéros|repas|rubis|sans|sas|secours|sens|souris|succès|talus|tapis|tas|taudis|temps|tiers|univers|velours|verglas|vernis|virus)$/i';
/**
* {@inheritdoc}
*/
public function singularize(string $plural): array
{
if ($this->isInflectedWord($plural)) {
@@ -130,9 +127,6 @@ final class FrenchInflector implements InflectorInterface
return [$plural];
}
/**
* {@inheritdoc}
*/
public function pluralize(string $singular): array
{
if ($this->isInflectedWord($singular)) {

View File

@@ -1,4 +1,4 @@
Copyright (c) 2019-2022 Fabien Potencier
Copyright (c) 2019-present Fabien Potencier
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

View File

@@ -18,28 +18,28 @@ namespace Symfony\Component\String;
*/
class LazyString implements \Stringable, \JsonSerializable
{
private $value;
private \Closure|string $value;
/**
* @param callable|array $callback A callable or a [Closure, method] lazy-callable
*
* @return static
*/
public static function fromCallable($callback, ...$arguments): self
public static function fromCallable(callable|array $callback, mixed ...$arguments): static
{
if (!\is_callable($callback) && !(\is_array($callback) && isset($callback[0]) && $callback[0] instanceof \Closure && 2 >= \count($callback))) {
throw new \TypeError(sprintf('Argument 1 passed to "%s()" must be a callable or a [Closure, method] lazy-callable, "%s" given.', __METHOD__, get_debug_type($callback)));
if (\is_array($callback) && !\is_callable($callback) && !(($callback[0] ?? null) instanceof \Closure || 2 < \count($callback))) {
throw new \TypeError(sprintf('Argument 1 passed to "%s()" must be a callable or a [Closure, method] lazy-callable, "%s" given.', __METHOD__, '['.implode(', ', array_map('get_debug_type', $callback)).']'));
}
$lazyString = new static();
$lazyString->value = static function () use (&$callback, &$arguments, &$value): string {
$lazyString->value = static function () use (&$callback, &$arguments): string {
static $value;
if (null !== $arguments) {
if (!\is_callable($callback)) {
$callback[0] = $callback[0]();
$callback[1] = $callback[1] ?? '__invoke';
$callback[1] ??= '__invoke';
}
$value = $callback(...$arguments);
$callback = self::getPrettyName($callback);
$callback = !\is_scalar($value) && !$value instanceof \Stringable ? self::getPrettyName($callback) : 'callable';
$arguments = null;
}
@@ -49,19 +49,10 @@ class LazyString implements \Stringable, \JsonSerializable
return $lazyString;
}
/**
* @param string|int|float|bool|\Stringable $value
*
* @return static
*/
public static function fromStringable($value): self
public static function fromStringable(string|int|float|bool|\Stringable $value): static
{
if (!self::isStringable($value)) {
throw new \TypeError(sprintf('Argument 1 passed to "%s()" must be a scalar or a stringable object, "%s" given.', __METHOD__, get_debug_type($value)));
}
if (\is_object($value)) {
return static::fromCallable([$value, '__toString']);
return static::fromCallable($value->__toString(...));
}
$lazyString = new static();
@@ -73,27 +64,22 @@ class LazyString implements \Stringable, \JsonSerializable
/**
* Tells whether the provided value can be cast to string.
*/
final public static function isStringable($value): bool
final public static function isStringable(mixed $value): bool
{
return \is_string($value) || $value instanceof self || (\is_object($value) ? method_exists($value, '__toString') : \is_scalar($value));
return \is_string($value) || $value instanceof \Stringable || \is_scalar($value);
}
/**
* Casts scalars and stringable objects to strings.
*
* @param object|string|int|float|bool $value
*
* @throws \TypeError When the provided value is not stringable
*/
final public static function resolve($value): string
final public static function resolve(\Stringable|string|int|float|bool $value): string
{
return $value;
}
/**
* @return string
*/
public function __toString()
public function __toString(): string
{
if (\is_string($this->value)) {
return $this->value;
@@ -102,7 +88,7 @@ class LazyString implements \Stringable, \JsonSerializable
try {
return $this->value = ($this->value)();
} catch (\Throwable $e) {
if (\TypeError::class === \get_class($e) && __FILE__ === $e->getFile()) {
if (\TypeError::class === $e::class && __FILE__ === $e->getFile()) {
$type = explode(', ', $e->getMessage());
$type = substr(array_pop($type), 0, -\strlen(' returned'));
$r = new \ReflectionFunction($this->value);
@@ -111,11 +97,6 @@ class LazyString implements \Stringable, \JsonSerializable
$e = new \TypeError(sprintf('Return value of %s() passed to %s::fromCallable() must be of the type string, %s returned.', $callback, static::class, $type));
}
if (\PHP_VERSION_ID < 70400) {
// leverage the ErrorHandler component with graceful fallback when it's not available
return trigger_error($e, \E_USER_ERROR);
}
throw $e;
}
}
@@ -148,7 +129,7 @@ class LazyString implements \Stringable, \JsonSerializable
} elseif ($callback instanceof \Closure) {
$r = new \ReflectionFunction($callback);
if (false !== strpos($r->name, '{closure}') || !$class = $r->getClosureScopeClass()) {
if (str_contains($r->name, '{closure}') || !$class = $r->getClosureCalledClass()) {
return $r->name;
}

View File

@@ -3,8 +3,8 @@
/*
* This file has been auto-generated by the Symfony String Component for internal use.
*
* Unicode version: 15.0.0
* Date: 2022-10-05T17:16:36+02:00
* Unicode version: 15.1.0
* Date: 2023-09-13T11:47:12+00:00
*/
return [
@@ -166,7 +166,7 @@ return [
],
[
12272,
12283,
12287,
],
[
12288,
@@ -396,6 +396,10 @@ return [
12736,
12771,
],
[
12783,
12783,
],
[
12784,
12799,
@@ -1110,6 +1114,14 @@ return [
],
[
191457,
191471,
],
[
191472,
192093,
],
[
192094,
194559,
],
[

View File

@@ -3,8 +3,8 @@
/*
* This file has been auto-generated by the Symfony String Component for internal use.
*
* Unicode version: 15.0.0
* Date: 2022-10-05T17:16:37+02:00
* Unicode version: 15.1.0
* Date: 2023-09-13T11:47:13+00:00
*/
return [

View File

@@ -31,7 +31,7 @@ if (!\function_exists(s::class)) {
*/
function s(?string $string = ''): AbstractString
{
$string = $string ?? '';
$string ??= '';
return preg_match('//u', $string) ? new UnicodeString($string) : new ByteString($string);
}

View File

@@ -11,6 +11,7 @@
namespace Symfony\Component\String\Slugger;
use Symfony\Component\Intl\Transliterator\EmojiTransliterator;
use Symfony\Component\String\AbstractUnicodeString;
use Symfony\Component\String\UnicodeString;
use Symfony\Contracts\Translation\LocaleAwareInterface;
@@ -54,69 +55,73 @@ class AsciiSlugger implements SluggerInterface, LocaleAwareInterface
'zh' => 'Han-Latin',
];
private $defaultLocale;
private $symbolsMap = [
private ?string $defaultLocale;
private \Closure|array $symbolsMap = [
'en' => ['@' => 'at', '&' => 'and'],
];
private bool|string $emoji = false;
/**
* Cache of transliterators per locale.
*
* @var \Transliterator[]
*/
private $transliterators = [];
private array $transliterators = [];
/**
* @param array|\Closure|null $symbolsMap
*/
public function __construct(string $defaultLocale = null, $symbolsMap = null)
public function __construct(?string $defaultLocale = null, array|\Closure|null $symbolsMap = null)
{
if (null !== $symbolsMap && !\is_array($symbolsMap) && !$symbolsMap instanceof \Closure) {
throw new \TypeError(sprintf('Argument 2 passed to "%s()" must be array, Closure or null, "%s" given.', __METHOD__, \gettype($symbolsMap)));
}
$this->defaultLocale = $defaultLocale;
$this->symbolsMap = $symbolsMap ?? $this->symbolsMap;
}
/**
* {@inheritdoc}
*/
public function setLocale($locale)
public function setLocale(string $locale): void
{
$this->defaultLocale = $locale;
}
/**
* {@inheritdoc}
*/
public function getLocale()
public function getLocale(): string
{
return $this->defaultLocale;
}
/**
* {@inheritdoc}
* @param bool|string $emoji true will use the same locale,
* false will disable emoji,
* and a string to use a specific locale
*/
public function slug(string $string, string $separator = '-', string $locale = null): AbstractUnicodeString
public function withEmoji(bool|string $emoji = true): static
{
$locale = $locale ?? $this->defaultLocale;
if (false !== $emoji && !class_exists(EmojiTransliterator::class)) {
throw new \LogicException(sprintf('You cannot use the "%s()" method as the "symfony/intl" package is not installed. Try running "composer require symfony/intl".', __METHOD__));
}
$new = clone $this;
$new->emoji = $emoji;
return $new;
}
public function slug(string $string, string $separator = '-', ?string $locale = null): AbstractUnicodeString
{
$locale ??= $this->defaultLocale;
$transliterator = [];
if ($locale && ('de' === $locale || 0 === strpos($locale, 'de_'))) {
if ($locale && ('de' === $locale || str_starts_with($locale, 'de_'))) {
// Use the shortcut for German in UnicodeString::ascii() if possible (faster and no requirement on intl)
$transliterator = ['de-ASCII'];
} elseif (\function_exists('transliterator_transliterate') && $locale) {
$transliterator = (array) $this->createTransliterator($locale);
}
if ($emojiTransliterator = $this->createEmojiTransliterator($locale)) {
$transliterator[] = $emojiTransliterator;
}
if ($this->symbolsMap instanceof \Closure) {
// If the symbols map is passed as a closure, there is no need to fallback to the parent locale
// as the closure can just provide substitutions for all locales of interest.
$symbolsMap = $this->symbolsMap;
array_unshift($transliterator, static function ($s) use ($symbolsMap, $locale) {
return $symbolsMap($s, $locale);
});
array_unshift($transliterator, static fn ($s) => $symbolsMap($s, $locale));
}
$unicodeString = (new UnicodeString($string))->ascii($transliterator);
@@ -168,6 +173,25 @@ class AsciiSlugger implements SluggerInterface, LocaleAwareInterface
return $this->transliterators[$locale] = $this->transliterators[$parent] = $transliterator ?? null;
}
private function createEmojiTransliterator(?string $locale): ?EmojiTransliterator
{
if (\is_string($this->emoji)) {
$locale = $this->emoji;
} elseif (!$this->emoji) {
return null;
}
while (null !== $locale) {
try {
return EmojiTransliterator::create("emoji-$locale");
} catch (\IntlException) {
$locale = self::getParentLocale($locale);
}
}
return null;
}
private static function getParentLocale(?string $locale): ?string
{
if (!$locale) {

View File

@@ -23,5 +23,5 @@ interface SluggerInterface
/**
* Creates a slug for the given string and locale, using appropriate transliteration when needed.
*/
public function slug(string $string, string $separator = '-', string $locale = null): AbstractUnicodeString;
public function slug(string $string, string $separator = '-', ?string $locale = null): AbstractUnicodeString;
}

View File

@@ -34,23 +34,32 @@ class UnicodeString extends AbstractUnicodeString
{
public function __construct(string $string = '')
{
$this->string = normalizer_is_normalized($string) ? $string : normalizer_normalize($string);
if ('' === $string || normalizer_is_normalized($this->string = $string)) {
return;
}
if (false === $this->string) {
if (false === $string = normalizer_normalize($string)) {
throw new InvalidArgumentException('Invalid UTF-8 string.');
}
$this->string = $string;
}
public function append(string ...$suffix): AbstractString
public function append(string ...$suffix): static
{
$str = clone $this;
$str->string = $this->string.(1 >= \count($suffix) ? ($suffix[0] ?? '') : implode('', $suffix));
normalizer_is_normalized($str->string) ?: $str->string = normalizer_normalize($str->string);
if (false === $str->string) {
if (normalizer_is_normalized($str->string)) {
return $str;
}
if (false === $string = normalizer_normalize($str->string)) {
throw new InvalidArgumentException('Invalid UTF-8 string.');
}
$str->string = $string;
return $str;
}
@@ -82,14 +91,12 @@ class UnicodeString extends AbstractUnicodeString
return $chunks;
}
public function endsWith($suffix): bool
public function endsWith(string|iterable|AbstractString $suffix): bool
{
if ($suffix instanceof AbstractString) {
$suffix = $suffix->string;
} elseif (\is_array($suffix) || $suffix instanceof \Traversable) {
} elseif (!\is_string($suffix)) {
return parent::endsWith($suffix);
} else {
$suffix = (string) $suffix;
}
$form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC;
@@ -106,14 +113,12 @@ class UnicodeString extends AbstractUnicodeString
return $suffix === grapheme_extract($this->string, \strlen($suffix), \GRAPHEME_EXTR_MAXBYTES, \strlen($this->string) - \strlen($suffix));
}
public function equalsTo($string): bool
public function equalsTo(string|iterable|AbstractString $string): bool
{
if ($string instanceof AbstractString) {
$string = $string->string;
} elseif (\is_array($string) || $string instanceof \Traversable) {
} elseif (!\is_string($string)) {
return parent::equalsTo($string);
} else {
$string = (string) $string;
}
$form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC;
@@ -126,14 +131,12 @@ class UnicodeString extends AbstractUnicodeString
return $string === $this->string;
}
public function indexOf($needle, int $offset = 0): ?int
public function indexOf(string|iterable|AbstractString $needle, int $offset = 0): ?int
{
if ($needle instanceof AbstractString) {
$needle = $needle->string;
} elseif (\is_array($needle) || $needle instanceof \Traversable) {
} elseif (!\is_string($needle)) {
return parent::indexOf($needle, $offset);
} else {
$needle = (string) $needle;
}
$form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC;
@@ -145,21 +148,19 @@ class UnicodeString extends AbstractUnicodeString
try {
$i = $this->ignoreCase ? grapheme_stripos($this->string, $needle, $offset) : grapheme_strpos($this->string, $needle, $offset);
} catch (\ValueError $e) {
} catch (\ValueError) {
return null;
}
return false === $i ? null : $i;
}
public function indexOfLast($needle, int $offset = 0): ?int
public function indexOfLast(string|iterable|AbstractString $needle, int $offset = 0): ?int
{
if ($needle instanceof AbstractString) {
$needle = $needle->string;
} elseif (\is_array($needle) || $needle instanceof \Traversable) {
} elseif (!\is_string($needle)) {
return parent::indexOfLast($needle, $offset);
} else {
$needle = (string) $needle;
}
$form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC;
@@ -184,7 +185,7 @@ class UnicodeString extends AbstractUnicodeString
return false === $i ? null : $i;
}
public function join(array $strings, string $lastGlue = null): AbstractString
public function join(array $strings, ?string $lastGlue = null): static
{
$str = parent::join($strings, $lastGlue);
normalizer_is_normalized($str->string) ?: $str->string = normalizer_normalize($str->string);
@@ -197,10 +198,7 @@ class UnicodeString extends AbstractUnicodeString
return grapheme_strlen($this->string);
}
/**
* @return static
*/
public function normalize(int $form = self::NFC): parent
public function normalize(int $form = self::NFC): static
{
$str = clone $this;
@@ -216,20 +214,25 @@ class UnicodeString extends AbstractUnicodeString
return $str;
}
public function prepend(string ...$prefix): AbstractString
public function prepend(string ...$prefix): static
{
$str = clone $this;
$str->string = (1 >= \count($prefix) ? ($prefix[0] ?? '') : implode('', $prefix)).$this->string;
normalizer_is_normalized($str->string) ?: $str->string = normalizer_normalize($str->string);
if (false === $str->string) {
if (normalizer_is_normalized($str->string)) {
return $str;
}
if (false === $string = normalizer_normalize($str->string)) {
throw new InvalidArgumentException('Invalid UTF-8 string.');
}
$str->string = $string;
return $str;
}
public function replace(string $from, string $to): AbstractString
public function replace(string $from, string $to): static
{
$str = clone $this;
normalizer_is_normalized($from) ?: $from = normalizer_normalize($from);
@@ -246,17 +249,22 @@ class UnicodeString extends AbstractUnicodeString
}
$str->string = $result.$tail;
normalizer_is_normalized($str->string) ?: $str->string = normalizer_normalize($str->string);
if (false === $str->string) {
if (normalizer_is_normalized($str->string)) {
return $str;
}
if (false === $string = normalizer_normalize($str->string)) {
throw new InvalidArgumentException('Invalid UTF-8 string.');
}
$str->string = $string;
}
return $str;
}
public function replaceMatches(string $fromRegexp, $to): AbstractString
public function replaceMatches(string $fromRegexp, string|callable $to): static
{
$str = parent::replaceMatches($fromRegexp, $to);
normalizer_is_normalized($str->string) ?: $str->string = normalizer_normalize($str->string);
@@ -264,40 +272,39 @@ class UnicodeString extends AbstractUnicodeString
return $str;
}
public function slice(int $start = 0, int $length = null): AbstractString
public function slice(int $start = 0, ?int $length = null): static
{
$str = clone $this;
if (\PHP_VERSION_ID < 80000 && 0 > $start && grapheme_strlen($this->string) < -$start) {
$start = 0;
}
$str->string = (string) grapheme_substr($this->string, $start, $length ?? 2147483647);
return $str;
}
public function splice(string $replacement, int $start = 0, int $length = null): AbstractString
public function splice(string $replacement, int $start = 0, ?int $length = null): static
{
$str = clone $this;
if (\PHP_VERSION_ID < 80000 && 0 > $start && grapheme_strlen($this->string) < -$start) {
$start = 0;
}
$start = $start ? \strlen(grapheme_substr($this->string, 0, $start)) : 0;
$length = $length ? \strlen(grapheme_substr($this->string, $start, $length ?? 2147483647)) : $length;
$str->string = substr_replace($this->string, $replacement, $start, $length ?? 2147483647);
normalizer_is_normalized($str->string) ?: $str->string = normalizer_normalize($str->string);
if (false === $str->string) {
if (normalizer_is_normalized($str->string)) {
return $str;
}
if (false === $string = normalizer_normalize($str->string)) {
throw new InvalidArgumentException('Invalid UTF-8 string.');
}
$str->string = $string;
return $str;
}
public function split(string $delimiter, int $limit = null, int $flags = null): array
public function split(string $delimiter, ?int $limit = null, ?int $flags = null): array
{
if (1 > $limit = $limit ?? 2147483647) {
if (1 > $limit ??= 2147483647) {
throw new InvalidArgumentException('Split limit must be a positive integer.');
}
@@ -333,14 +340,12 @@ class UnicodeString extends AbstractUnicodeString
return $chunks;
}
public function startsWith($prefix): bool
public function startsWith(string|iterable|AbstractString $prefix): bool
{
if ($prefix instanceof AbstractString) {
$prefix = $prefix->string;
} elseif (\is_array($prefix) || $prefix instanceof \Traversable) {
} elseif (!\is_string($prefix)) {
return parent::startsWith($prefix);
} else {
$prefix = (string) $prefix;
}
$form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC;
@@ -357,7 +362,7 @@ class UnicodeString extends AbstractUnicodeString
return $prefix === grapheme_extract($this->string, \strlen($prefix), \GRAPHEME_EXTR_MAXBYTES);
}
public function __wakeup()
public function __wakeup(): void
{
if (!\is_string($this->string)) {
throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);

View File

@@ -16,21 +16,21 @@
}
],
"require": {
"php": ">=7.2.5",
"php": ">=8.2",
"symfony/polyfill-ctype": "~1.8",
"symfony/polyfill-intl-grapheme": "~1.0",
"symfony/polyfill-intl-normalizer": "~1.0",
"symfony/polyfill-mbstring": "~1.0",
"symfony/polyfill-php80": "~1.15"
"symfony/polyfill-mbstring": "~1.0"
},
"require-dev": {
"symfony/error-handler": "^4.4|^5.0|^6.0",
"symfony/http-client": "^4.4|^5.0|^6.0",
"symfony/translation-contracts": "^1.1|^2",
"symfony/var-exporter": "^4.4|^5.0|^6.0"
"symfony/error-handler": "^6.4|^7.0",
"symfony/intl": "^6.4|^7.0",
"symfony/http-client": "^6.4|^7.0",
"symfony/translation-contracts": "^2.5|^3.0",
"symfony/var-exporter": "^6.4|^7.0"
},
"conflict": {
"symfony/translation-contracts": ">=3.0"
"symfony/translation-contracts": "<2.5"
},
"autoload": {
"psr-4": { "Symfony\\Component\\String\\": "" },