cleaned up composer

This commit is contained in:
2026-02-18 20:17:19 -06:00
parent 3c94239da7
commit 3e153679bd
5952 changed files with 271417 additions and 203117 deletions
+140 -165
View File
@@ -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,23 +234,17 @@ 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('/(?:\s{2,}+|[^\S ])/', ' ', $str->string));
$str->string = trim(preg_replace("/(?:[ \n\r\t\x0C]{2,}+|[\n\r\t\x0C])/", ' ', $str->string), " \n\r\t\x0C");
return $str;
}
@@ -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,10 +260,10 @@ 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) {
throw new \TypeError(sprintf('Method "%s()" must be overridden by class "%s" to deal with non-iterable values.', __FUNCTION__, static::class));
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));
}
foreach ($suffix as $s) {
@@ -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,10 +309,10 @@ 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) {
throw new \TypeError(sprintf('Method "%s()" must be overridden by class "%s" to deal with non-iterable values.', __FUNCTION__, static::class));
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));
}
foreach ($string as $s) {
@@ -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,10 +337,10 @@ 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) {
throw new \TypeError(sprintf('Method "%s()" must be overridden by class "%s" to deal with non-iterable values.', __FUNCTION__, static::class));
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));
}
$i = \PHP_INT_MAX;
@@ -372,10 +359,10 @@ 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) {
throw new \TypeError(sprintf('Method "%s()" must be overridden by class "%s" to deal with non-iterable values.', __FUNCTION__, static::class));
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));
}
$i = null;
@@ -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,33 +403,18 @@ 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));
throw new InvalidArgumentException(\sprintf('Multiplier must be positive, %d given.', $multiplier));
}
$str = clone $this;
@@ -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,10 +478,10 @@ 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) {
throw new \TypeError(sprintf('Method "%s()" must be overridden by class "%s" to deal with non-iterable values.', __FUNCTION__, static::class));
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));
}
foreach ($prefix as $prefix) {
@@ -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,25 +535,77 @@ 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;
abstract public function trimEnd(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): static;
/**
* @return static
* @param string|string[] $prefix
*/
abstract public function trimEnd(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): self;
public function trimPrefix($prefix): static
{
if (\is_array($prefix) || $prefix instanceof \Traversable) { // don't use is_iterable(), it's slow
foreach ($prefix as $s) {
$t = $this->trimPrefix($s);
if ($t->string !== $this->string) {
return $t;
}
}
return clone $this;
}
$str = clone $this;
if ($prefix instanceof self) {
$prefix = $prefix->string;
} else {
$prefix = (string) $prefix;
}
if ('' !== $prefix && \strlen($this->string) >= \strlen($prefix) && 0 === substr_compare($this->string, $prefix, 0, \strlen($prefix), $this->ignoreCase)) {
$str->string = substr($this->string, \strlen($prefix));
}
return $str;
}
abstract public function trimStart(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): static;
/**
* @return static
* @param string|string[] $suffix
*/
abstract public function trimStart(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): self;
public function trimSuffix($suffix): static
{
if (\is_array($suffix) || $suffix instanceof \Traversable) { // don't use is_iterable(), it's slow
foreach ($suffix as $s) {
$t = $this->trimSuffix($s);
/**
* @return static
*/
public function truncate(int $length, string $ellipsis = '', bool $cut = true): self
if ($t->string !== $this->string) {
return $t;
}
}
return clone $this;
}
$str = clone $this;
if ($suffix instanceof self) {
$suffix = $suffix->string;
} else {
$suffix = (string) $suffix;
}
if ('' !== $suffix && \strlen($this->string) >= \strlen($suffix) && 0 === substr_compare($this->string, $suffix, -\strlen($suffix), null, $this->ignoreCase)) {
$str->string = substr($this->string, 0, -\strlen($suffix));
}
return $str;
}
public function truncate(int $length, string $ellipsis = '', bool $cut = true): static
{
$stringLength = $this->length();
@@ -651,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 = [];
+109 -93
View File
@@ -37,23 +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 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 = '';
@@ -122,14 +117,14 @@ 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) {
throw new InvalidArgumentException(sprintf('Unknown transliteration rule "%s".', $rule));
throw new InvalidArgumentException(\sprintf('Unknown transliteration rule "%s".', $rule));
}
self::$transliterators['any-latin/bgn'] = $transliterator;
@@ -140,15 +135,21 @@ abstract class AbstractUnicodeString extends AbstractString
} elseif (!\function_exists('iconv')) {
$s = preg_replace('/[^\x00-\x7F]/u', '?', $s);
} else {
$s = @preg_replace_callback('/[^\x00-\x7F]/u', static function ($c) {
$c = (string) iconv('UTF-8', 'ASCII//TRANSLIT', $c[0]);
$previousLocale = setlocale(\LC_CTYPE, 0);
try {
setlocale(\LC_CTYPE, 'C');
$s = @preg_replace_callback('/[^\x00-\x7F]/u', static function ($c) {
$c = (string) iconv('UTF-8', 'ASCII//TRANSLIT', $c[0]);
if ('' === $c && '' === iconv('UTF-8', 'ASCII//TRANSLIT', '²')) {
throw new \LogicException(sprintf('"%s" requires a translit-able iconv implementation, try installing "gnu-libiconv" if you\'re using Alpine Linux.', static::class));
}
if ('' === $c && '' === iconv('UTF-8', 'ASCII//TRANSLIT', '²')) {
throw new \LogicException(\sprintf('"%s" requires a translit-able iconv implementation, try installing "gnu-libiconv" if you\'re using Alpine Linux.', static::class));
}
return 1 < \strlen($c) ? ltrim($c, '\'`"^~') : ('' !== $c ? $c : '?');
}, $s);
return 1 < \strlen($c) ? ltrim($c, '\'`"^~') : ('' !== $c ? $c : '?');
}, $s);
} finally {
setlocale(\LC_CTYPE, $previousLocale);
}
}
}
@@ -157,10 +158,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./u', static function ($m) use (&$i) {
$str->string = str_replace(' ', '', preg_replace_callback('/\b.(?!\p{Lu})/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)));
@@ -187,13 +190,13 @@ 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');
$str->string = mb_strtolower(str_replace(self::FOLD_FROM, self::FOLD_TO, $str->string), 'UTF-8');
} else {
$str->string = normalizer_normalize($str->string, \Normalizer::NFKC_CF);
}
@@ -201,7 +204,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;
@@ -215,7 +218,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');
@@ -231,19 +234,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();
@@ -252,10 +247,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.');
@@ -267,7 +259,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.');
@@ -279,7 +271,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.');
@@ -291,7 +283,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.');
@@ -303,17 +295,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);
@@ -330,14 +318,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.'.');
}
}
@@ -354,7 +342,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)));
@@ -362,28 +350,26 @@ abstract class AbstractUnicodeString extends AbstractString
return $str;
}
public function snake(): parent
public function snake(): static
{
$str = $this->camel()->title();
$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');
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.');
@@ -396,7 +382,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.');
@@ -409,7 +395,27 @@ 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 trimPrefix($prefix): static
{
if (!$this->ignoreCase) {
return parent::trimPrefix($prefix);
}
$str = clone $this;
if ($prefix instanceof \Traversable) {
$prefix = iterator_to_array($prefix, false);
} elseif ($prefix instanceof parent) {
$prefix = $prefix->string;
}
$prefix = implode('|', array_map('preg_quote', (array) $prefix));
$str->string = preg_replace("{^(?:$prefix)}iuD", '', $this->string);
return $str;
}
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.');
@@ -422,15 +428,31 @@ abstract class AbstractUnicodeString extends AbstractString
return $str;
}
public function upper(): parent
public function trimSuffix($suffix): static
{
if (!$this->ignoreCase) {
return parent::trimSuffix($suffix);
}
$str = clone $this;
if ($suffix instanceof \Traversable) {
$suffix = iterator_to_array($suffix, false);
} elseif ($suffix instanceof parent) {
$suffix = $suffix->string;
}
$suffix = implode('|', array_map('preg_quote', (array) $suffix));
$str->string = preg_replace("{(?:$suffix)$}iuD", '', $this->string);
return $str;
}
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;
}
@@ -439,7 +461,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);
}
@@ -450,23 +472,23 @@ abstract class AbstractUnicodeString extends AbstractString
foreach (explode("\n", $s) as $s) {
if ($ignoreAnsiDecoration) {
$s = preg_replace('/(?:\x1B(?:
\[ [\x30-\x3F]*+ [\x20-\x2F]*+ [0x40-\x7E]
\[ [\x30-\x3F]*+ [\x20-\x2F]*+ [\x40-\x7E]
| [P\]X^_] .*? \x1B\\\\
| [\x41-\x7E]
)|[\p{Cc}\x7F]++)/xu', '', $s);
}
// Non printable characters have been dropped, so wcswidth cannot logically return -1.
$width += $this->wcswidth($s);
$lineWidth = $this->wcswidth($s);
if ($lineWidth > $width) {
$width = $lineWidth;
}
}
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();
@@ -480,22 +502,22 @@ abstract class AbstractUnicodeString extends AbstractString
switch ($type) {
case \STR_PAD_RIGHT:
return $this->append(str_repeat($pad->string, $freeLen / $padLen).($len ? $pad->slice(0, $len) : ''));
return $this->append(str_repeat($pad->string, intdiv($freeLen, $padLen)).($len ? $pad->slice(0, $len) : ''));
case \STR_PAD_LEFT:
return $this->prepend(str_repeat($pad->string, $freeLen / $padLen).($len ? $pad->slice(0, $len) : ''));
return $this->prepend(str_repeat($pad->string, intdiv($freeLen, $padLen)).($len ? $pad->slice(0, $len) : ''));
case \STR_PAD_BOTH:
$freeLen /= 2;
$rightLen = ceil($freeLen);
$len = $rightLen % $padLen;
$str = $this->append(str_repeat($pad->string, $rightLen / $padLen).($len ? $pad->slice(0, $len) : ''));
$str = $this->append(str_repeat($pad->string, intdiv($rightLen, $padLen)).($len ? $pad->slice(0, $len) : ''));
$leftLen = floor($freeLen);
$len = $leftLen % $padLen;
return $str->prepend(str_repeat($pad->string, $leftLen / $padLen).($len ? $pad->slice(0, $len) : ''));
return $str->prepend(str_repeat($pad->string, intdiv($leftLen, $padLen)).($len ? $pad->slice(0, $len) : ''));
default:
throw new InvalidArgumentException('Invalid padding type.');
@@ -530,19 +552,16 @@ abstract class AbstractUnicodeString extends AbstractString
return -1;
}
static $tableZero;
if (null === $tableZero) {
$tableZero = require __DIR__.'/Resources/data/wcswidth_table_zero.php';
}
self::$tableZero ??= require __DIR__.'/Resources/data/wcswidth_table_zero.php';
if ($codePoint >= $tableZero[0][0] && $codePoint <= $tableZero[$ubound = \count($tableZero) - 1][1]) {
if ($codePoint >= self::$tableZero[0][0] && $codePoint <= self::$tableZero[$ubound = \count(self::$tableZero) - 1][1]) {
$lbound = 0;
while ($ubound >= $lbound) {
$mid = floor(($lbound + $ubound) / 2);
if ($codePoint > $tableZero[$mid][1]) {
if ($codePoint > self::$tableZero[$mid][1]) {
$lbound = $mid + 1;
} elseif ($codePoint < $tableZero[$mid][0]) {
} elseif ($codePoint < self::$tableZero[$mid][0]) {
$ubound = $mid - 1;
} else {
continue 2;
@@ -550,19 +569,16 @@ abstract class AbstractUnicodeString extends AbstractString
}
}
static $tableWide;
if (null === $tableWide) {
$tableWide = require __DIR__.'/Resources/data/wcswidth_table_wide.php';
}
self::$tableWide ??= require __DIR__.'/Resources/data/wcswidth_table_wide.php';
if ($codePoint >= $tableWide[0][0] && $codePoint <= $tableWide[$ubound = \count($tableWide) - 1][1]) {
if ($codePoint >= self::$tableWide[0][0] && $codePoint <= self::$tableWide[$ubound = \count(self::$tableWide) - 1][1]) {
$lbound = 0;
while ($ubound >= $lbound) {
$mid = floor(($lbound + $ubound) / 2);
if ($codePoint > $tableWide[$mid][1]) {
if ($codePoint > self::$tableWide[$mid][1]) {
$lbound = $mid + 1;
} elseif ($codePoint < $tableWide[$mid][0]) {
} elseif ($codePoint < self::$tableWide[$mid][0]) {
$ubound = $mid - 1;
} else {
$width += 2;
+53 -74
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));
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,10 +100,13 @@ class ByteString extends AbstractString
return $str;
}
public function camel(): parent
public function camel(): static
{
$str = clone $this;
$str->string = lcfirst(str_replace(' ', '', ucwords(preg_replace('/[^a-zA-Z0-9\x7f-\xff]++/', ' ', $this->string))));
$parts = explode(' ', trim(ucwords(preg_replace('/[^a-zA-Z0-9\x7f-\xff]++/', ' ', $this->string))));
$parts[0] = 1 !== \strlen($parts[0]) && ctype_upper($parts[0]) ? $parts[0] : lcfirst($parts[0]);
$str->string = implode('', $parts);
return $str;
}
@@ -129,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) {
@@ -159,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);
@@ -167,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) {
@@ -186,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) {
@@ -210,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;
@@ -225,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);
@@ -241,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();
@@ -262,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);
@@ -270,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);
@@ -278,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);
@@ -286,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;
@@ -294,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;
@@ -305,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.'.');
}
}
@@ -345,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);
@@ -353,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);
@@ -361,15 +340,15 @@ class ByteString extends AbstractString
return $str;
}
public function snake(): parent
public function snake(): static
{
$str = $this->camel()->title();
$str = $this->camel();
$str->string = strtolower(preg_replace(['/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'], '\1_\2', $str->string));
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);
@@ -377,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.');
}
@@ -404,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);
@@ -415,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);
@@ -423,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();
@@ -438,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 {
@@ -457,7 +436,7 @@ class ByteString extends AbstractString
}
if (!$validEncoding) {
throw new InvalidArgumentException(sprintf('Invalid "%s" string.', $fromEncoding ?? 'Windows-1252'));
throw new InvalidArgumentException(\sprintf('Invalid "%s" string.', $fromEncoding ?? 'Windows-1252'));
}
$u->string = mb_convert_encoding($this->string, 'UTF-8', $fromEncoding ?? 'Windows-1252');
@@ -465,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);
@@ -473,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);
@@ -481,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);
@@ -489,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);
+15
View File
@@ -1,6 +1,21 @@
CHANGELOG
=========
6.2
---
* Add support for emoji in `AsciiSlugger`
5.4
---
* Add `trimSuffix()` and `trimPrefix()` methods
5.3
---
* Made `AsciiSlugger` fallback to parent locale's symbolsMap
5.2.0
-----
+17 -27
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)) {
+140 -34
View File
@@ -21,12 +21,52 @@ 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
// bacteria (bacterium), criteria (criterion), phenomena (phenomenon)
['a', 1, true, true, ['on', 'um']],
// insignias (insigne), insignia (insigne)
['saingisni', 9, true, true, 'insigne'],
['aingisni', 8, true, true, 'insigne'],
// passersby (passerby)
['ybsressap', 9, true, true, 'passerby'],
// nodes (node)
['sedon', 5, true, true, 'node'],
// bacteria (bacterium)
['airetcab', 8, true, true, 'bacterium'],
// issues (issue)
['seussi', 6, true, true, 'issue'],
// corpora (corpus)
['aroproc', 7, true, true, 'corpus'],
// criteria (criterion)
['airetirc', 8, true, true, 'criterion'],
// curricula (curriculum)
['alucirruc', 9, true, true, 'curriculum'],
// quora (quorum)
['arouq', 5, true, true, 'quorum'],
// genera (genus)
['areneg', 6, true, true, 'genus'],
// media (medium)
['aidem', 5, true, true, 'medium'],
// memoranda (memorandum)
['adnaromem', 9, true, true, 'memorandum'],
// phenomena (phenomenon)
['anemonehp', 9, true, true, 'phenomenon'],
// strata (stratum)
['atarts', 6, true, true, 'stratum'],
// nebulae (nebula)
['ea', 2, true, true, 'a'],
@@ -55,12 +95,21 @@ 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'],
// zombies (zombie)
['seibmoz', 7, true, true, 'zombie'],
// movies (movie)
['seivom', 6, true, true, 'movie'],
// names (name)
['seman', 5, true, false, 'name'],
// conspectuses (conspectus), prospectuses (prospectus)
['sesutcep', 8, true, true, 'pectus'],
@@ -85,6 +134,12 @@ final class EnglishInflector implements InflectorInterface
// accesses (access), addresses (address), kisses (kiss)
['sess', 4, true, false, 'ss'],
// statuses (status)
['sesutats', 8, true, true, 'status'],
// article (articles), ancle (ancles)
['sel', 3, true, true, 'le'],
// analyses (analysis), ellipses (ellipsis), fungi (fungus),
// neuroses (neurosis), theses (thesis), emphases (emphasis),
// oases (oasis), crises (crisis), houses (house), bases (base),
@@ -124,11 +179,17 @@ final class EnglishInflector implements InflectorInterface
// edges (edge)
['segd', 4, true, true, 'dge'],
// outages (outage) - specific fix to avoid 'outag'
['segatuo', 7, true, true, 'outage'],
// roses (rose), garages (garage), cassettes (cassette),
// waltzes (waltz), heroes (hero), bushes (bush), arches (arch),
// shoes (shoe)
['se', 2, true, true, ['', 'e']],
// status (status)
['sutats', 6, true, true, 'status'],
// tags (tag)
['s', 1, true, true, ''],
@@ -147,10 +208,22 @@ 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
// passerby (passersby)
['ybressap', 8, true, true, 'passersby'],
// insigne (insignia, insignias)
['engisni', 7, true, true, ['insignia', 'insignias']],
// nodes (node)
['edon', 4, true, true, 'nodes'],
// axes (axis)
['sixa', 4, false, false, 'axes'],
// criterion (criteria)
['airetirc', 8, false, false, 'criterion'],
@@ -220,7 +293,13 @@ final class EnglishInflector implements InflectorInterface
// teeth (tooth)
['htoot', 5, true, true, 'teeth'],
// bacteria (bacterium), criteria (criterion), phenomena (phenomenon)
// albums (album)
['mubla', 5, true, true, 'albums'],
// quorums (quorum)
['murouq', 6, true, true, ['quora', 'quorums']],
// bacteria (bacterium), curricula (curriculum), media (medium), memoranda (memorandum), phenomena (phenomenon), strata (stratum)
['mu', 2, true, true, 'a'],
// men (man), women (woman)
@@ -229,17 +308,11 @@ final class EnglishInflector implements InflectorInterface
// people (person)
['nosrep', 6, true, true, ['persons', 'people']],
// bacteria (bacterium), criteria (criterion), phenomena (phenomenon)
['noi', 3, true, true, 'ions'],
// criteria (criterion)
['noiretirc', 9, true, true, 'criteria'],
// coupon (coupons)
['nop', 3, true, true, 'pons'],
// seasons (season), treasons (treason), poisons (poison), lessons (lesson)
['nos', 3, true, true, 'sons'],
// bacteria (bacterium), criteria (criterion), phenomena (phenomenon)
['no', 2, true, true, 'a'],
// phenomena (phenomenon)
['nonemonehp', 10, true, true, 'phenomena'],
// echoes (echo)
['ohce', 4, true, true, 'echoes'],
@@ -250,6 +323,9 @@ final class EnglishInflector implements InflectorInterface
// atlases (atlas)
['salta', 5, true, true, 'atlases'],
// aliases (alias)
['saila', 5, true, true, 'aliases'],
// irises (iris)
['siri', 4, true, true, 'irises'],
@@ -270,9 +346,21 @@ final class EnglishInflector implements InflectorInterface
// circuses (circus)
['suc', 3, true, true, 'cuses'],
// hippocampi (hippocampus)
['supmacoppih', 11, false, false, 'hippocampi'],
// campuses (campus)
['sup', 3, true, true, 'puses'],
// status (status)
['sutats', 6, true, true, ['status', 'statuses']],
// conspectuses (conspectus), prospectuses (prospectus)
['sutcep', 6, true, true, 'pectuses'],
// nexuses (nexus)
['suxen', 5, false, false, 'nexuses'],
// fungi (fungus), alumni (alumnus), syllabi (syllabus), radii (radius)
['su', 2, true, true, 'i'],
@@ -294,14 +382,14 @@ final class EnglishInflector implements InflectorInterface
// indices (index)
['xedni', 5, false, true, ['indicies', 'indexes']],
// fax (faxes, faxxes)
['xaf', 3, true, true, ['faxes', 'faxxes']],
// boxes (box)
['xo', 2, false, true, 'oxes'],
// indexes (index), matrixes (matrix)
['x', 1, true, false, ['cies', 'xes']],
// appendices (appendix)
['xi', 2, false, true, 'ices'],
// indexes (index), matrixes (matrix), appendices (appendix)
['x', 1, true, false, ['ces', 'xes']],
// babies (baby)
['y', 1, false, true, 'ies'],
@@ -325,15 +413,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',
@@ -345,11 +448,17 @@ final class EnglishInflector implements InflectorInterface
// species
'seiceps',
// traffic
'ciffart',
// aircraft
'tfarcria',
// hardware
'erawdrah',
];
/**
* {@inheritdoc}
*/
public function singularize(string $plural): array
{
$pluralRev = strrev($plural);
@@ -381,14 +490,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;
}
@@ -426,9 +535,6 @@ final class EnglishInflector implements InflectorInterface
return [$plural];
}
/**
* {@inheritdoc}
*/
public function pluralize(string $singular): array
{
$singularRev = strrev($singular);
@@ -461,14 +567,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;
}
+2 -8
View File
@@ -100,7 +100,7 @@ final class FrenchInflector implements InflectorInterface
['/^mes(sieur|seigneur)s$/', 'mon\1'],
['/^Mes(sieur|seigneur)s$/', 'Mon\1'],
//Default rule
// Default rule
['/s$/i', ''],
];
@@ -108,11 +108,8 @@ final class FrenchInflector implements InflectorInterface
* A list of words which should not be inflected.
* This list is only used by singularize.
*/
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|sas|secours|sens|souris|succès|talus|tapis|tas|taudis|temps|tiers|univers|velours|verglas|vernis|virus)$/i';
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)) {
+2 -2
View File
@@ -18,7 +18,7 @@ interface InflectorInterface
*
* If the method can't determine the form with certainty, several possible singulars are returned.
*
* @return string[] An array of possible singular forms
* @return string[]
*/
public function singularize(string $plural): array;
@@ -27,7 +27,7 @@ interface InflectorInterface
*
* If the method can't determine the form with certainty, several possible plurals are returned.
*
* @return string[] An array of possible plural forms
* @return string[]
*/
public function pluralize(string $singular): array;
}
+1 -1
View File
@@ -1,4 +1,4 @@
Copyright (c) 2019-2021 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
+18 -37
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,18 +88,13 @@ 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);
$callback = $r->getStaticVariables()['callback'];
$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);
$e = new \TypeError(\sprintf('Return value of %s() passed to %s::fromCallable() must be of the type string, %s returned.', $callback, static::class, $type));
}
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 = \PHP_VERSION_ID >= 80111 ? $r->getClosureCalledClass() : $r->getClosureScopeClass()) {
return $r->name;
}
+5 -5
View File
@@ -7,8 +7,8 @@ with bytes, UTF-8 code points and grapheme clusters in a unified way.
Resources
---------
* [Documentation](https://symfony.com/doc/current/components/string.html)
* [Contributing](https://symfony.com/doc/current/contributing/index.html)
* [Report issues](https://github.com/symfony/symfony/issues) and
[send Pull Requests](https://github.com/symfony/symfony/pulls)
in the [main Symfony repository](https://github.com/symfony/symfony)
* [Documentation](https://symfony.com/doc/current/components/string.html)
* [Contributing](https://symfony.com/doc/current/contributing/index.html)
* [Report issues](https://github.com/symfony/symfony/issues) and
[send Pull Requests](https://github.com/symfony/symfony/pulls)
in the [main Symfony repository](https://github.com/symfony/symfony)
+90 -34
View File
@@ -3,8 +3,8 @@
/*
* This file has been auto-generated by the Symfony String Component for internal use.
*
* Unicode version: 13.0.0
* Date: 2020-03-12T08:04:33+00:00
* Unicode version: 16.0.0
* Date: 2024-09-11T08:21:22+00:00
*/
return [
@@ -44,6 +44,10 @@ return [
9748,
9749,
],
[
9776,
9783,
],
[
9800,
9811,
@@ -52,6 +56,10 @@ return [
9855,
9855,
],
[
9866,
9871,
],
[
9875,
9875,
@@ -166,7 +174,7 @@ return [
],
[
12272,
12283,
12287,
],
[
12288,
@@ -394,7 +402,11 @@ return [
],
[
12736,
12771,
12773,
],
[
12783,
12783,
],
[
12784,
@@ -449,11 +461,11 @@ return [
19903,
],
[
19968,
40956,
19904,
19967,
],
[
40957,
19968,
40959,
],
[
@@ -836,22 +848,46 @@ return [
101120,
101589,
],
[
101631,
101631,
],
[
101632,
101640,
],
[
110576,
110579,
],
[
110581,
110587,
],
[
110589,
110590,
],
[
110592,
110847,
],
[
110848,
110878,
110882,
],
[
110898,
110898,
],
[
110928,
110930,
],
[
110933,
110933,
],
[
110948,
110951,
@@ -860,6 +896,14 @@ return [
110960,
111355,
],
[
119552,
119638,
],
[
119648,
119670,
],
[
126980,
126980,
@@ -996,6 +1040,10 @@ return [
128725,
128727,
],
[
128732,
128735,
],
[
128747,
128748,
@@ -1008,6 +1056,10 @@ return [
128992,
129003,
],
[
129008,
129008,
],
[
129292,
129338,
@@ -1018,58 +1070,46 @@ return [
],
[
129351,
129400,
],
[
129402,
129483,
],
[
129485,
129535,
],
[
129648,
129652,
],
[
129656,
129658,
129660,
],
[
129664,
129670,
129673,
],
[
129680,
129704,
129679,
129734,
],
[
129712,
129718,
129742,
129756,
],
[
129728,
129730,
129759,
129769,
],
[
129744,
129750,
129776,
129784,
],
[
131072,
173789,
173791,
],
[
173790,
173792,
173823,
],
[
173824,
177972,
177977,
],
[
177973,
177978,
177983,
],
[
@@ -1094,6 +1134,14 @@ return [
],
[
191457,
191471,
],
[
191472,
192093,
],
[
192094,
194559,
],
[
@@ -1114,6 +1162,14 @@ return [
],
[
201547,
201551,
],
[
201552,
205743,
],
[
205744,
262141,
],
];
+130 -10
View File
@@ -3,8 +3,8 @@
/*
* This file has been auto-generated by the Symfony String Component for internal use.
*
* Unicode version: 13.0.0
* Date: 2020-03-12T08:04:34+00:00
* Unicode version: 16.0.0
* Date: 2024-09-11T08:21:22+00:00
*/
return [
@@ -109,7 +109,11 @@ return [
2139,
],
[
2259,
2199,
2207,
],
[
2250,
2273,
],
[
@@ -272,6 +276,10 @@ return [
3076,
3076,
],
[
3132,
3132,
],
[
3134,
3136,
@@ -374,7 +382,7 @@ return [
],
[
3784,
3789,
3790,
],
[
3864,
@@ -470,7 +478,7 @@ return [
],
[
5938,
5940,
5939,
],
[
5970,
@@ -504,6 +512,10 @@ return [
6155,
6157,
],
[
6159,
6159,
],
[
6277,
6278,
@@ -574,7 +586,7 @@ return [
],
[
6847,
6848,
6862,
],
[
6912,
@@ -666,10 +678,6 @@ return [
],
[
7616,
7673,
],
[
7675,
7679,
],
[
@@ -908,14 +916,26 @@ return [
68900,
68903,
],
[
68969,
68973,
],
[
69291,
69292,
],
[
69372,
69375,
],
[
69446,
69456,
],
[
69506,
69509,
],
[
69633,
69633,
@@ -924,6 +944,14 @@ return [
69688,
69702,
],
[
69744,
69744,
],
[
69747,
69748,
],
[
69759,
69761,
@@ -936,6 +964,10 @@ return [
69817,
69818,
],
[
69826,
69826,
],
[
69888,
69890,
@@ -984,6 +1016,10 @@ return [
70206,
70206,
],
[
70209,
70209,
],
[
70367,
70367,
@@ -1012,6 +1048,26 @@ return [
70512,
70516,
],
[
70587,
70592,
],
[
70606,
70606,
],
[
70608,
70608,
],
[
70610,
70610,
],
[
70625,
70626,
],
[
70712,
70719,
@@ -1090,6 +1146,10 @@ return [
],
[
71453,
71453,
],
[
71455,
71455,
],
[
@@ -1228,6 +1288,42 @@ return [
73459,
73460,
],
[
73472,
73473,
],
[
73526,
73530,
],
[
73536,
73536,
],
[
73538,
73538,
],
[
73562,
73562,
],
[
78912,
78912,
],
[
78919,
78933,
],
[
90398,
90409,
],
[
90413,
90415,
],
[
92912,
92916,
@@ -1252,6 +1348,14 @@ return [
113821,
113822,
],
[
118528,
118573,
],
[
118576,
118598,
],
[
119143,
119145,
@@ -1316,14 +1420,30 @@ return [
122918,
122922,
],
[
123023,
123023,
],
[
123184,
123190,
],
[
123566,
123566,
],
[
123628,
123631,
],
[
124140,
124143,
],
[
124398,
124399,
],
[
125136,
125142,
+1 -1
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);
}
+81 -30
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,74 +55,94 @@ 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}
* @return void
*/
public function setLocale($locale)
public function setLocale(string $locale)
{
$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 ('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);
if (\is_array($this->symbolsMap) && isset($this->symbolsMap[$locale])) {
foreach ($this->symbolsMap[$locale] as $char => $replace) {
$unicodeString = $unicodeString->replace($char, ' '.$replace.' ');
if (\is_array($this->symbolsMap)) {
$map = null;
if (isset($this->symbolsMap[$locale ?? ''])) {
$map = $this->symbolsMap[$locale ?? ''];
} else {
$parent = self::getParentLocale($locale);
if ($parent && isset($this->symbolsMap[$parent])) {
$map = $this->symbolsMap[$parent];
}
}
if ($map) {
foreach ($map as $char => $replace) {
$unicodeString = $unicodeString->replace($char, ' '.$replace.' ');
}
}
}
@@ -143,17 +164,47 @@ class AsciiSlugger implements SluggerInterface, LocaleAwareInterface
}
// Locale not supported and no parent, fallback to any-latin
if (false === $str = strrchr($locale, '_')) {
if (!$parent = self::getParentLocale($locale)) {
return $this->transliterators[$locale] = null;
}
// Try to use the parent locale (ie. try "de" for "de_AT") and cache both locales
$parent = substr($locale, 0, -\strlen($str));
if ($id = self::LOCALE_TO_TRANSLITERATOR_ID[$parent] ?? null) {
$transliterator = \Transliterator::create($id.'/BGN') ?? \Transliterator::create($id);
}
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) {
return null;
}
if (false === $str = strrchr($locale, '_')) {
// no parent locale
return null;
}
return substr($locale, 0, -\strlen($str));
}
}
+1 -1
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;
}
+96 -50
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,6 +362,47 @@ class UnicodeString extends AbstractUnicodeString
return $prefix === grapheme_extract($this->string, \strlen($prefix), \GRAPHEME_EXTR_MAXBYTES);
}
public function trimPrefix($prefix): static
{
if (\is_array($prefix) || $prefix instanceof \Traversable) {
return parent::trimPrefix($prefix);
}
if ($prefix instanceof AbstractString) {
$prefix = $prefix->string;
} else {
$prefix = (string) $prefix;
}
if (!normalizer_is_normalized($prefix, \Normalizer::NFC)) {
$prefix = normalizer_normalize($prefix, \Normalizer::NFC);
}
return parent::trimPrefix($prefix);
}
public function trimSuffix($suffix): static
{
if (\is_array($suffix) || $suffix instanceof \Traversable) {
return parent::trimSuffix($suffix);
}
if ($suffix instanceof AbstractString) {
$suffix = $suffix->string;
} else {
$suffix = (string) $suffix;
}
if (!normalizer_is_normalized($suffix, \Normalizer::NFC)) {
$suffix = normalizer_normalize($suffix, \Normalizer::NFC);
}
return parent::trimSuffix($suffix);
}
/**
* @return void
*/
public function __wakeup()
{
if (!\is_string($this->string)) {
+9 -7
View File
@@ -16,18 +16,20 @@
}
],
"require": {
"php": ">=7.2.5",
"php": ">=8.1",
"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",
"symfony/http-client": "^4.4|^5.0",
"symfony/translation-contracts": "^1.1|^2",
"symfony/var-exporter": "^4.4|^5.0"
"symfony/http-client": "^5.4|^6.0|^7.0",
"symfony/intl": "^6.2|^7.0",
"symfony/translation-contracts": "^2.5|^3.0",
"symfony/var-exporter": "^5.4|^6.0|^7.0"
},
"conflict": {
"symfony/translation-contracts": "<2.5"
},
"autoload": {
"psr-4": { "Symfony\\Component\\String\\": "" },