From 5da67cef4efe1206c47536b23441e1b90e3cce1e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20H=C3=A4drich?= Date: Mon, 30 Sep 2024 00:06:01 +0200 Subject: [PATCH 01/14] Extract methods in separate classes --- src/Illuminate/Support/Casing.php | 202 ++++ src/Illuminate/Support/Generator.php | 383 +++++++ src/Illuminate/Support/PatternMatcher.php | 182 ++++ src/Illuminate/Support/Replacer.php | 208 ++++ src/Illuminate/Support/Sanitizer.php | 95 ++ src/Illuminate/Support/Str.php | 1193 ++------------------- src/Illuminate/Support/StrGrammar.php | 49 + 7 files changed, 1188 insertions(+), 1124 deletions(-) create mode 100644 src/Illuminate/Support/Casing.php create mode 100644 src/Illuminate/Support/Generator.php create mode 100644 src/Illuminate/Support/PatternMatcher.php create mode 100644 src/Illuminate/Support/Replacer.php create mode 100644 src/Illuminate/Support/Sanitizer.php create mode 100644 src/Illuminate/Support/StrGrammar.php diff --git a/src/Illuminate/Support/Casing.php b/src/Illuminate/Support/Casing.php new file mode 100644 index 000000000000..059f158dba96 --- /dev/null +++ b/src/Illuminate/Support/Casing.php @@ -0,0 +1,202 @@ + 1 + ? array_map([static::class, 'title'], $parts) + : array_map([static::class, 'title'], static::ucsplit(implode('_', $parts))); + + $collapsed = static::replace(['-', '_', ' '], '_', implode('_', $parts)); + + return implode(' ', array_filter(explode('_', $collapsed))); + } + + /** + * Make a string's first character lowercase. + * + * @param string $string + * @return string + */ + public static function lcfirst($string) + { + return static::lower(static::substr($string, 0, 1)).static::substr($string, 1); + } + + /** + * Make a string's first character uppercase. + * + * @param string $string + * @return string + */ + public static function ucfirst($string) + { + return static::upper(static::substr($string, 0, 1)).static::substr($string, 1); + } + + /** + * Convert a string to snake case. + * + * @param string $value + * @param string $delimiter + * @return string + */ + public static function snake($value, $delimiter = '_') + { + $key = $value; + + if (isset(static::$snakeCache[$key][$delimiter])) { + return static::$snakeCache[$key][$delimiter]; + } + + if (! ctype_lower($value)) { + $value = preg_replace('/\s+/u', '', ucwords($value)); + + $value = static::lower(preg_replace('/(.)(?=[A-Z])/u', '$1'.$delimiter, $value)); + } + + return static::$snakeCache[$key][$delimiter] = $value; + } + + /** + * Convert a value to studly caps case. + * + * @param string $value + * @return string + */ + public static function studly($value) + { + $key = $value; + + if (isset(static::$studlyCache[$key])) { + return static::$studlyCache[$key]; + } + + $words = explode(' ', static::replace(['-', '_'], ' ', $value)); + + $studlyWords = array_map(fn ($word) => static::ucfirst($word), $words); + + return static::$studlyCache[$key] = implode($studlyWords); + } + + /** + * Remove all strings from the casing caches. + * + * @return void + */ + public static function flushCache() + { + static::$snakeCache = []; + static::$camelCache = []; + static::$studlyCache = []; + } +} diff --git a/src/Illuminate/Support/Generator.php b/src/Illuminate/Support/Generator.php new file mode 100644 index 000000000000..527c411eb3be --- /dev/null +++ b/src/Illuminate/Support/Generator.php @@ -0,0 +1,383 @@ +setRandomGenerator(new CombGenerator( + $factory->getRandomGenerator(), + $factory->getNumberConverter() + )); + + $factory->setCodec(new TimestampFirstCombCodec( + $factory->getUuidBuilder() + )); + + return $factory->uuid4(); + } + + /** + * Set the callable that will be used to generate UUIDs. + * + * @param callable|null $factory + * @return void + */ + public static function createUuidsUsing(?callable $factory = null) + { + static::$uuidFactory = $factory; + } + + /** + * Set the sequence that will be used to generate UUIDs. + * + * @param array $sequence + * @param callable|null $whenMissing + * @return void + */ + public static function createUuidsUsingSequence(array $sequence, $whenMissing = null) + { + $next = 0; + + $whenMissing ??= function () use (&$next) { + $factoryCache = static::$uuidFactory; + + static::$uuidFactory = null; + + $uuid = static::uuid(); + + static::$uuidFactory = $factoryCache; + + $next++; + + return $uuid; + }; + + static::createUuidsUsing(function () use (&$next, $sequence, $whenMissing) { + if (array_key_exists($next, $sequence)) { + return $sequence[$next++]; + } + + return $whenMissing(); + }); + } + + /** + * Always return the same UUID when generating new UUIDs. + * + * @param \Closure|null $callback + * @return \Ramsey\Uuid\UuidInterface + */ + public static function freezeUuids(?Closure $callback = null) + { + $uuid = Str::uuid(); + + Str::createUuidsUsing(fn () => $uuid); + + if ($callback !== null) { + try { + $callback($uuid); + } finally { + Str::createUuidsNormally(); + } + } + + return $uuid; + } + + /** + * Indicate that UUIDs should be created normally and not using a custom factory. + * + * @return void + */ + public static function createUuidsNormally() + { + static::$uuidFactory = null; + } + + /** + * Generate a ULID. + * + * @param \DateTimeInterface|null $time + * @return \Symfony\Component\Uid\Ulid + */ + public static function ulid($time = null) + { + if (static::$ulidFactory) { + return call_user_func(static::$ulidFactory); + } + + if ($time === null) { + return new Ulid(); + } + + return new Ulid(Ulid::generate($time)); + } + + /** + * Indicate that ULIDs should be created normally and not using a custom factory. + * + * @return void + */ + public static function createUlidsNormally() + { + static::$ulidFactory = null; + } + + /** + * Set the callable that will be used to generate ULIDs. + * + * @param callable|null $factory + * @return void + */ + public static function createUlidsUsing(?callable $factory = null) + { + static::$ulidFactory = $factory; + } + + /** + * Set the sequence that will be used to generate ULIDs. + * + * @param array $sequence + * @param callable|null $whenMissing + * @return void + */ + public static function createUlidsUsingSequence(array $sequence, $whenMissing = null) + { + $next = 0; + + $whenMissing ??= function () use (&$next) { + $factoryCache = static::$ulidFactory; + + static::$ulidFactory = null; + + $ulid = static::ulid(); + + static::$ulidFactory = $factoryCache; + + $next++; + + return $ulid; + }; + + static::createUlidsUsing(function () use (&$next, $sequence, $whenMissing) { + if (array_key_exists($next, $sequence)) { + return $sequence[$next++]; + } + + return $whenMissing(); + }); + } + + /** + * Always return the same ULID when generating new ULIDs. + * + * @param Closure|null $callback + * @return Ulid + */ + public static function freezeUlids(?Closure $callback = null) + { + $ulid = Str::ulid(); + + Str::createUlidsUsing(fn () => $ulid); + + if ($callback !== null) { + try { + $callback($ulid); + } finally { + Str::createUlidsNormally(); + } + } + + return $ulid; + } + + /** + * Generate a random, secure password. + * + * @param int $length + * @param bool $letters + * @param bool $numbers + * @param bool $symbols + * @param bool $spaces + * @return string + */ + public static function password($length = 32, $letters = true, $numbers = true, $symbols = true, $spaces = false) + { + $password = new Collection(); + + $options = (new Collection([ + 'letters' => $letters === true ? [ + 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', + 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', + 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', + 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', + 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', + ] : null, + 'numbers' => $numbers === true ? [ + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + ] : null, + 'symbols' => $symbols === true ? [ + '~', '!', '#', '$', '%', '^', '&', '*', '(', ')', '-', + '_', '.', ',', '<', '>', '?', '/', '\\', '{', '}', '[', + ']', '|', ':', ';', + ] : null, + 'spaces' => $spaces === true ? [' '] : null, + ]))->filter()->each(fn ($c) => $password->push($c[random_int(0, count($c) - 1)]) + )->flatten(); + + $length = $length - $password->count(); + + return $password->merge($options->pipe( + fn ($c) => Collection::times($length, fn () => $c[random_int(0, $c->count() - 1)]) + ))->shuffle()->implode(''); + } +} diff --git a/src/Illuminate/Support/PatternMatcher.php b/src/Illuminate/Support/PatternMatcher.php new file mode 100644 index 000000000000..a6f59db5c5fd --- /dev/null +++ b/src/Illuminate/Support/PatternMatcher.php @@ -0,0 +1,182 @@ + $pattern + * @param string $value + * @return bool + */ + public static function is($pattern, $value) + { + $value = (string) $value; + + if (! is_iterable($pattern)) { + $pattern = [$pattern]; + } + + foreach ($pattern as $pattern) { + $pattern = (string) $pattern; + + // If the given value is an exact match we can of course return true right + // from the beginning. Otherwise, we will translate asterisks and do an + // actual pattern match against the two strings to see if they match. + if ($pattern === '*' || $pattern === $value) { + return true; + } + + $pattern = preg_quote($pattern, '#'); + + // Asterisks are translated into zero-or-more regular expression wildcards + // to make it convenient to check if the strings starts with the given + // pattern such as "library/*", making any string check convenient. + $pattern = str_replace('\*', '.*', $pattern); + + if (preg_match('#^'.$pattern.'\z#su', $value) === 1) { + return true; + } + } + + return false; + } + + /** + * Determine if a given string is 7 bit ASCII. + * + * @param string $value + * @return bool + */ + public static function isAscii($value) + { + return ASCII::is_ascii((string) $value); + } + + /** + * Determine if a given value is a valid URL. + * + * @param mixed $value + * @param array $protocols + * @return bool + */ + public static function isUrl($value, array $protocols = []) + { + if (! is_string($value)) { + return false; + } + + $protocolList = empty($protocols) + ? 'aaa|aaas|about|acap|acct|acd|acr|adiumxtra|adt|afp|afs|aim|amss|android|appdata|apt|ark|attachment|aw|barion|beshare|bitcoin|bitcoincash|blob|bolo|browserext|calculator|callto|cap|cast|casts|chrome|chrome-extension|cid|coap|coap\+tcp|coap\+ws|coaps|coaps\+tcp|coaps\+ws|com-eventbrite-attendee|content|conti|crid|cvs|dab|data|dav|diaspora|dict|did|dis|dlna-playcontainer|dlna-playsingle|dns|dntp|dpp|drm|drop|dtn|dvb|ed2k|elsi|example|facetime|fax|feed|feedready|file|filesystem|finger|first-run-pen-experience|fish|fm|ftp|fuchsia-pkg|geo|gg|git|gizmoproject|go|gopher|graph|gtalk|h323|ham|hcap|hcp|http|https|hxxp|hxxps|hydrazone|iax|icap|icon|im|imap|info|iotdisco|ipn|ipp|ipps|irc|irc6|ircs|iris|iris\.beep|iris\.lwz|iris\.xpc|iris\.xpcs|isostore|itms|jabber|jar|jms|keyparc|lastfm|ldap|ldaps|leaptofrogans|lorawan|lvlt|magnet|mailserver|mailto|maps|market|message|mid|mms|modem|mongodb|moz|ms-access|ms-browser-extension|ms-calculator|ms-drive-to|ms-enrollment|ms-excel|ms-eyecontrolspeech|ms-gamebarservices|ms-gamingoverlay|ms-getoffice|ms-help|ms-infopath|ms-inputapp|ms-lockscreencomponent-config|ms-media-stream-id|ms-mixedrealitycapture|ms-mobileplans|ms-officeapp|ms-people|ms-project|ms-powerpoint|ms-publisher|ms-restoretabcompanion|ms-screenclip|ms-screensketch|ms-search|ms-search-repair|ms-secondary-screen-controller|ms-secondary-screen-setup|ms-settings|ms-settings-airplanemode|ms-settings-bluetooth|ms-settings-camera|ms-settings-cellular|ms-settings-cloudstorage|ms-settings-connectabledevices|ms-settings-displays-topology|ms-settings-emailandaccounts|ms-settings-language|ms-settings-location|ms-settings-lock|ms-settings-nfctransactions|ms-settings-notifications|ms-settings-power|ms-settings-privacy|ms-settings-proximity|ms-settings-screenrotation|ms-settings-wifi|ms-settings-workplace|ms-spd|ms-sttoverlay|ms-transit-to|ms-useractivityset|ms-virtualtouchpad|ms-visio|ms-walk-to|ms-whiteboard|ms-whiteboard-cmd|ms-word|msnim|msrp|msrps|mss|mtqp|mumble|mupdate|mvn|news|nfs|ni|nih|nntp|notes|ocf|oid|onenote|onenote-cmd|opaquelocktoken|openpgp4fpr|pack|palm|paparazzi|payto|pkcs11|platform|pop|pres|prospero|proxy|pwid|psyc|pttp|qb|query|redis|rediss|reload|res|resource|rmi|rsync|rtmfp|rtmp|rtsp|rtsps|rtspu|s3|secondlife|service|session|sftp|sgn|shttp|sieve|simpleledger|sip|sips|skype|smb|sms|smtp|snews|snmp|soap\.beep|soap\.beeps|soldat|spiffe|spotify|ssh|steam|stun|stuns|submit|svn|tag|teamspeak|tel|teliaeid|telnet|tftp|tg|things|thismessage|tip|tn3270|tool|ts3server|turn|turns|tv|udp|unreal|urn|ut2004|v-event|vemmi|ventrilo|videotex|vnc|view-source|wais|webcal|wpid|ws|wss|wtai|wyciwyg|xcon|xcon-userid|xfire|xmlrpc\.beep|xmlrpc\.beeps|xmpp|xri|ymsgr|z39\.50|z39\.50r|z39\.50s' + : implode('|', $protocols); + + /* + * This pattern is derived from Symfony\Component\Validator\Constraints\UrlValidator (5.0.7). + * + * (c) Fabien Potencier http://symfony.com + */ + $pattern = '~^ + (LARAVEL_PROTOCOLS):// # protocol + (((?:[\_\.\pL\pN-]|%[0-9A-Fa-f]{2})+:)?((?:[\_\.\pL\pN-]|%[0-9A-Fa-f]{2})+)@)? # basic auth + ( + ([\pL\pN\pS\-\_\.])+(\.?([\pL\pN]|xn\-\-[\pL\pN-]+)+\.?) # a domain name + | # or + \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} # an IP address + | # or + \[ + (?:(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){6})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:::(?:(?:(?:[0-9a-f]{1,4})):){5})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:[0-9a-f]{1,4})))?::(?:(?:(?:[0-9a-f]{1,4})):){4})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,1}(?:(?:[0-9a-f]{1,4})))?::(?:(?:(?:[0-9a-f]{1,4})):){3})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,2}(?:(?:[0-9a-f]{1,4})))?::(?:(?:(?:[0-9a-f]{1,4})):){2})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,3}(?:(?:[0-9a-f]{1,4})))?::(?:(?:[0-9a-f]{1,4})):)(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,4}(?:(?:[0-9a-f]{1,4})))?::)(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,5}(?:(?:[0-9a-f]{1,4})))?::)(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,6}(?:(?:[0-9a-f]{1,4})))?::)))) + \] # an IPv6 address + ) + (:[0-9]+)? # a port (optional) + (?:/ (?:[\pL\pN\-._\~!$&\'()*+,;=:@]|%[0-9A-Fa-f]{2})* )* # a path + (?:\? (?:[\pL\pN\-._\~!$&\'\[\]()*+,;=:@/?]|%[0-9A-Fa-f]{2})* )? # a query (optional) + (?:\# (?:[\pL\pN\-._\~!$&\'()*+,;=:@/?]|%[0-9A-Fa-f]{2})* )? # a fragment (optional) + $~ixu'; + + return preg_match(str_replace('LARAVEL_PROTOCOLS', $protocolList, $pattern), $value) > 0; + } + + /** + * Determine if a given value is a valid UUID. + * + * @param mixed $value + * @return bool + */ + public static function isUuid($value) + { + if (! is_string($value)) { + return false; + } + + return preg_match('/^[\da-fA-F]{8}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{12}$/D', $value) > 0; + } + + /** + * Get the string matching the given pattern. + * + * @param string $pattern + * @param string $subject + * @return string + */ + public static function match($pattern, $subject) + { + preg_match($pattern, $subject, $matches); + + if (! $matches) { + return ''; + } + + return $matches[1] ?? $matches[0]; + } + + /** + * Determine if a given string matches a given pattern. + * + * @param string|iterable $pattern + * @param string $value + * @return bool + */ + public static function isMatch($pattern, $value) + { + $value = (string) $value; + + if (! is_iterable($pattern)) { + $pattern = [$pattern]; + } + + foreach ($pattern as $pattern) { + $pattern = (string) $pattern; + + if (preg_match($pattern, $value) === 1) { + return true; + } + } + + return false; + } + + /** + * Get the string matching the given pattern. + * + * @param string $pattern + * @param string $subject + * @return \Illuminate\Support\Collection + */ + public static function matchAll($pattern, $subject) + { + preg_match_all($pattern, $subject, $matches); + + if (empty($matches[0])) { + return collect(); + } + + return collect($matches[1] ?? $matches[0]); + } +} diff --git a/src/Illuminate/Support/Replacer.php b/src/Illuminate/Support/Replacer.php new file mode 100644 index 000000000000..fa4c256029b1 --- /dev/null +++ b/src/Illuminate/Support/Replacer.php @@ -0,0 +1,208 @@ + $replace + * @param string $subject + * @return string + */ + public static function replaceArray($search, $replace, $subject) + { + if ($replace instanceof Traversable) { + $replace = collect($replace)->all(); + } + + $segments = explode($search, $subject); + + $result = array_shift($segments); + + foreach ($segments as $segment) { + $result .= self::toStringOr(array_shift($replace) ?? $search, $search).$segment; + } + + return $result; + } + + /** + * Replace the given value in the given string. + * + * @param string|iterable $search + * @param string|iterable $replace + * @param string|iterable $subject + * @param bool $caseSensitive + * @return string|string[] + */ + public static function replace($search, $replace, $subject, $caseSensitive = true) + { + if ($search instanceof Traversable) { + $search = collect($search)->all(); + } + + if ($replace instanceof Traversable) { + $replace = collect($replace)->all(); + } + + if ($subject instanceof Traversable) { + $subject = collect($subject)->all(); + } + + return $caseSensitive + ? str_replace($search, $replace, $subject) + : str_ireplace($search, $replace, $subject); + } + + /** + * Replace the first occurrence of a given value in the string. + * + * @param string $search + * @param string $replace + * @param string $subject + * @return string + */ + public static function replaceFirst($search, $replace, $subject) + { + $search = (string) $search; + + if ($search === '') { + return $subject; + } + + $position = strpos($subject, $search); + + if ($position !== false) { + return substr_replace($subject, $replace, $position, strlen($search)); + } + + return $subject; + } + + /** + * Replace the first occurrence of the given value if it appears at the start of the string. + * + * @param string $search + * @param string $replace + * @param string $subject + * @return string + */ + public static function replaceStart($search, $replace, $subject) + { + $search = (string) $search; + + if ($search === '') { + return $subject; + } + + if (static::startsWith($subject, $search)) { + return static::replaceFirst($search, $replace, $subject); + } + + return $subject; + } + + /** + * Replace the last occurrence of a given value in the string. + * + * @param string $search + * @param string $replace + * @param string $subject + * @return string + */ + public static function replaceLast($search, $replace, $subject) + { + $search = (string) $search; + + if ($search === '') { + return $subject; + } + + $position = strrpos($subject, $search); + + if ($position !== false) { + return substr_replace($subject, $replace, $position, strlen($search)); + } + + return $subject; + } + + /** + * Replace the last occurrence of a given value if it appears at the end of the string. + * + * @param string $search + * @param string $replace + * @param string $subject + * @return string + */ + public static function replaceEnd($search, $replace, $subject) + { + $search = (string) $search; + + if ($search === '') { + return $subject; + } + + if (static::endsWith($subject, $search)) { + return static::replaceLast($search, $replace, $subject); + } + + return $subject; + } + + /** + * Replace the patterns matching the given regular expression. + * + * @param array|string $pattern + * @param \Closure|string[]|string $replace + * @param array|string $subject + * @param int $limit + * @return string|string[]|null + */ + public static function replaceMatches($pattern, $replace, $subject, $limit = -1) + { + if ($replace instanceof Closure) { + return preg_replace_callback($pattern, $replace, $subject, $limit); + } + + return preg_replace($pattern, $replace, $subject, $limit); + } + + /** + * Replace text within a portion of a string. + * + * @param string|string[] $string + * @param string|string[] $replace + * @param int|int[] $offset + * @param int|int[]|null $length + * @return string|string[] + */ + public static function substrReplace($string, $replace, $offset = 0, $length = null) + { + if ($length === null) { + $length = strlen($string); + } + + return substr_replace($string, $replace, $offset, $length); + } +} diff --git a/src/Illuminate/Support/Sanitizer.php b/src/Illuminate/Support/Sanitizer.php new file mode 100644 index 000000000000..7b809c75aefb --- /dev/null +++ b/src/Illuminate/Support/Sanitizer.php @@ -0,0 +1,95 @@ + $search + * @param string|iterable $subject + * @param bool $caseSensitive + * @return string + */ + public static function remove($search, $subject, $caseSensitive = true) + { + if ($search instanceof Traversable) { + $search = collect($search)->all(); + } + + return $caseSensitive + ? str_replace($search, '', $subject) + : str_ireplace($search, '', $subject); + } + + /** + * Remove all whitespace from both ends of a string. + * + * @param string $value + * @param string|null $charlist + * @return string + */ + public static function trim($value, $charlist = null) + { + if ($charlist === null) { + $trimDefaultCharacters = " \n\r\t\v\0"; + + return preg_replace('~^[\s\x{FEFF}\x{200B}\x{200E}'.$trimDefaultCharacters.']+|[\s\x{FEFF}\x{200B}\x{200E}'.$trimDefaultCharacters.']+$~u', '', $value) ?? trim($value); + } + + return trim($value, $charlist); + } + + /** + * Remove all whitespace from the beginning of a string. + * + * @param string $value + * @param string|null $charlist + * @return string + */ + public static function ltrim($value, $charlist = null) + { + if ($charlist === null) { + $ltrimDefaultCharacters = " \n\r\t\v\0"; + + return preg_replace('~^[\s\x{FEFF}\x{200B}\x{200E}'.$ltrimDefaultCharacters.']+~u', '', $value) ?? ltrim($value); + } + + return ltrim($value, $charlist); + } + + /** + * Remove all whitespace from the end of a string. + * + * @param string $value + * @param string|null $charlist + * @return string + */ + public static function rtrim($value, $charlist = null) + { + if ($charlist === null) { + $rtrimDefaultCharacters = " \n\r\t\v\0"; + + return preg_replace('~[\s\x{FEFF}\x{200B}\x{200E}'.$rtrimDefaultCharacters.']+$~u', '', $value) ?? rtrim($value); + } + + return rtrim($value, $charlist); + } + + /** + * Remove all "extra" blank space from the given string. + * + * @param string $value + * @return string + */ + public static function squish($value) + { + return preg_replace('~(\s|\x{3164}|\x{1160})+~u', ' ', static::trim($value)); + } +} diff --git a/src/Illuminate/Support/Str.php b/src/Illuminate/Support/Str.php index 0fc1a80b16bf..968b526a6994 100644 --- a/src/Illuminate/Support/Str.php +++ b/src/Illuminate/Support/Str.php @@ -2,7 +2,6 @@ namespace Illuminate\Support; -use Closure; use Illuminate\Support\Traits\Macroable; use JsonException; use League\CommonMark\Environment\Environment; @@ -10,61 +9,14 @@ use League\CommonMark\Extension\InlinesOnly\InlinesOnlyExtension; use League\CommonMark\GithubFlavoredMarkdownConverter; use League\CommonMark\MarkdownConverter; -use Ramsey\Uuid\Codec\TimestampFirstCombCodec; -use Ramsey\Uuid\Generator\CombGenerator; -use Ramsey\Uuid\Uuid; -use Ramsey\Uuid\UuidFactory; use Symfony\Component\Uid\Ulid; use Throwable; -use Traversable; use voku\helper\ASCII; class Str { use Macroable; - /** - * The cache of snake-cased words. - * - * @var array - */ - protected static $snakeCache = []; - - /** - * The cache of camel-cased words. - * - * @var array - */ - protected static $camelCache = []; - - /** - * The cache of studly-cased words. - * - * @var array - */ - protected static $studlyCache = []; - - /** - * The callback that should be used to generate UUIDs. - * - * @var callable|null - */ - protected static $uuidFactory; - - /** - * The callback that should be used to generate ULIDs. - * - * @var callable|null - */ - protected static $ulidFactory; - - /** - * The callback that should be used to generate random strings. - * - * @var callable|null - */ - protected static $randomStringFactory; - /** * Get a new stringable object from the given string. * @@ -209,21 +161,6 @@ public static function betweenFirst($subject, $from, $to) return static::before(static::after($subject, $from), $to); } - /** - * Convert a value to camel case. - * - * @param string $value - * @return string - */ - public static function camel($value) - { - if (isset(static::$camelCache[$value])) { - return static::$camelCache[$value]; - } - - return static::$camelCache[$value] = lcfirst(static::studly($value)); - } - /** * Get the character at the specified index. * @@ -328,19 +265,6 @@ public static function containsAll($haystack, $needles, $ignoreCase = false) return true; } - /** - * Convert the case of a string. - * - * @param string $string - * @param int $mode - * @param string|null $encoding - * @return string - */ - public static function convertCase(string $string, int $mode = MB_CASE_FOLD, ?string $encoding = 'UTF-8') - { - return mb_convert_case($string, $mode, $encoding); - } - /** * Replace consecutive instances of a given character with a single character in the given string. * @@ -459,57 +383,6 @@ public static function unwrap($value, $before, $after = null) return $value; } - /** - * Determine if a given string matches a given pattern. - * - * @param string|iterable $pattern - * @param string $value - * @return bool - */ - public static function is($pattern, $value) - { - $value = (string) $value; - - if (! is_iterable($pattern)) { - $pattern = [$pattern]; - } - - foreach ($pattern as $pattern) { - $pattern = (string) $pattern; - - // If the given value is an exact match we can of course return true right - // from the beginning. Otherwise, we will translate asterisks and do an - // actual pattern match against the two strings to see if they match. - if ($pattern === '*' || $pattern === $value) { - return true; - } - - $pattern = preg_quote($pattern, '#'); - - // Asterisks are translated into zero-or-more regular expression wildcards - // to make it convenient to check if the strings starts with the given - // pattern such as "library/*", making any string check convenient. - $pattern = str_replace('\*', '.*', $pattern); - - if (preg_match('#^'.$pattern.'\z#su', $value) === 1) { - return true; - } - } - - return false; - } - - /** - * Determine if a given string is 7 bit ASCII. - * - * @param string $value - * @return bool - */ - public static function isAscii($value) - { - return ASCII::is_ascii((string) $value); - } - /** * Determine if a given value is valid JSON. * @@ -535,64 +408,6 @@ public static function isJson($value) return true; } - /** - * Determine if a given value is a valid URL. - * - * @param mixed $value - * @param array $protocols - * @return bool - */ - public static function isUrl($value, array $protocols = []) - { - if (! is_string($value)) { - return false; - } - - $protocolList = empty($protocols) - ? 'aaa|aaas|about|acap|acct|acd|acr|adiumxtra|adt|afp|afs|aim|amss|android|appdata|apt|ark|attachment|aw|barion|beshare|bitcoin|bitcoincash|blob|bolo|browserext|calculator|callto|cap|cast|casts|chrome|chrome-extension|cid|coap|coap\+tcp|coap\+ws|coaps|coaps\+tcp|coaps\+ws|com-eventbrite-attendee|content|conti|crid|cvs|dab|data|dav|diaspora|dict|did|dis|dlna-playcontainer|dlna-playsingle|dns|dntp|dpp|drm|drop|dtn|dvb|ed2k|elsi|example|facetime|fax|feed|feedready|file|filesystem|finger|first-run-pen-experience|fish|fm|ftp|fuchsia-pkg|geo|gg|git|gizmoproject|go|gopher|graph|gtalk|h323|ham|hcap|hcp|http|https|hxxp|hxxps|hydrazone|iax|icap|icon|im|imap|info|iotdisco|ipn|ipp|ipps|irc|irc6|ircs|iris|iris\.beep|iris\.lwz|iris\.xpc|iris\.xpcs|isostore|itms|jabber|jar|jms|keyparc|lastfm|ldap|ldaps|leaptofrogans|lorawan|lvlt|magnet|mailserver|mailto|maps|market|message|mid|mms|modem|mongodb|moz|ms-access|ms-browser-extension|ms-calculator|ms-drive-to|ms-enrollment|ms-excel|ms-eyecontrolspeech|ms-gamebarservices|ms-gamingoverlay|ms-getoffice|ms-help|ms-infopath|ms-inputapp|ms-lockscreencomponent-config|ms-media-stream-id|ms-mixedrealitycapture|ms-mobileplans|ms-officeapp|ms-people|ms-project|ms-powerpoint|ms-publisher|ms-restoretabcompanion|ms-screenclip|ms-screensketch|ms-search|ms-search-repair|ms-secondary-screen-controller|ms-secondary-screen-setup|ms-settings|ms-settings-airplanemode|ms-settings-bluetooth|ms-settings-camera|ms-settings-cellular|ms-settings-cloudstorage|ms-settings-connectabledevices|ms-settings-displays-topology|ms-settings-emailandaccounts|ms-settings-language|ms-settings-location|ms-settings-lock|ms-settings-nfctransactions|ms-settings-notifications|ms-settings-power|ms-settings-privacy|ms-settings-proximity|ms-settings-screenrotation|ms-settings-wifi|ms-settings-workplace|ms-spd|ms-sttoverlay|ms-transit-to|ms-useractivityset|ms-virtualtouchpad|ms-visio|ms-walk-to|ms-whiteboard|ms-whiteboard-cmd|ms-word|msnim|msrp|msrps|mss|mtqp|mumble|mupdate|mvn|news|nfs|ni|nih|nntp|notes|ocf|oid|onenote|onenote-cmd|opaquelocktoken|openpgp4fpr|pack|palm|paparazzi|payto|pkcs11|platform|pop|pres|prospero|proxy|pwid|psyc|pttp|qb|query|redis|rediss|reload|res|resource|rmi|rsync|rtmfp|rtmp|rtsp|rtsps|rtspu|s3|secondlife|service|session|sftp|sgn|shttp|sieve|simpleledger|sip|sips|skype|smb|sms|smtp|snews|snmp|soap\.beep|soap\.beeps|soldat|spiffe|spotify|ssh|steam|stun|stuns|submit|svn|tag|teamspeak|tel|teliaeid|telnet|tftp|tg|things|thismessage|tip|tn3270|tool|ts3server|turn|turns|tv|udp|unreal|urn|ut2004|v-event|vemmi|ventrilo|videotex|vnc|view-source|wais|webcal|wpid|ws|wss|wtai|wyciwyg|xcon|xcon-userid|xfire|xmlrpc\.beep|xmlrpc\.beeps|xmpp|xri|ymsgr|z39\.50|z39\.50r|z39\.50s' - : implode('|', $protocols); - - /* - * This pattern is derived from Symfony\Component\Validator\Constraints\UrlValidator (5.0.7). - * - * (c) Fabien Potencier http://symfony.com - */ - $pattern = '~^ - (LARAVEL_PROTOCOLS):// # protocol - (((?:[\_\.\pL\pN-]|%[0-9A-Fa-f]{2})+:)?((?:[\_\.\pL\pN-]|%[0-9A-Fa-f]{2})+)@)? # basic auth - ( - ([\pL\pN\pS\-\_\.])+(\.?([\pL\pN]|xn\-\-[\pL\pN-]+)+\.?) # a domain name - | # or - \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} # an IP address - | # or - \[ - (?:(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){6})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:::(?:(?:(?:[0-9a-f]{1,4})):){5})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:[0-9a-f]{1,4})))?::(?:(?:(?:[0-9a-f]{1,4})):){4})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,1}(?:(?:[0-9a-f]{1,4})))?::(?:(?:(?:[0-9a-f]{1,4})):){3})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,2}(?:(?:[0-9a-f]{1,4})))?::(?:(?:(?:[0-9a-f]{1,4})):){2})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,3}(?:(?:[0-9a-f]{1,4})))?::(?:(?:[0-9a-f]{1,4})):)(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,4}(?:(?:[0-9a-f]{1,4})))?::)(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,5}(?:(?:[0-9a-f]{1,4})))?::)(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,6}(?:(?:[0-9a-f]{1,4})))?::)))) - \] # an IPv6 address - ) - (:[0-9]+)? # a port (optional) - (?:/ (?:[\pL\pN\-._\~!$&\'()*+,;=:@]|%[0-9A-Fa-f]{2})* )* # a path - (?:\? (?:[\pL\pN\-._\~!$&\'\[\]()*+,;=:@/?]|%[0-9A-Fa-f]{2})* )? # a query (optional) - (?:\# (?:[\pL\pN\-._\~!$&\'()*+,;=:@/?]|%[0-9A-Fa-f]{2})* )? # a fragment (optional) - $~ixu'; - - return preg_match(str_replace('LARAVEL_PROTOCOLS', $protocolList, $pattern), $value) > 0; - } - - /** - * Determine if a given value is a valid UUID. - * - * @param mixed $value - * @return bool - */ - public static function isUuid($value) - { - if (! is_string($value)) { - return false; - } - - return preg_match('/^[\da-fA-F]{8}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{12}$/D', $value) > 0; - } - /** * Determine if a given value is a valid ULID. * @@ -608,17 +423,6 @@ public static function isUlid($value) return Ulid::isValid($value); } - /** - * Convert a string to kebab case. - * - * @param string $value - * @return string - */ - public static function kebab($value) - { - return static::snake($value, '-'); - } - /** * Return the length of the given string. * @@ -660,18 +464,6 @@ public static function limit($value, $limit = 100, $end = '...', $preserveWords return preg_replace("/(.*)\s.*/", '$1', $trimmed).$end; } - - /** - * Convert the given string to lower-case. - * - * @param string $value - * @return string - */ - public static function lower($value) - { - return mb_strtolower($value, 'UTF-8'); - } - /** * Limit the number of words in a string. * @@ -767,79 +559,6 @@ public static function mask($string, $character, $index, $length = null, $encodi return $start.str_repeat(mb_substr($character, 0, 1, $encoding), $segmentLen).$end; } - /** - * Get the string matching the given pattern. - * - * @param string $pattern - * @param string $subject - * @return string - */ - public static function match($pattern, $subject) - { - preg_match($pattern, $subject, $matches); - - if (! $matches) { - return ''; - } - - return $matches[1] ?? $matches[0]; - } - - /** - * Determine if a given string matches a given pattern. - * - * @param string|iterable $pattern - * @param string $value - * @return bool - */ - public static function isMatch($pattern, $value) - { - $value = (string) $value; - - if (! is_iterable($pattern)) { - $pattern = [$pattern]; - } - - foreach ($pattern as $pattern) { - $pattern = (string) $pattern; - - if (preg_match($pattern, $value) === 1) { - return true; - } - } - - return false; - } - - /** - * Get the string matching the given pattern. - * - * @param string $pattern - * @param string $subject - * @return \Illuminate\Support\Collection - */ - public static function matchAll($pattern, $subject) - { - preg_match_all($pattern, $subject, $matches); - - if (empty($matches[0])) { - return collect(); - } - - return collect($matches[1] ?? $matches[0]); - } - - /** - * Remove all non-numeric characters from a string. - * - * @param string $value - * @return string - */ - public static function numbers($value) - { - return preg_replace('/[^0-9]/', '', $value); - } - /** * Pad both sides of a string with another. * @@ -925,512 +644,125 @@ public static function parseCallback($callback, $default = null) } /** - * Get the plural form of an English word. + * Find the multi-byte safe position of the first occurrence of a given substring in a string. * - * @param string $value - * @param int|array|\Countable $count - * @return string + * @param string $haystack + * @param string $needle + * @param int $offset + * @param string|null $encoding + * @return int|false */ - public static function plural($value, $count = 2) + public static function position($haystack, $needle, $offset = 0, $encoding = null) { - return Pluralizer::plural($value, $count); + return mb_strpos($haystack, (string) $needle, $offset, $encoding); } /** - * Pluralize the last word of an English, studly caps case string. + * Repeat the given string. * - * @param string $value - * @param int|array|\Countable $count + * @param string $string + * @param int $times * @return string */ - public static function pluralStudly($value, $count = 2) + public static function repeat(string $string, int $times) { - $parts = preg_split('/(.)(?=[A-Z])/u', $value, -1, PREG_SPLIT_DELIM_CAPTURE); - - $lastWord = array_pop($parts); - - return implode('', $parts).self::plural($lastWord, $count); + return str_repeat($string, $times); } /** - * Generate a random, secure password. + * Convert the given value to a string or return the given fallback on failure. * - * @param int $length - * @param bool $letters - * @param bool $numbers - * @param bool $symbols - * @param bool $spaces + * @param mixed $value + * @param string $fallback * @return string */ - public static function password($length = 32, $letters = true, $numbers = true, $symbols = true, $spaces = false) + private static function toStringOr($value, $fallback) { - $password = new Collection(); - - $options = (new Collection([ - 'letters' => $letters === true ? [ - 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', - 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', - 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', - 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', - 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', - ] : null, - 'numbers' => $numbers === true ? [ - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - ] : null, - 'symbols' => $symbols === true ? [ - '~', '!', '#', '$', '%', '^', '&', '*', '(', ')', '-', - '_', '.', ',', '<', '>', '?', '/', '\\', '{', '}', '[', - ']', '|', ':', ';', - ] : null, - 'spaces' => $spaces === true ? [' '] : null, - ]))->filter()->each(fn ($c) => $password->push($c[random_int(0, count($c) - 1)]) - )->flatten(); - - $length = $length - $password->count(); - - return $password->merge($options->pipe( - fn ($c) => Collection::times($length, fn () => $c[random_int(0, $c->count() - 1)]) - ))->shuffle()->implode(''); + try { + return (string) $value; + } catch (Throwable $e) { + return $fallback; + } } /** - * Find the multi-byte safe position of the first occurrence of a given substring in a string. + * Reverse the given string. * - * @param string $haystack - * @param string $needle - * @param int $offset - * @param string|null $encoding - * @return int|false + * @param string $value + * @return string */ - public static function position($haystack, $needle, $offset = 0, $encoding = null) + public static function reverse(string $value) { - return mb_strpos($haystack, (string) $needle, $offset, $encoding); + return implode(array_reverse(mb_str_split($value))); } /** - * Generate a more truly "random" alpha-numeric string. + * Begin a string with a single instance of a given value. * - * @param int $length + * @param string $value + * @param string $prefix * @return string */ - public static function random($length = 16) + public static function start($value, $prefix) { - return (static::$randomStringFactory ?? function ($length) { - $string = ''; - - while (($len = strlen($string)) < $length) { - $size = $length - $len; - - $bytesSize = (int) ceil($size / 3) * 3; - - $bytes = random_bytes($bytesSize); - - $string .= substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $size); - } + $quoted = preg_quote($prefix, '/'); - return $string; - })($length); + return $prefix.preg_replace('/^(?:'.$quoted.')+/u', '', $value); } /** - * Set the callable that will be used to generate random strings. + * Convert the given string to APA-style title case. * - * @param callable|null $factory - * @return void - */ - public static function createRandomStringsUsing(?callable $factory = null) - { - static::$randomStringFactory = $factory; - } - - /** - * Set the sequence that will be used to generate random strings. + * See: https://apastyle.apa.org/style-grammar-guidelines/capitalization/title-case * - * @param array $sequence - * @param callable|null $whenMissing - * @return void + * @param string $value + * @return string */ - public static function createRandomStringsUsingSequence(array $sequence, $whenMissing = null) + public static function apa($value) { - $next = 0; + if (trim($value) === '') { + return $value; + } - $whenMissing ??= function ($length) use (&$next) { - $factoryCache = static::$randomStringFactory; + $minorWords = [ + 'and', 'as', 'but', 'for', 'if', 'nor', 'or', 'so', 'yet', 'a', 'an', + 'the', 'at', 'by', 'for', 'in', 'of', 'off', 'on', 'per', 'to', 'up', 'via', + 'et', 'ou', 'un', 'une', 'la', 'le', 'les', 'de', 'du', 'des', 'par', 'à', + ]; - static::$randomStringFactory = null; + $endPunctuation = ['.', '!', '?', ':', '—', ',']; - $randomString = static::random($length); + $words = preg_split('/\s+/', $value, -1, PREG_SPLIT_NO_EMPTY); - static::$randomStringFactory = $factoryCache; + for ($i = 0; $i < count($words); $i++) { + $lowercaseWord = mb_strtolower($words[$i]); - $next++; + if (str_contains($lowercaseWord, '-')) { + $hyphenatedWords = explode('-', $lowercaseWord); - return $randomString; - }; + $hyphenatedWords = array_map(function ($part) use ($minorWords) { + return (in_array($part, $minorWords) && mb_strlen($part) <= 3) + ? $part + : mb_strtoupper(mb_substr($part, 0, 1)).mb_substr($part, 1); + }, $hyphenatedWords); - static::createRandomStringsUsing(function ($length) use (&$next, $sequence, $whenMissing) { - if (array_key_exists($next, $sequence)) { - return $sequence[$next++]; + $words[$i] = implode('-', $hyphenatedWords); + } else { + if (in_array($lowercaseWord, $minorWords) && + mb_strlen($lowercaseWord) <= 3 && + ! ($i === 0 || in_array(mb_substr($words[$i - 1], -1), $endPunctuation))) { + $words[$i] = $lowercaseWord; + } else { + $words[$i] = mb_strtoupper(mb_substr($lowercaseWord, 0, 1)).mb_substr($lowercaseWord, 1); + } } + } - return $whenMissing($length); - }); + return implode(' ', $words); } /** - * Indicate that random strings should be created normally and not using a custom factory. - * - * @return void - */ - public static function createRandomStringsNormally() - { - static::$randomStringFactory = null; - } - - /** - * Repeat the given string. - * - * @param string $string - * @param int $times - * @return string - */ - public static function repeat(string $string, int $times) - { - return str_repeat($string, $times); - } - - /** - * Replace a given value in the string sequentially with an array. - * - * @param string $search - * @param iterable $replace - * @param string $subject - * @return string - */ - public static function replaceArray($search, $replace, $subject) - { - if ($replace instanceof Traversable) { - $replace = collect($replace)->all(); - } - - $segments = explode($search, $subject); - - $result = array_shift($segments); - - foreach ($segments as $segment) { - $result .= self::toStringOr(array_shift($replace) ?? $search, $search).$segment; - } - - return $result; - } - - /** - * Convert the given value to a string or return the given fallback on failure. - * - * @param mixed $value - * @param string $fallback - * @return string - */ - private static function toStringOr($value, $fallback) - { - try { - return (string) $value; - } catch (Throwable $e) { - return $fallback; - } - } - - /** - * Replace the given value in the given string. - * - * @param string|iterable $search - * @param string|iterable $replace - * @param string|iterable $subject - * @param bool $caseSensitive - * @return string|string[] - */ - public static function replace($search, $replace, $subject, $caseSensitive = true) - { - if ($search instanceof Traversable) { - $search = collect($search)->all(); - } - - if ($replace instanceof Traversable) { - $replace = collect($replace)->all(); - } - - if ($subject instanceof Traversable) { - $subject = collect($subject)->all(); - } - - return $caseSensitive - ? str_replace($search, $replace, $subject) - : str_ireplace($search, $replace, $subject); - } - - /** - * Replace the first occurrence of a given value in the string. - * - * @param string $search - * @param string $replace - * @param string $subject - * @return string - */ - public static function replaceFirst($search, $replace, $subject) - { - $search = (string) $search; - - if ($search === '') { - return $subject; - } - - $position = strpos($subject, $search); - - if ($position !== false) { - return substr_replace($subject, $replace, $position, strlen($search)); - } - - return $subject; - } - - /** - * Replace the first occurrence of the given value if it appears at the start of the string. - * - * @param string $search - * @param string $replace - * @param string $subject - * @return string - */ - public static function replaceStart($search, $replace, $subject) - { - $search = (string) $search; - - if ($search === '') { - return $subject; - } - - if (static::startsWith($subject, $search)) { - return static::replaceFirst($search, $replace, $subject); - } - - return $subject; - } - - /** - * Replace the last occurrence of a given value in the string. - * - * @param string $search - * @param string $replace - * @param string $subject - * @return string - */ - public static function replaceLast($search, $replace, $subject) - { - $search = (string) $search; - - if ($search === '') { - return $subject; - } - - $position = strrpos($subject, $search); - - if ($position !== false) { - return substr_replace($subject, $replace, $position, strlen($search)); - } - - return $subject; - } - - /** - * Replace the last occurrence of a given value if it appears at the end of the string. - * - * @param string $search - * @param string $replace - * @param string $subject - * @return string - */ - public static function replaceEnd($search, $replace, $subject) - { - $search = (string) $search; - - if ($search === '') { - return $subject; - } - - if (static::endsWith($subject, $search)) { - return static::replaceLast($search, $replace, $subject); - } - - return $subject; - } - - /** - * Replace the patterns matching the given regular expression. - * - * @param array|string $pattern - * @param \Closure|string[]|string $replace - * @param array|string $subject - * @param int $limit - * @return string|string[]|null - */ - public static function replaceMatches($pattern, $replace, $subject, $limit = -1) - { - if ($replace instanceof Closure) { - return preg_replace_callback($pattern, $replace, $subject, $limit); - } - - return preg_replace($pattern, $replace, $subject, $limit); - } - - /** - * Remove any occurrence of the given string in the subject. - * - * @param string|iterable $search - * @param string|iterable $subject - * @param bool $caseSensitive - * @return string - */ - public static function remove($search, $subject, $caseSensitive = true) - { - if ($search instanceof Traversable) { - $search = collect($search)->all(); - } - - return $caseSensitive - ? str_replace($search, '', $subject) - : str_ireplace($search, '', $subject); - } - - /** - * Reverse the given string. - * - * @param string $value - * @return string - */ - public static function reverse(string $value) - { - return implode(array_reverse(mb_str_split($value))); - } - - /** - * Begin a string with a single instance of a given value. - * - * @param string $value - * @param string $prefix - * @return string - */ - public static function start($value, $prefix) - { - $quoted = preg_quote($prefix, '/'); - - return $prefix.preg_replace('/^(?:'.$quoted.')+/u', '', $value); - } - - /** - * Convert the given string to upper-case. - * - * @param string $value - * @return string - */ - public static function upper($value) - { - return mb_strtoupper($value, 'UTF-8'); - } - - /** - * Convert the given string to proper case. - * - * @param string $value - * @return string - */ - public static function title($value) - { - return mb_convert_case($value, MB_CASE_TITLE, 'UTF-8'); - } - - /** - * Convert the given string to proper case for each word. - * - * @param string $value - * @return string - */ - public static function headline($value) - { - $parts = explode(' ', $value); - - $parts = count($parts) > 1 - ? array_map([static::class, 'title'], $parts) - : array_map([static::class, 'title'], static::ucsplit(implode('_', $parts))); - - $collapsed = static::replace(['-', '_', ' '], '_', implode('_', $parts)); - - return implode(' ', array_filter(explode('_', $collapsed))); - } - - /** - * Convert the given string to APA-style title case. - * - * See: https://apastyle.apa.org/style-grammar-guidelines/capitalization/title-case - * - * @param string $value - * @return string - */ - public static function apa($value) - { - if (trim($value) === '') { - return $value; - } - - $minorWords = [ - 'and', 'as', 'but', 'for', 'if', 'nor', 'or', 'so', 'yet', 'a', 'an', - 'the', 'at', 'by', 'for', 'in', 'of', 'off', 'on', 'per', 'to', 'up', 'via', - 'et', 'ou', 'un', 'une', 'la', 'le', 'les', 'de', 'du', 'des', 'par', 'à', - ]; - - $endPunctuation = ['.', '!', '?', ':', '—', ',']; - - $words = preg_split('/\s+/', $value, -1, PREG_SPLIT_NO_EMPTY); - - for ($i = 0; $i < count($words); $i++) { - $lowercaseWord = mb_strtolower($words[$i]); - - if (str_contains($lowercaseWord, '-')) { - $hyphenatedWords = explode('-', $lowercaseWord); - - $hyphenatedWords = array_map(function ($part) use ($minorWords) { - return (in_array($part, $minorWords) && mb_strlen($part) <= 3) - ? $part - : mb_strtoupper(mb_substr($part, 0, 1)).mb_substr($part, 1); - }, $hyphenatedWords); - - $words[$i] = implode('-', $hyphenatedWords); - } else { - if (in_array($lowercaseWord, $minorWords) && - mb_strlen($lowercaseWord) <= 3 && - ! ($i === 0 || in_array(mb_substr($words[$i - 1], -1), $endPunctuation))) { - $words[$i] = $lowercaseWord; - } else { - $words[$i] = mb_strtoupper(mb_substr($lowercaseWord, 0, 1)).mb_substr($lowercaseWord, 1); - } - } - } - - return implode(' ', $words); - } - - /** - * Get the singular form of an English word. - * - * @param string $value - * @return string - */ - public static function singular($value) - { - return Pluralizer::singular($value); - } - - /** - * Generate a URL friendly "slug" from a given string. + * Generate a URL friendly "slug" from a given string. * * @param string $title * @param string $separator @@ -1463,95 +795,6 @@ public static function slug($title, $separator = '-', $language = 'en', $diction return trim($title, $separator); } - /** - * Convert a string to snake case. - * - * @param string $value - * @param string $delimiter - * @return string - */ - public static function snake($value, $delimiter = '_') - { - $key = $value; - - if (isset(static::$snakeCache[$key][$delimiter])) { - return static::$snakeCache[$key][$delimiter]; - } - - if (! ctype_lower($value)) { - $value = preg_replace('/\s+/u', '', ucwords($value)); - - $value = static::lower(preg_replace('/(.)(?=[A-Z])/u', '$1'.$delimiter, $value)); - } - - return static::$snakeCache[$key][$delimiter] = $value; - } - - /** - * Remove all whitespace from both ends of a string. - * - * @param string $value - * @param string|null $charlist - * @return string - */ - public static function trim($value, $charlist = null) - { - if ($charlist === null) { - $trimDefaultCharacters = " \n\r\t\v\0"; - - return preg_replace('~^[\s\x{FEFF}\x{200B}\x{200E}'.$trimDefaultCharacters.']+|[\s\x{FEFF}\x{200B}\x{200E}'.$trimDefaultCharacters.']+$~u', '', $value) ?? trim($value); - } - - return trim($value, $charlist); - } - - /** - * Remove all whitespace from the beginning of a string. - * - * @param string $value - * @param string|null $charlist - * @return string - */ - public static function ltrim($value, $charlist = null) - { - if ($charlist === null) { - $ltrimDefaultCharacters = " \n\r\t\v\0"; - - return preg_replace('~^[\s\x{FEFF}\x{200B}\x{200E}'.$ltrimDefaultCharacters.']+~u', '', $value) ?? ltrim($value); - } - - return ltrim($value, $charlist); - } - - /** - * Remove all whitespace from the end of a string. - * - * @param string $value - * @param string|null $charlist - * @return string - */ - public static function rtrim($value, $charlist = null) - { - if ($charlist === null) { - $rtrimDefaultCharacters = " \n\r\t\v\0"; - - return preg_replace('~[\s\x{FEFF}\x{200B}\x{200E}'.$rtrimDefaultCharacters.']+$~u', '', $value) ?? rtrim($value); - } - - return rtrim($value, $charlist); - } - - /** - * Remove all "extra" blank space from the given string. - * - * @param string $value - * @return string - */ - public static function squish($value) - { - return preg_replace('~(\s|\x{3164}|\x{1160})+~u', ' ', static::trim($value)); - } - /** * Determine if a given string starts with a given substring. * @@ -1574,27 +817,6 @@ public static function startsWith($haystack, $needles) return false; } - /** - * Convert a value to studly caps case. - * - * @param string $value - * @return string - */ - public static function studly($value) - { - $key = $value; - - if (isset(static::$studlyCache[$key])) { - return static::$studlyCache[$key]; - } - - $words = explode(' ', static::replace(['-', '_'], ' ', $value)); - - $studlyWords = array_map(fn ($word) => static::ucfirst($word), $words); - - return static::$studlyCache[$key] = implode($studlyWords); - } - /** * Returns the portion of the string specified by the start and length parameters. * @@ -1627,24 +849,6 @@ public static function substrCount($haystack, $needle, $offset = 0, $length = nu return substr_count($haystack, $needle, $offset); } - /** - * Replace text within a portion of a string. - * - * @param string|string[] $string - * @param string|string[] $replace - * @param int|int[] $offset - * @param int|int[]|null $length - * @return string|string[] - */ - public static function substrReplace($string, $replace, $offset = 0, $length = null) - { - if ($length === null) { - $length = strlen($string); - } - - return substr_replace($string, $replace, $offset, $length); - } - /** * Swap multiple keywords in a string with other keywords. * @@ -1696,28 +900,6 @@ public static function fromBase64($string, $strict = false) return base64_decode($string, $strict); } - /** - * Make a string's first character lowercase. - * - * @param string $string - * @return string - */ - public static function lcfirst($string) - { - return static::lower(static::substr($string, 0, 1)).static::substr($string, 1); - } - - /** - * Make a string's first character uppercase. - * - * @param string $string - * @return string - */ - public static function ucfirst($string) - { - return static::upper(static::substr($string, 0, 1)).static::substr($string, 1); - } - /** * Split a string into pieces by uppercase characters. * @@ -1754,241 +936,4 @@ public static function wordWrap($string, $characters = 75, $break = "\n", $cutLo { return wordwrap($string, $characters, $break, $cutLongWords); } - - /** - * Generate a UUID (version 4). - * - * @return \Ramsey\Uuid\UuidInterface - */ - public static function uuid() - { - return static::$uuidFactory - ? call_user_func(static::$uuidFactory) - : Uuid::uuid4(); - } - - /** - * Generate a UUID (version 7). - * - * @param \DateTimeInterface|null $time - * @return \Ramsey\Uuid\UuidInterface - */ - public static function uuid7($time = null) - { - return static::$uuidFactory - ? call_user_func(static::$uuidFactory) - : Uuid::uuid7($time); - } - - /** - * Generate a time-ordered UUID. - * - * @return \Ramsey\Uuid\UuidInterface - */ - public static function orderedUuid() - { - if (static::$uuidFactory) { - return call_user_func(static::$uuidFactory); - } - - $factory = new UuidFactory; - - $factory->setRandomGenerator(new CombGenerator( - $factory->getRandomGenerator(), - $factory->getNumberConverter() - )); - - $factory->setCodec(new TimestampFirstCombCodec( - $factory->getUuidBuilder() - )); - - return $factory->uuid4(); - } - - /** - * Set the callable that will be used to generate UUIDs. - * - * @param callable|null $factory - * @return void - */ - public static function createUuidsUsing(?callable $factory = null) - { - static::$uuidFactory = $factory; - } - - /** - * Set the sequence that will be used to generate UUIDs. - * - * @param array $sequence - * @param callable|null $whenMissing - * @return void - */ - public static function createUuidsUsingSequence(array $sequence, $whenMissing = null) - { - $next = 0; - - $whenMissing ??= function () use (&$next) { - $factoryCache = static::$uuidFactory; - - static::$uuidFactory = null; - - $uuid = static::uuid(); - - static::$uuidFactory = $factoryCache; - - $next++; - - return $uuid; - }; - - static::createUuidsUsing(function () use (&$next, $sequence, $whenMissing) { - if (array_key_exists($next, $sequence)) { - return $sequence[$next++]; - } - - return $whenMissing(); - }); - } - - /** - * Always return the same UUID when generating new UUIDs. - * - * @param \Closure|null $callback - * @return \Ramsey\Uuid\UuidInterface - */ - public static function freezeUuids(?Closure $callback = null) - { - $uuid = Str::uuid(); - - Str::createUuidsUsing(fn () => $uuid); - - if ($callback !== null) { - try { - $callback($uuid); - } finally { - Str::createUuidsNormally(); - } - } - - return $uuid; - } - - /** - * Indicate that UUIDs should be created normally and not using a custom factory. - * - * @return void - */ - public static function createUuidsNormally() - { - static::$uuidFactory = null; - } - - /** - * Generate a ULID. - * - * @param \DateTimeInterface|null $time - * @return \Symfony\Component\Uid\Ulid - */ - public static function ulid($time = null) - { - if (static::$ulidFactory) { - return call_user_func(static::$ulidFactory); - } - - if ($time === null) { - return new Ulid(); - } - - return new Ulid(Ulid::generate($time)); - } - - /** - * Indicate that ULIDs should be created normally and not using a custom factory. - * - * @return void - */ - public static function createUlidsNormally() - { - static::$ulidFactory = null; - } - - /** - * Set the callable that will be used to generate ULIDs. - * - * @param callable|null $factory - * @return void - */ - public static function createUlidsUsing(?callable $factory = null) - { - static::$ulidFactory = $factory; - } - - /** - * Set the sequence that will be used to generate ULIDs. - * - * @param array $sequence - * @param callable|null $whenMissing - * @return void - */ - public static function createUlidsUsingSequence(array $sequence, $whenMissing = null) - { - $next = 0; - - $whenMissing ??= function () use (&$next) { - $factoryCache = static::$ulidFactory; - - static::$ulidFactory = null; - - $ulid = static::ulid(); - - static::$ulidFactory = $factoryCache; - - $next++; - - return $ulid; - }; - - static::createUlidsUsing(function () use (&$next, $sequence, $whenMissing) { - if (array_key_exists($next, $sequence)) { - return $sequence[$next++]; - } - - return $whenMissing(); - }); - } - - /** - * Always return the same ULID when generating new ULIDs. - * - * @param Closure|null $callback - * @return Ulid - */ - public static function freezeUlids(?Closure $callback = null) - { - $ulid = Str::ulid(); - - Str::createUlidsUsing(fn () => $ulid); - - if ($callback !== null) { - try { - $callback($ulid); - } finally { - Str::createUlidsNormally(); - } - } - - return $ulid; - } - - /** - * Remove all strings from the casing caches. - * - * @return void - */ - public static function flushCache() - { - static::$snakeCache = []; - static::$camelCache = []; - static::$studlyCache = []; - } } diff --git a/src/Illuminate/Support/StrGrammar.php b/src/Illuminate/Support/StrGrammar.php new file mode 100644 index 000000000000..dc6ed6cde2fc --- /dev/null +++ b/src/Illuminate/Support/StrGrammar.php @@ -0,0 +1,49 @@ + Date: Mon, 30 Sep 2024 00:11:39 +0200 Subject: [PATCH 02/14] fix: :pencil2: Rename class to match file name --- src/Illuminate/Support/StrGrammar.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Illuminate/Support/StrGrammar.php b/src/Illuminate/Support/StrGrammar.php index dc6ed6cde2fc..bfbb6f1998a7 100644 --- a/src/Illuminate/Support/StrGrammar.php +++ b/src/Illuminate/Support/StrGrammar.php @@ -4,7 +4,7 @@ use Illuminate\Support\Traits\Macroable; -class Casing +class StrGrammar { use Macroable; From bd21862d69ac5d9473bc283c3b1acfeeb6b9548a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20H=C3=A4drich?= Date: Mon, 30 Sep 2024 14:06:50 +0200 Subject: [PATCH 03/14] Change respective classes in tests --- tests/Support/SupportCasingTest.php | 188 +++++ tests/Support/SupportGeneratorTest.php | 309 +++++++ tests/Support/SupportPatternMatcherTest.php | 180 ++++ tests/Support/SupportPluralizerTest.php | 74 +- tests/Support/SupportReplacerTest.php | 105 +++ tests/Support/SupportSanitizerTest.php | 149 ++++ tests/Support/SupportStrTest.php | 882 +------------------- 7 files changed, 970 insertions(+), 917 deletions(-) create mode 100644 tests/Support/SupportCasingTest.php create mode 100644 tests/Support/SupportGeneratorTest.php create mode 100644 tests/Support/SupportPatternMatcherTest.php create mode 100644 tests/Support/SupportReplacerTest.php create mode 100644 tests/Support/SupportSanitizerTest.php diff --git a/tests/Support/SupportCasingTest.php b/tests/Support/SupportCasingTest.php new file mode 100644 index 000000000000..d3fd4e9b009c --- /dev/null +++ b/tests/Support/SupportCasingTest.php @@ -0,0 +1,188 @@ +assertSame('HELLO', Casing::convertCase('hello', MB_CASE_UPPER)); + $this->assertSame('WORLD', Casing::convertCase('WORLD', MB_CASE_UPPER)); + + // Lower Case Conversion + $this->assertSame('hello', Casing::convertCase('HELLO', MB_CASE_LOWER)); + $this->assertSame('world', Casing::convertCase('WORLD', MB_CASE_LOWER)); + + // Case Folding + $this->assertSame('hello', Casing::convertCase('HeLLo', MB_CASE_FOLD)); + $this->assertSame('world', Casing::convertCase('WoRLD', MB_CASE_FOLD)); + + // Multi-byte String + $this->assertSame('ÜÖÄ', Casing::convertCase('üöä', MB_CASE_UPPER, 'UTF-8')); + $this->assertSame('üöä', Casing::convertCase('ÜÖÄ', MB_CASE_LOWER, 'UTF-8')); + + // Unsupported Mode + $this->expectException(\ValueError::class); + Casing::convertCase('Hello', -1); + } + + public function testKebab() + { + $this->assertSame('laravel-php-framework', Casing::kebab('LaravelPhpFramework')); + $this->assertSame('laravel-php-framework', Casing::kebab('Laravel Php Framework')); + $this->assertSame('laravel❤-php-framework', Casing::kebab('Laravel ❤ Php Framework')); + $this->assertSame('', Casing::kebab('')); + } + + public function testLower() + { + $this->assertSame('foo bar baz', Casing::lower('FOO BAR BAZ')); + $this->assertSame('foo bar baz', Casing::lower('fOo Bar bAz')); + } + + public function testUpper() + { + $this->assertSame('FOO BAR BAZ', Casing::upper('foo bar baz')); + $this->assertSame('FOO BAR BAZ', Casing::upper('foO bAr BaZ')); + } + + public function testCamel(): void + { + $this->assertSame('laravelPHPFramework', Casing::camel('Laravel_p_h_p_framework')); + $this->assertSame('laravelPhpFramework', Casing::camel('Laravel_php_framework')); + $this->assertSame('laravelPhPFramework', Casing::camel('Laravel-phP-framework')); + $this->assertSame('laravelPhpFramework', Casing::camel('Laravel -_- php -_- framework ')); + + $this->assertSame('fooBar', Casing::camel('FooBar')); + $this->assertSame('fooBar', Casing::camel('foo_bar')); + $this->assertSame('fooBar', Casing::camel('foo_bar')); // test cache + $this->assertSame('fooBarBaz', Casing::camel('Foo-barBaz')); + $this->assertSame('fooBarBaz', Casing::camel('foo-bar_baz')); + + $this->assertSame('', Casing::camel('')); + $this->assertSame('lARAVELPHPFRAMEWORK', Casing::camel('LARAVEL_PHP_FRAMEWORK')); + $this->assertSame('laravelPhpFramework', Casing::camel(' laravel php framework ')); + + $this->assertSame('foo1Bar', Casing::camel('foo1_bar')); + $this->assertSame('1FooBar', Casing::camel('1 foo bar')); + } + + public function testStringTitle() + { + $this->assertSame('Jefferson Costella', Casing::title('jefferson costella')); + $this->assertSame('Jefferson Costella', Casing::title('jefFErson coSTella')); + + $this->assertSame('', Casing::title('')); + $this->assertSame('123 Laravel', Casing::title('123 laravel')); + $this->assertSame('❤Laravel', Casing::title('❤laravel')); + $this->assertSame('Laravel ❤', Casing::title('laravel ❤')); + $this->assertSame('Laravel123', Casing::title('laravel123')); + $this->assertSame('Laravel123', Casing::title('Laravel123')); + + $longString = 'lorem ipsum '.str_repeat('dolor sit amet ', 1000); + $expectedResult = 'Lorem Ipsum Dolor Sit Amet '.str_repeat('Dolor Sit Amet ', 999); + $this->assertSame($expectedResult, Casing::title($longString)); + } + + public function testStringHeadline() + { + $this->assertSame('Jefferson Costella', Casing::headline('jefferson costella')); + $this->assertSame('Jefferson Costella', Casing::headline('jefFErson coSTella')); + $this->assertSame('Jefferson Costella Uses Laravel', Casing::headline('jefferson_costella uses-_Laravel')); + $this->assertSame('Jefferson Costella Uses Laravel', Casing::headline('jefferson_costella uses__Laravel')); + + $this->assertSame('Laravel P H P Framework', Casing::headline('laravel_p_h_p_framework')); + $this->assertSame('Laravel P H P Framework', Casing::headline('laravel _p _h _p _framework')); + $this->assertSame('Laravel Php Framework', Casing::headline('laravel_php_framework')); + $this->assertSame('Laravel Ph P Framework', Casing::headline('laravel-phP-framework')); + $this->assertSame('Laravel Php Framework', Casing::headline('laravel -_- php -_- framework ')); + + $this->assertSame('Foo Bar', Casing::headline('fooBar')); + $this->assertSame('Foo Bar', Casing::headline('foo_bar')); + $this->assertSame('Foo Bar Baz', Casing::headline('foo-barBaz')); + $this->assertSame('Foo Bar Baz', Casing::headline('foo-bar_baz')); + + $this->assertSame('Öffentliche Überraschungen', Casing::headline('öffentliche-überraschungen')); + $this->assertSame('Öffentliche Überraschungen', Casing::headline('-_öffentliche_überraschungen_-')); + $this->assertSame('Öffentliche Überraschungen', Casing::headline('-öffentliche überraschungen')); + + $this->assertSame('Sind Öde Und So', Casing::headline('sindÖdeUndSo')); + + $this->assertSame('Orwell 1984', Casing::headline('orwell 1984')); + $this->assertSame('Orwell 1984', Casing::headline('orwell 1984')); + $this->assertSame('Orwell 1984', Casing::headline('-orwell-1984 -')); + $this->assertSame('Orwell 1984', Casing::headline(' orwell_- 1984 ')); + } + + public function testLcfirst() + { + $this->assertSame('laravel', Casing::lcfirst('Laravel')); + $this->assertSame('laravel framework', Casing::lcfirst('Laravel framework')); + $this->assertSame('мама', Casing::lcfirst('Мама')); + $this->assertSame('мама мыла раму', Casing::lcfirst('Мама мыла раму')); + } + + public function testUcfirst() + { + $this->assertSame('Laravel', Casing::ucfirst('laravel')); + $this->assertSame('Laravel framework', Casing::ucfirst('laravel framework')); + $this->assertSame('Мама', Casing::ucfirst('мама')); + $this->assertSame('Мама мыла раму', Casing::ucfirst('мама мыла раму')); + } + + public function testFlushCache() + { + $reflection = new ReflectionClass(Casing::class); + $property = $reflection->getProperty('snakeCache'); + + Casing::flushCache(); + $this->assertEmpty($property->getValue()); + + Casing::snake('Taylor Otwell'); + $this->assertNotEmpty($property->getValue()); + + Casing::flushCache(); + $this->assertEmpty($property->getValue()); + } + + public function testSnake() + { + $this->assertSame('laravel_p_h_p_framework', Casing::snake('LaravelPHPFramework')); + $this->assertSame('laravel_php_framework', Casing::snake('LaravelPhpFramework')); + $this->assertSame('laravel php framework', Casing::snake('LaravelPhpFramework', ' ')); + $this->assertSame('laravel_php_framework', Casing::snake('Laravel Php Framework')); + $this->assertSame('laravel_php_framework', Casing::snake('Laravel Php Framework ')); + // ensure cache keys don't overlap + $this->assertSame('laravel__php__framework', Casing::snake('LaravelPhpFramework', '__')); + $this->assertSame('laravel_php_framework_', Casing::snake('LaravelPhpFramework_', '_')); + $this->assertSame('laravel_php_framework', Casing::snake('laravel php Framework')); + $this->assertSame('laravel_php_frame_work', Casing::snake('laravel php FrameWork')); + // prevent breaking changes + $this->assertSame('foo-bar', Casing::snake('foo-bar')); + $this->assertSame('foo-_bar', Casing::snake('Foo-Bar')); + $this->assertSame('foo__bar', Casing::snake('Foo_Bar')); + $this->assertSame('żółtałódka', Casing::snake('ŻółtaŁódka')); + } + + public function testStudly() + { + $this->assertSame('LaravelPHPFramework', Casing::studly('laravel_p_h_p_framework')); + $this->assertSame('LaravelPhpFramework', Casing::studly('laravel_php_framework')); + $this->assertSame('LaravelPhPFramework', Casing::studly('laravel-phP-framework')); + $this->assertSame('LaravelPhpFramework', Casing::studly('laravel -_- php -_- framework ')); + + $this->assertSame('FooBar', Casing::studly('fooBar')); + $this->assertSame('FooBar', Casing::studly('foo_bar')); + $this->assertSame('FooBar', Casing::studly('foo_bar')); // test cache + $this->assertSame('FooBarBaz', Casing::studly('foo-barBaz')); + $this->assertSame('FooBarBaz', Casing::studly('foo-bar_baz')); + + $this->assertSame('ÖffentlicheÜberraschungen', Casing::studly('öffentliche-überraschungen')); + } +} diff --git a/tests/Support/SupportGeneratorTest.php b/tests/Support/SupportGeneratorTest.php new file mode 100644 index 000000000000..b9688fac243c --- /dev/null +++ b/tests/Support/SupportGeneratorTest.php @@ -0,0 +1,309 @@ +assertEquals(16, strlen(Generator::random())); + $randomInteger = random_int(1, 100); + $this->assertEquals($randomInteger, strlen(Generator::random($randomInteger))); + $this->assertIsString(Generator::random()); + } + + public function testWhetherTheNumberOfGeneratedCharactersIsEquallyDistributed() + { + $results = []; + // take 6.200.000 samples, because there are 62 different characters + for ($i = 0; $i < 620000; $i++) { + $random = Generator::random(1); + $results[$random] = ($results[$random] ?? 0) + 1; + } + + // each character should occur 100.000 times with a variance of 5%. + foreach ($results as $result) { + $this->assertEqualsWithDelta(10000, $result, 500); + } + } + + public function testRandomStringFactoryCanBeSet() + { + Generator::createRandomStringsUsing(fn ($length) => 'length:'.$length); + + $this->assertSame('length:7', Generator::random(7)); + $this->assertSame('length:7', Generator::random(7)); + + Generator::createRandomStringsNormally(); + + $this->assertNotSame('length:7', Generator::random()); + } + + public function testItCanSpecifyASequenceOfRandomStringsToUtilise() + { + Generator::createRandomStringsUsingSequence([ + 0 => 'x', + // 1 => just generate a random one here... + 2 => 'y', + 3 => 'z', + // ... => continue to generate random strings... + ]); + + $this->assertSame('x', Generator::random()); + $this->assertSame(16, mb_strlen(Generator::random())); + $this->assertSame('y', Generator::random()); + $this->assertSame('z', Generator::random()); + $this->assertSame(16, mb_strlen(Generator::random())); + $this->assertSame(16, mb_strlen(Generator::random())); + + Generator::createRandomStringsNormally(); + } + + public function testItCanSpecifyAFallbackForARandomStringSequence() + { + Generator::createRandomStringsUsingSequence([Generator::random(), Generator::random()], fn () => throw new Exception('Out of random strings.')); + Generator::random(); + Generator::random(); + + try { + $this->expectExceptionMessage('Out of random strings.'); + Generator::random(); + $this->fail(); + } finally { + Generator::createRandomStringsNormally(); + } + } + + public function testUuid() + { + $this->assertInstanceOf(UuidInterface::class, Generator::uuid()); + $this->assertInstanceOf(UuidInterface::class, Generator::orderedUuid()); + $this->assertInstanceOf(UuidInterface::class, Generator::uuid7()); + } + + public function testItCanFreezeUuids() + { + $this->assertNotSame((string) Generator::uuid(), (string) Generator::uuid()); + $this->assertNotSame(Generator::uuid(), Generator::uuid()); + + $uuid = Generator::freezeUuids(); + + $this->assertSame($uuid, Generator::uuid()); + $this->assertSame(Generator::uuid(), Generator::uuid()); + $this->assertSame((string) $uuid, (string) Generator::uuid()); + $this->assertSame((string) Generator::uuid(), (string) Generator::uuid()); + + Generator::createUuidsNormally(); + + $this->assertNotSame(Generator::uuid(), Generator::uuid()); + $this->assertNotSame((string) Generator::uuid(), (string) Generator::uuid()); + } + + public function testItCanFreezeUuidsInAClosure() + { + $uuids = []; + + $uuid = Generator::freezeUuids(function ($uuid) use (&$uuids) { + $uuids[] = $uuid; + $uuids[] = Generator::uuid(); + $uuids[] = Generator::uuid(); + }); + + $this->assertSame($uuid, $uuids[0]); + $this->assertSame((string) $uuid, (string) $uuids[0]); + $this->assertSame((string) $uuids[0], (string) $uuids[1]); + $this->assertSame($uuids[0], $uuids[1]); + $this->assertSame((string) $uuids[0], (string) $uuids[1]); + $this->assertSame($uuids[1], $uuids[2]); + $this->assertSame((string) $uuids[1], (string) $uuids[2]); + $this->assertNotSame(Generator::uuid(), Generator::uuid()); + $this->assertNotSame((string) Generator::uuid(), (string) Generator::uuid()); + + Generator::createUuidsNormally(); + } + + public function testItCreatesUuidsNormallyAfterFailureWithinFreezeMethod() + { + try { + Generator::freezeUuids(function () { + Generator::createUuidsUsing(fn () => Str::of('1234')); + $this->assertSame('1234', Generator::uuid()->toString()); + throw new \Exception('Something failed.'); + }); + } catch (\Exception) { + $this->assertNotSame('1234', Generator::uuid()->toString()); + } + } + + public function testItCanSpecifyASequenceOfUuidsToUtilise() + { + Generator::createUuidsUsingSequence([ + 0 => ($zeroth = Generator::uuid()), + 1 => ($first = Generator::uuid7()), + // just generate a random one here... + 3 => ($third = Generator::uuid()), + // continue to generate random uuids... + ]); + + $retrieved = Generator::uuid(); + $this->assertSame($zeroth, $retrieved); + $this->assertSame((string) $zeroth, (string) $retrieved); + + $retrieved = Generator::uuid(); + $this->assertSame($first, $retrieved); + $this->assertSame((string) $first, (string) $retrieved); + + $retrieved = Generator::uuid(); + $this->assertFalse(in_array($retrieved, [$zeroth, $first, $third], true)); + $this->assertFalse(in_array((string) $retrieved, [(string) $zeroth, (string) $first, (string) $third], true)); + + $retrieved = Generator::uuid(); + $this->assertSame($third, $retrieved); + $this->assertSame((string) $third, (string) $retrieved); + + $retrieved = Generator::uuid(); + $this->assertFalse(in_array($retrieved, [$zeroth, $first, $third], true)); + $this->assertFalse(in_array((string) $retrieved, [(string) $zeroth, (string) $first, (string) $third], true)); + + Generator::createUuidsNormally(); + } + + public function testItCanSpecifyAFallbackForASequence() + { + Generator::createUuidsUsingSequence([Generator::uuid(), Generator::uuid()], fn () => throw new Exception('Out of Uuids.')); + Generator::uuid(); + Generator::uuid(); + + try { + $this->expectExceptionMessage('Out of Uuids.'); + Generator::uuid(); + $this->fail(); + } finally { + Generator::createUuidsNormally(); + } + } + + public function testItCanFreezeUlids() + { + $this->assertNotSame((string) Generator::ulid(), (string) Generator::ulid()); + $this->assertNotSame(Generator::ulid(), Generator::ulid()); + + $ulid = Generator::freezeUlids(); + + $this->assertSame($ulid, Generator::ulid()); + $this->assertSame(Generator::ulid(), Generator::ulid()); + $this->assertSame((string) $ulid, (string) Generator::ulid()); + $this->assertSame((string) Generator::ulid(), (string) Generator::ulid()); + + Generator::createUlidsNormally(); + + $this->assertNotSame(Generator::ulid(), Generator::ulid()); + $this->assertNotSame((string) Generator::ulid(), (string) Generator::ulid()); + } + + public function testItCanFreezeUlidsInAClosure() + { + $ulids = []; + + $ulid = Generator::freezeUlids(function ($ulid) use (&$ulids) { + $ulids[] = $ulid; + $ulids[] = Generator::ulid(); + $ulids[] = Generator::ulid(); + }); + + $this->assertSame($ulid, $ulids[0]); + $this->assertSame((string) $ulid, (string) $ulids[0]); + $this->assertSame((string) $ulids[0], (string) $ulids[1]); + $this->assertSame($ulids[0], $ulids[1]); + $this->assertSame((string) $ulids[0], (string) $ulids[1]); + $this->assertSame($ulids[1], $ulids[2]); + $this->assertSame((string) $ulids[1], (string) $ulids[2]); + $this->assertNotSame(Generator::ulid(), Generator::ulid()); + $this->assertNotSame((string) Generator::ulid(), (string) Generator::ulid()); + + Generator::createUlidsNormally(); + } + + public function testItCreatesUlidsNormallyAfterFailureWithinFreezeMethod() + { + try { + Generator::freezeUlids(function () { + Generator::createUlidsUsing(fn () => Str::of('1234')); + $this->assertSame('1234', (string) Generator::ulid()); + throw new \Exception('Something failed'); + }); + } catch (\Exception) { + $this->assertNotSame('1234', (string) Generator::ulid()); + } + } + + public function testItCanSpecifyASequenceOfUlidsToUtilise() + { + Generator::createUlidsUsingSequence([ + 0 => ($zeroth = Generator::ulid()), + 1 => ($first = Generator::ulid()), + // just generate a random one here... + 3 => ($third = Generator::ulid()), + // continue to generate random ulids... + ]); + + $retrieved = Generator::ulid(); + $this->assertSame($zeroth, $retrieved); + $this->assertSame((string) $zeroth, (string) $retrieved); + + $retrieved = Generator::ulid(); + $this->assertSame($first, $retrieved); + $this->assertSame((string) $first, (string) $retrieved); + + $retrieved = Generator::ulid(); + $this->assertFalse(in_array($retrieved, [$zeroth, $first, $third], true)); + $this->assertFalse(in_array((string) $retrieved, [(string) $zeroth, (string) $first, (string) $third], true)); + + $retrieved = Generator::ulid(); + $this->assertSame($third, $retrieved); + $this->assertSame((string) $third, (string) $retrieved); + + $retrieved = Generator::ulid(); + $this->assertFalse(in_array($retrieved, [$zeroth, $first, $third], true)); + $this->assertFalse(in_array((string) $retrieved, [(string) $zeroth, (string) $first, (string) $third], true)); + + Generator::createUlidsNormally(); + } + + public function testItCanSpecifyAFallbackForAUlidSequence() + { + Generator::createUlidsUsingSequence( + [Generator::ulid(), Generator::ulid()], + fn () => throw new Exception('Out of Ulids'), + ); + Generator::ulid(); + Generator::ulid(); + + try { + $this->expectExceptionMessage('Out of Ulids'); + Generator::ulid(); + $this->fail(); + } finally { + Generator::createUlidsNormally(); + } + } + + public function testPasswordCreation() + { + $this->assertTrue(strlen(Generator::password()) === 32); + + $this->assertStringNotContainsString(' ', Generator::password()); + $this->assertStringContainsString(' ', Generator::password(spaces: true)); + + $this->assertTrue( + Str::of(Generator::password())->contains(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']) + ); + } +} \ No newline at end of file diff --git a/tests/Support/SupportPatternMatcherTest.php b/tests/Support/SupportPatternMatcherTest.php new file mode 100644 index 000000000000..b5137d524c8a --- /dev/null +++ b/tests/Support/SupportPatternMatcherTest.php @@ -0,0 +1,180 @@ +assertTrue(PatternMatcher::is('/', '/')); + $this->assertFalse(PatternMatcher::is('/', ' /')); + $this->assertFalse(PatternMatcher::is('/', '/a')); + $this->assertTrue(PatternMatcher::is('foo/*', 'foo/bar/baz')); + + $this->assertTrue(PatternMatcher::is('*@*', 'App\Class@method')); + $this->assertTrue(PatternMatcher::is('*@*', 'app\Class@')); + $this->assertTrue(PatternMatcher::is('*@*', '@method')); + + // is case sensitive + $this->assertFalse(PatternMatcher::is('*BAZ*', 'foo/bar/baz')); + $this->assertFalse(PatternMatcher::is('*FOO*', 'foo/bar/baz')); + $this->assertFalse(PatternMatcher::is('A', 'a')); + + // Accepts array of patterns + $this->assertTrue(PatternMatcher::is(['a*', 'b*'], 'a/')); + $this->assertTrue(PatternMatcher::is(['a*', 'b*'], 'b/')); + $this->assertFalse(PatternMatcher::is(['a*', 'b*'], 'f/')); + + // numeric values and patterns + $this->assertFalse(PatternMatcher::is(['a*', 'b*'], 123)); + $this->assertTrue(PatternMatcher::is(['*2*', 'b*'], 11211)); + + $this->assertTrue(PatternMatcher::is('*/foo', 'blah/baz/foo')); + + $valueObject = new StringableObjectStub('foo/bar/baz'); + $patternObject = new StringableObjectStub('foo/*'); + + $this->assertTrue(PatternMatcher::is('foo/bar/baz', $valueObject)); + $this->assertTrue(PatternMatcher::is($patternObject, $valueObject)); + + // empty patterns + $this->assertFalse(PatternMatcher::is([], 'test')); + + $this->assertFalse(PatternMatcher::is('', 0)); + $this->assertFalse(PatternMatcher::is([null], 0)); + $this->assertTrue(PatternMatcher::is([null], null)); + } + + public function testIsWithMultilineStrings() + { + $this->assertFalse(PatternMatcher::is('/', "/\n")); + $this->assertTrue(PatternMatcher::is('/*', "/\n")); + $this->assertTrue(PatternMatcher::is('*/*', "/\n")); + $this->assertTrue(PatternMatcher::is('*/*', "\n/\n")); + + $this->assertTrue(PatternMatcher::is('*', "\n")); + $this->assertTrue(PatternMatcher::is('*', "\n\n")); + $this->assertFalse(PatternMatcher::is('', "\n")); + $this->assertFalse(PatternMatcher::is('', "\n\n")); + + $multilineValue = <<<'VALUE' + assertTrue(PatternMatcher::is($multilineValue, $multilineValue)); + $this->assertTrue(PatternMatcher::is('*', $multilineValue)); + $this->assertTrue(PatternMatcher::is("*namespace Illuminate\Tests\*", $multilineValue)); + $this->assertFalse(PatternMatcher::is("namespace Illuminate\Tests\*", $multilineValue)); + $this->assertFalse(PatternMatcher::is("*namespace Illuminate\Tests", $multilineValue)); + $this->assertTrue(PatternMatcher::is('assertTrue(PatternMatcher::is("assertFalse(PatternMatcher::is('use Exception;', $multilineValue)); + $this->assertFalse(PatternMatcher::is('use Exception;*', $multilineValue)); + $this->assertTrue(PatternMatcher::is('*use Exception;', $multilineValue)); + + $this->assertTrue(PatternMatcher::is("assertTrue(PatternMatcher::is(<<<'PATTERN' + assertTrue(PatternMatcher::is(<<<'PATTERN' + assertTrue(PatternMatcher::isUrl('https://laravel.com')); + $this->assertFalse(PatternMatcher::isUrl('invalid url')); + } + + #[DataProvider('validUuidList')] + public function testIsUuidWithValidUuid($uuid) + { + $this->assertTrue(PatternMatcher::isUuid($uuid)); + } + + #[DataProvider('invalidUuidList')] + public function testIsUuidWithInvalidUuid($uuid) + { + $this->assertFalse(PatternMatcher::isUuid($uuid)); + } + + public static function validUuidList() + { + return [ + ['a0a2a2d2-0b87-4a18-83f2-2529882be2de'], + ['145a1e72-d11d-11e8-a8d5-f2801f1b9fd1'], + ['00000000-0000-0000-0000-000000000000'], + ['e60d3f48-95d7-4d8d-aad0-856f29a27da2'], + ['ff6f8cb0-c57d-11e1-9b21-0800200c9a66'], + ['ff6f8cb0-c57d-21e1-9b21-0800200c9a66'], + ['ff6f8cb0-c57d-31e1-9b21-0800200c9a66'], + ['ff6f8cb0-c57d-41e1-9b21-0800200c9a66'], + ['ff6f8cb0-c57d-51e1-9b21-0800200c9a66'], + ['FF6F8CB0-C57D-11E1-9B21-0800200C9A66'], + ]; + } + + public static function invalidUuidList() + { + return [ + ['not a valid uuid so we can test this'], + ['zf6f8cb0-c57d-11e1-9b21-0800200c9a66'], + ['145a1e72-d11d-11e8-a8d5-f2801f1b9fd1'.PHP_EOL], + ['145a1e72-d11d-11e8-a8d5-f2801f1b9fd1 '], + [' 145a1e72-d11d-11e8-a8d5-f2801f1b9fd1'], + ['145a1e72-d11d-11e8-a8d5-f2z01f1b9fd1'], + ['3f6f8cb0-c57d-11e1-9b21-0800200c9a6'], + ['af6f8cb-c57d-11e1-9b21-0800200c9a66'], + ['af6f8cb0c57d11e19b210800200c9a66'], + ['ff6f8cb0-c57da-51e1-9b21-0800200c9a66'], + ]; + } + + public function testMatch(): void + { + $this->assertSame('bar', PatternMatcher::match('/bar/', 'foo bar')); + $this->assertSame('bar', PatternMatcher::match('/foo (.*)/', 'foo bar')); + $this->assertEmpty(PatternMatcher::match('/nothing/', 'foo bar')); + + $this->assertEquals(['bar', 'bar'], PatternMatcher::matchAll('/bar/', 'bar foo bar')->all()); + + $this->assertEquals(['un', 'ly'], PatternMatcher::matchAll('/f(\w*)/', 'bar fun bar fly')->all()); + $this->assertEmpty(PatternMatcher::matchAll('/nothing/', 'bar fun bar fly')); + + $this->assertEmpty(PatternMatcher::match('/pattern/', '')); + $this->assertEmpty(PatternMatcher::matchAll('/pattern/', '')); + } + + public function testIsMatch() + { + $this->assertTrue(PatternMatcher::isMatch('/.*,.*!/', 'Hello, Laravel!')); + $this->assertTrue(PatternMatcher::isMatch('/^.*$(.*)/', 'Hello, Laravel!')); + $this->assertTrue(PatternMatcher::isMatch('/laravel/i', 'Hello, Laravel!')); + $this->assertTrue(PatternMatcher::isMatch('/^(.*(.*(.*)))/', 'Hello, Laravel!')); + + $this->assertFalse(PatternMatcher::isMatch('/H.o/', 'Hello, Laravel!')); + $this->assertFalse(PatternMatcher::isMatch('/^laravel!/i', 'Hello, Laravel!')); + $this->assertFalse(PatternMatcher::isMatch('/laravel!(.*)/', 'Hello, Laravel!')); + $this->assertFalse(PatternMatcher::isMatch('/^[a-zA-Z,!]+$/', 'Hello, Laravel!')); + + $this->assertTrue(PatternMatcher::isMatch(['/.*,.*!/', '/H.o/'], 'Hello, Laravel!')); + $this->assertTrue(PatternMatcher::isMatch(['/^laravel!/i', '/^.*$(.*)/'], 'Hello, Laravel!')); + $this->assertTrue(PatternMatcher::isMatch(['/laravel/i', '/laravel!(.*)/'], 'Hello, Laravel!')); + $this->assertTrue(PatternMatcher::isMatch(['/^[a-zA-Z,!]+$/', '/^(.*(.*(.*)))/'], 'Hello, Laravel!')); + } +} \ No newline at end of file diff --git a/tests/Support/SupportPluralizerTest.php b/tests/Support/SupportPluralizerTest.php index d528a6006759..75fb7a500607 100755 --- a/tests/Support/SupportPluralizerTest.php +++ b/tests/Support/SupportPluralizerTest.php @@ -2,56 +2,56 @@ namespace Illuminate\Tests\Support; -use Illuminate\Support\Str; +use Illuminate\Support\StrGrammar; use PHPUnit\Framework\TestCase; class SupportPluralizerTest extends TestCase { public function testBasicSingular() { - $this->assertSame('child', Str::singular('children')); + $this->assertSame('child', StrGrammar::singular('children')); } public function testBasicPlural() { - $this->assertSame('children', Str::plural('child')); - $this->assertSame('cod', Str::plural('cod')); - $this->assertSame('The words', Str::plural('The word')); - $this->assertSame('Bouquetés', Str::plural('Bouqueté')); + $this->assertSame('children', StrGrammar::plural('child')); + $this->assertSame('cod', StrGrammar::plural('cod')); + $this->assertSame('The words', StrGrammar::plural('The word')); + $this->assertSame('Bouquetés', StrGrammar::plural('Bouqueté')); } public function testCaseSensitiveSingularUsage() { - $this->assertSame('Child', Str::singular('Children')); - $this->assertSame('CHILD', Str::singular('CHILDREN')); - $this->assertSame('Test', Str::singular('Tests')); + $this->assertSame('Child', StrGrammar::singular('Children')); + $this->assertSame('CHILD', StrGrammar::singular('CHILDREN')); + $this->assertSame('Test', StrGrammar::singular('Tests')); } public function testCaseSensitiveSingularPlural() { - $this->assertSame('Children', Str::plural('Child')); - $this->assertSame('CHILDREN', Str::plural('CHILD')); - $this->assertSame('Tests', Str::plural('Test')); - $this->assertSame('children', Str::plural('cHiLd')); + $this->assertSame('Children', StrGrammar::plural('Child')); + $this->assertSame('CHILDREN', StrGrammar::plural('CHILD')); + $this->assertSame('Tests', StrGrammar::plural('Test')); + $this->assertSame('children', StrGrammar::plural('cHiLd')); } public function testIfEndOfWordPlural() { - $this->assertSame('VortexFields', Str::plural('VortexField')); - $this->assertSame('MatrixFields', Str::plural('MatrixField')); - $this->assertSame('IndexFields', Str::plural('IndexField')); - $this->assertSame('VertexFields', Str::plural('VertexField')); + $this->assertSame('VortexFields', StrGrammar::plural('VortexField')); + $this->assertSame('MatrixFields', StrGrammar::plural('MatrixField')); + $this->assertSame('IndexFields', StrGrammar::plural('IndexField')); + $this->assertSame('VertexFields', StrGrammar::plural('VertexField')); - // This is expected behavior, use "Str::pluralStudly" instead. - $this->assertSame('RealHumen', Str::plural('RealHuman')); + // This is expected behavior, use "StrGrammar::pluralStudly" instead. + $this->assertSame('RealHumen', StrGrammar::plural('RealHuman')); } public function testPluralWithNegativeCount() { - $this->assertSame('test', Str::plural('test', 1)); - $this->assertSame('tests', Str::plural('test', 2)); - $this->assertSame('test', Str::plural('test', -1)); - $this->assertSame('tests', Str::plural('test', -2)); + $this->assertSame('test', StrGrammar::plural('test', 1)); + $this->assertSame('tests', StrGrammar::plural('test', 2)); + $this->assertSame('test', StrGrammar::plural('test', -1)); + $this->assertSame('tests', StrGrammar::plural('test', -2)); } public function testPluralStudly() @@ -72,31 +72,31 @@ public function testPluralStudlyWithCount() public function testPluralNotAppliedForStringEndingWithNonAlphanumericCharacter() { - $this->assertSame('Alien.', Str::plural('Alien.')); - $this->assertSame('Alien!', Str::plural('Alien!')); - $this->assertSame('Alien ', Str::plural('Alien ')); - $this->assertSame('50%', Str::plural('50%')); + $this->assertSame('Alien.', StrGrammar::plural('Alien.')); + $this->assertSame('Alien!', StrGrammar::plural('Alien!')); + $this->assertSame('Alien ', StrGrammar::plural('Alien ')); + $this->assertSame('50%', StrGrammar::plural('50%')); } public function testPluralAppliedForStringEndingWithNumericCharacter() { - $this->assertSame('User1s', Str::plural('User1')); - $this->assertSame('User2s', Str::plural('User2')); - $this->assertSame('User3s', Str::plural('User3')); + $this->assertSame('User1s', StrGrammar::plural('User1')); + $this->assertSame('User2s', StrGrammar::plural('User2')); + $this->assertSame('User3s', StrGrammar::plural('User3')); } public function testPluralSupportsArrays() { - $this->assertSame('users', Str::plural('user', [])); - $this->assertSame('user', Str::plural('user', ['one'])); - $this->assertSame('users', Str::plural('user', ['one', 'two'])); + $this->assertSame('users', StrGrammar::plural('user', [])); + $this->assertSame('user', StrGrammar::plural('user', ['one'])); + $this->assertSame('users', StrGrammar::plural('user', ['one', 'two'])); } public function testPluralSupportsCollections() { - $this->assertSame('users', Str::plural('user', collect())); - $this->assertSame('user', Str::plural('user', collect(['one']))); - $this->assertSame('users', Str::plural('user', collect(['one', 'two']))); + $this->assertSame('users', StrGrammar::plural('user', collect())); + $this->assertSame('user', StrGrammar::plural('user', collect(['one']))); + $this->assertSame('users', StrGrammar::plural('user', collect(['one', 'two']))); } public function testPluralStudlySupportsArrays() @@ -115,6 +115,6 @@ public function testPluralStudlySupportsCollections() private function assertPluralStudly($expected, $value, $count = 2) { - $this->assertSame($expected, Str::pluralStudly($value, $count)); + $this->assertSame($expected, StrGrammar::pluralStudly($value, $count)); } } diff --git a/tests/Support/SupportReplacerTest.php b/tests/Support/SupportReplacerTest.php new file mode 100644 index 000000000000..a4f6cacc0dcf --- /dev/null +++ b/tests/Support/SupportReplacerTest.php @@ -0,0 +1,105 @@ +assertSame('5551234567', Replacer::numbers('(555) 123-4567')); + $this->assertSame('443', Replacer::numbers('L4r4v3l!')); + $this->assertSame('', Replacer::numbers('Laravel!')); + + $arrayValue = ['(555) 123-4567', 'L4r4v3l', 'Laravel!']; + $arrayExpected = ['5551234567', '443', '']; + $this->assertSame($arrayExpected, Replacer::numbers($arrayValue)); + } + + public function testReplace() + { + $this->assertSame('foo bar laravel', Replacer::replace('baz', 'laravel', 'foo bar baz')); + $this->assertSame('foo bar laravel', Replacer::replace('baz', 'laravel', 'foo bar Baz', false)); + $this->assertSame('foo bar baz 8.x', Replacer::replace('?', '8.x', 'foo bar baz ?')); + $this->assertSame('foo bar baz 8.x', Replacer::replace('x', '8.x', 'foo bar baz X', false)); + $this->assertSame('foo/bar/baz', Replacer::replace(' ', '/', 'foo bar baz')); + $this->assertSame('foo bar baz', Replacer::replace(['?1', '?2', '?3'], ['foo', 'bar', 'baz'], '?1 ?2 ?3')); + $this->assertSame(['foo', 'bar', 'baz'], Replacer::replace(collect(['?1', '?2', '?3']), collect(['foo', 'bar', 'baz']), collect(['?1', '?2', '?3']))); + } + + public function testReplaceArray() + { + $this->assertSame('foo/bar/baz', Replacer::replaceArray('?', ['foo', 'bar', 'baz'], '?/?/?')); + $this->assertSame('foo/bar/baz/?', Replacer::replaceArray('?', ['foo', 'bar', 'baz'], '?/?/?/?')); + $this->assertSame('foo/bar', Replacer::replaceArray('?', ['foo', 'bar', 'baz'], '?/?')); + $this->assertSame('?/?/?', Replacer::replaceArray('x', ['foo', 'bar', 'baz'], '?/?/?')); + // Ensure recursive replacements are avoided + $this->assertSame('foo?/bar/baz', Replacer::replaceArray('?', ['foo?', 'bar', 'baz'], '?/?/?')); + // Test for associative array support + $this->assertSame('foo/bar', Replacer::replaceArray('?', [1 => 'foo', 2 => 'bar'], '?/?')); + $this->assertSame('foo/bar', Replacer::replaceArray('?', ['x' => 'foo', 'y' => 'bar'], '?/?')); + // Test does not crash on bad input + $this->assertSame('?', Replacer::replaceArray('?', [(object) ['foo' => 'bar']], '?')); + } + + public function testReplaceFirst() + { + $this->assertSame('fooqux foobar', Replacer::replaceFirst('bar', 'qux', 'foobar foobar')); + $this->assertSame('foo/qux? foo/bar?', Replacer::replaceFirst('bar?', 'qux?', 'foo/bar? foo/bar?')); + $this->assertSame('foo foobar', Replacer::replaceFirst('bar', '', 'foobar foobar')); + $this->assertSame('foobar foobar', Replacer::replaceFirst('xxx', 'yyy', 'foobar foobar')); + $this->assertSame('foobar foobar', Replacer::replaceFirst('', 'yyy', 'foobar foobar')); + $this->assertSame('1', Replacer::replaceFirst(0, '1', '0')); + // Test for multibyte string support + $this->assertSame('Jxxxnköping Malmö', Replacer::replaceFirst('ö', 'xxx', 'Jönköping Malmö')); + $this->assertSame('Jönköping Malmö', Replacer::replaceFirst('', 'yyy', 'Jönköping Malmö')); + } + + public function testReplaceStart() + { + $this->assertSame('foobar foobar', Replacer::replaceStart('bar', 'qux', 'foobar foobar')); + $this->assertSame('foo/bar? foo/bar?', Replacer::replaceStart('bar?', 'qux?', 'foo/bar? foo/bar?')); + $this->assertSame('quxbar foobar', Replacer::replaceStart('foo', 'qux', 'foobar foobar')); + $this->assertSame('qux? foo/bar?', Replacer::replaceStart('foo/bar?', 'qux?', 'foo/bar? foo/bar?')); + $this->assertSame('bar foobar', Replacer::replaceStart('foo', '', 'foobar foobar')); + $this->assertSame('1', Replacer::replaceStart(0, '1', '0')); + // Test for multibyte string support + $this->assertSame('xxxnköping Malmö', Replacer::replaceStart('Jö', 'xxx', 'Jönköping Malmö')); + $this->assertSame('Jönköping Malmö', Replacer::replaceStart('', 'yyy', 'Jönköping Malmö')); + } + + public function testReplaceLast() + { + $this->assertSame('foobar fooqux', Replacer::replaceLast('bar', 'qux', 'foobar foobar')); + $this->assertSame('foo/bar? foo/qux?', Replacer::replaceLast('bar?', 'qux?', 'foo/bar? foo/bar?')); + $this->assertSame('foobar foo', Replacer::replaceLast('bar', '', 'foobar foobar')); + $this->assertSame('foobar foobar', Replacer::replaceLast('xxx', 'yyy', 'foobar foobar')); + $this->assertSame('foobar foobar', Replacer::replaceLast('', 'yyy', 'foobar foobar')); + // Test for multibyte string support + $this->assertSame('Malmö Jönkxxxping', Replacer::replaceLast('ö', 'xxx', 'Malmö Jönköping')); + $this->assertSame('Malmö Jönköping', Replacer::replaceLast('', 'yyy', 'Malmö Jönköping')); + } + + public function testReplaceEnd() + { + $this->assertSame('foobar fooqux', Replacer::replaceEnd('bar', 'qux', 'foobar foobar')); + $this->assertSame('foo/bar? foo/qux?', Replacer::replaceEnd('bar?', 'qux?', 'foo/bar? foo/bar?')); + $this->assertSame('foobar foo', Replacer::replaceEnd('bar', '', 'foobar foobar')); + $this->assertSame('foobar foobar', Replacer::replaceEnd('xxx', 'yyy', 'foobar foobar')); + $this->assertSame('foobar foobar', Replacer::replaceEnd('', 'yyy', 'foobar foobar')); + $this->assertSame('fooxxx foobar', Replacer::replaceEnd('xxx', 'yyy', 'fooxxx foobar')); + + // // Test for multibyte string support + $this->assertSame('Malmö Jönköping', Replacer::replaceEnd('ö', 'xxx', 'Malmö Jönköping')); + $this->assertSame('Malmö Jönkyyy', Replacer::replaceEnd('öping', 'yyy', 'Malmö Jönköping')); + } + + public function testSubstrReplace() + { + $this->assertSame('12:00', Replacer::substrReplace('1200', ':', 2, 0)); + $this->assertSame('The Laravel Framework', Replacer::substrReplace('The Framework', 'Laravel ', 4, 0)); + $this->assertSame('Laravel – The PHP Framework for Web Artisans', Replacer::substrReplace('Laravel Framework', '– The PHP Framework for Web Artisans', 8)); + } +} \ No newline at end of file diff --git a/tests/Support/SupportSanitizerTest.php b/tests/Support/SupportSanitizerTest.php new file mode 100644 index 000000000000..0c1c1853a307 --- /dev/null +++ b/tests/Support/SupportSanitizerTest.php @@ -0,0 +1,149 @@ +assertSame('Fbar', Sanitizer::remove('o', 'Foobar')); + $this->assertSame('Foo', Sanitizer::remove('bar', 'Foobar')); + $this->assertSame('oobar', Sanitizer::remove('F', 'Foobar')); + $this->assertSame('Foobar', Sanitizer::remove('f', 'Foobar')); + $this->assertSame('oobar', Sanitizer::remove('f', 'Foobar', false)); + + $this->assertSame('Fbr', Sanitizer::remove(['o', 'a'], 'Foobar')); + $this->assertSame('Fooar', Sanitizer::remove(['f', 'b'], 'Foobar')); + $this->assertSame('ooar', Sanitizer::remove(['f', 'b'], 'Foobar', false)); + $this->assertSame('Foobar', Sanitizer::remove(['f', '|'], 'Foo|bar')); + } + + public function testTrim() + { + $this->assertSame('foo bar', Sanitizer::trim(' foo bar ')); + $this->assertSame('foo bar', Sanitizer::trim('foo bar ')); + $this->assertSame('foo bar', Sanitizer::trim(' foo bar')); + $this->assertSame('foo bar', Sanitizer::trim('foo bar')); + $this->assertSame(' foo bar ', Sanitizer::trim(' foo bar ', '')); + $this->assertSame('foo bar', Sanitizer::trim(' foo bar ', ' ')); + $this->assertSame('foo bar', Sanitizer::trim('-foo bar_', '-_')); + + $this->assertSame('foo bar', Sanitizer::trim(' foo bar ')); + + $this->assertSame('123', Sanitizer::trim('  123   ')); + $this->assertSame('だ', Sanitizer::trim('だ')); + $this->assertSame('ム', Sanitizer::trim('ム')); + $this->assertSame('だ', Sanitizer::trim('  だ   ')); + $this->assertSame('ム', Sanitizer::trim('  ム   ')); + + $this->assertSame( + 'foo bar', + Sanitizer::trim(' + foo bar + ') + ); + $this->assertSame( + 'foo + bar', + Sanitizer::trim(' + foo + bar + ') + ); + + $this->assertSame("\xE9", Sanitizer::trim(" \xE9 ")); + + $trimDefaultChars = [' ', "\n", "\r", "\t", "\v", "\0"]; + + foreach ($trimDefaultChars as $char) { + $this->assertSame('', Sanitizer::trim(" {$char} ")); + $this->assertSame(trim(" {$char} "), Sanitizer::trim(" {$char} ")); + + $this->assertSame('foo bar', Sanitizer::trim("{$char} foo bar {$char}")); + $this->assertSame(trim("{$char} foo bar {$char}"), Sanitizer::trim("{$char} foo bar {$char}")); + } + } + + public function testLtrim() + { + $this->assertSame('foo bar ', Sanitizer::ltrim(' foo bar ')); + + $this->assertSame('123   ', Sanitizer::ltrim('  123   ')); + $this->assertSame('だ', Sanitizer::ltrim('だ')); + $this->assertSame('ム', Sanitizer::ltrim('ム')); + $this->assertSame('だ   ', Sanitizer::ltrim('  だ   ')); + $this->assertSame('ム   ', Sanitizer::ltrim('  ム   ')); + + $this->assertSame( + 'foo bar + ', + Sanitizer::ltrim(' + foo bar + ') + ); + $this->assertSame("\xE9 ", Sanitizer::ltrim(" \xE9 ")); + + $ltrimDefaultChars = [' ', "\n", "\r", "\t", "\v", "\0"]; + + foreach ($ltrimDefaultChars as $char) { + $this->assertSame('', Sanitizer::ltrim(" {$char} ")); + $this->assertSame(ltrim(" {$char} "), Sanitizer::ltrim(" {$char} ")); + + $this->assertSame("foo bar {$char}", Sanitizer::ltrim("{$char} foo bar {$char}")); + $this->assertSame(ltrim("{$char} foo bar {$char}"), Sanitizer::ltrim("{$char} foo bar {$char}")); + } + } + + public function testRtrim() + { + $this->assertSame(' foo bar', Sanitizer::rtrim(' foo bar ')); + + $this->assertSame('  123', Sanitizer::rtrim('  123   ')); + $this->assertSame('だ', Sanitizer::rtrim('だ')); + $this->assertSame('ム', Sanitizer::rtrim('ム')); + $this->assertSame('  だ', Sanitizer::rtrim('  だ   ')); + $this->assertSame('  ム', Sanitizer::rtrim('  ム   ')); + + $this->assertSame( + ' + foo bar', + Sanitizer::rtrim(' + foo bar + ') + ); + + $this->assertSame(" \xE9", Sanitizer::rtrim(" \xE9 ")); + + $rtrimDefaultChars = [' ', "\n", "\r", "\t", "\v", "\0"]; + + foreach ($rtrimDefaultChars as $char) { + $this->assertSame('', Sanitizer::rtrim(" {$char} ")); + $this->assertSame(rtrim(" {$char} "), Sanitizer::rtrim(" {$char} ")); + + $this->assertSame("{$char} foo bar", Sanitizer::rtrim("{$char} foo bar {$char}")); + $this->assertSame(rtrim("{$char} foo bar {$char}"), Sanitizer::rtrim("{$char} foo bar {$char}")); + } + } + + public function testSquish() + { + $this->assertSame('laravel php framework', Sanitizer::squish(' laravel php framework ')); + $this->assertSame('laravel php framework', Sanitizer::squish("laravel\t\tphp\n\nframework")); + $this->assertSame('laravel php framework', Sanitizer::squish(' + laravel + php + framework + ')); + $this->assertSame('laravel php framework', Sanitizer::squish('   laravel   php   framework   ')); + $this->assertSame('123', Sanitizer::squish('  123   ')); + $this->assertSame('だ', Sanitizer::squish('だ')); + $this->assertSame('ム', Sanitizer::squish('ム')); + $this->assertSame('だ', Sanitizer::squish('  だ   ')); + $this->assertSame('ム', Sanitizer::squish('  ム   ')); + $this->assertSame('laravel php framework', Sanitizer::squish('laravelㅤㅤㅤphpㅤframework')); + $this->assertSame('laravel php framework', Sanitizer::squish('laravelᅠᅠᅠᅠᅠᅠᅠᅠᅠᅠphpᅠᅠframework')); + } +} \ No newline at end of file diff --git a/tests/Support/SupportStrTest.php b/tests/Support/SupportStrTest.php index 47d45b5e3dab..c854f31f0e41 100755 --- a/tests/Support/SupportStrTest.php +++ b/tests/Support/SupportStrTest.php @@ -3,6 +3,7 @@ namespace Illuminate\Tests\Support; use Exception; +use Illuminate\Support\PatternMatcher; use Illuminate\Support\Str; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; @@ -35,53 +36,6 @@ public function testStringTrimmedOnlyWhereNecessary() $this->assertSame(' Taylor...', Str::words(' Taylor Otwell ', 1)); } - public function testStringTitle() - { - $this->assertSame('Jefferson Costella', Str::title('jefferson costella')); - $this->assertSame('Jefferson Costella', Str::title('jefFErson coSTella')); - - $this->assertSame('', Str::title('')); - $this->assertSame('123 Laravel', Str::title('123 laravel')); - $this->assertSame('❤Laravel', Str::title('❤laravel')); - $this->assertSame('Laravel ❤', Str::title('laravel ❤')); - $this->assertSame('Laravel123', Str::title('laravel123')); - $this->assertSame('Laravel123', Str::title('Laravel123')); - - $longString = 'lorem ipsum '.str_repeat('dolor sit amet ', 1000); - $expectedResult = 'Lorem Ipsum Dolor Sit Amet '.str_repeat('Dolor Sit Amet ', 999); - $this->assertSame($expectedResult, Str::title($longString)); - } - - public function testStringHeadline() - { - $this->assertSame('Jefferson Costella', Str::headline('jefferson costella')); - $this->assertSame('Jefferson Costella', Str::headline('jefFErson coSTella')); - $this->assertSame('Jefferson Costella Uses Laravel', Str::headline('jefferson_costella uses-_Laravel')); - $this->assertSame('Jefferson Costella Uses Laravel', Str::headline('jefferson_costella uses__Laravel')); - - $this->assertSame('Laravel P H P Framework', Str::headline('laravel_p_h_p_framework')); - $this->assertSame('Laravel P H P Framework', Str::headline('laravel _p _h _p _framework')); - $this->assertSame('Laravel Php Framework', Str::headline('laravel_php_framework')); - $this->assertSame('Laravel Ph P Framework', Str::headline('laravel-phP-framework')); - $this->assertSame('Laravel Php Framework', Str::headline('laravel -_- php -_- framework ')); - - $this->assertSame('Foo Bar', Str::headline('fooBar')); - $this->assertSame('Foo Bar', Str::headline('foo_bar')); - $this->assertSame('Foo Bar Baz', Str::headline('foo-barBaz')); - $this->assertSame('Foo Bar Baz', Str::headline('foo-bar_baz')); - - $this->assertSame('Öffentliche Überraschungen', Str::headline('öffentliche-überraschungen')); - $this->assertSame('Öffentliche Überraschungen', Str::headline('-_öffentliche_überraschungen_-')); - $this->assertSame('Öffentliche Überraschungen', Str::headline('-öffentliche überraschungen')); - - $this->assertSame('Sind Öde Und So', Str::headline('sindÖdeUndSo')); - - $this->assertSame('Orwell 1984', Str::headline('orwell 1984')); - $this->assertSame('Orwell 1984', Str::headline('orwell 1984')); - $this->assertSame('Orwell 1984', Str::headline('-orwell-1984 -')); - $this->assertSame('Orwell 1984', Str::headline(' orwell_- 1984 ')); - } - public function testStringApa() { $this->assertSame('Tom and Jerry', Str::apa('tom and jerry')); @@ -377,29 +331,6 @@ public function testStrContainsAll($haystack, $needles, $expected, $ignoreCase = $this->assertEquals($expected, Str::containsAll($haystack, $needles, $ignoreCase)); } - public function testConvertCase() - { - // Upper Case Conversion - $this->assertSame('HELLO', Str::convertCase('hello', MB_CASE_UPPER)); - $this->assertSame('WORLD', Str::convertCase('WORLD', MB_CASE_UPPER)); - - // Lower Case Conversion - $this->assertSame('hello', Str::convertCase('HELLO', MB_CASE_LOWER)); - $this->assertSame('world', Str::convertCase('WORLD', MB_CASE_LOWER)); - - // Case Folding - $this->assertSame('hello', Str::convertCase('HeLLo', MB_CASE_FOLD)); - $this->assertSame('world', Str::convertCase('WoRLD', MB_CASE_FOLD)); - - // Multi-byte String - $this->assertSame('ÜÖÄ', Str::convertCase('üöä', MB_CASE_UPPER, 'UTF-8')); - $this->assertSame('üöä', Str::convertCase('ÜÖÄ', MB_CASE_LOWER, 'UTF-8')); - - // Unsupported Mode - $this->expectException(\ValueError::class); - Str::convertCase('Hello', -1); - } - public function testDedup() { $this->assertSame(' laravel php framework ', Str::deduplicate(' laravel php framework ')); @@ -448,21 +379,6 @@ public function testStrStart() $this->assertSame('/test/string', Str::start('//test/string', '/')); } - public function testFlushCache() - { - $reflection = new ReflectionClass(Str::class); - $property = $reflection->getProperty('snakeCache'); - - Str::flushCache(); - $this->assertEmpty($property->getValue()); - - Str::snake('Taylor Otwell'); - $this->assertNotEmpty($property->getValue()); - - Str::flushCache(); - $this->assertEmpty($property->getValue()); - } - public function testFinish() { $this->assertSame('abbc', Str::finish('ab', 'bc')); @@ -485,111 +401,6 @@ public function testUnwrap() $this->assertEquals('some: "json"', Str::unwrap('{some: "json"}', '{', '}')); } - public function testIs() - { - $this->assertTrue(Str::is('/', '/')); - $this->assertFalse(Str::is('/', ' /')); - $this->assertFalse(Str::is('/', '/a')); - $this->assertTrue(Str::is('foo/*', 'foo/bar/baz')); - - $this->assertTrue(Str::is('*@*', 'App\Class@method')); - $this->assertTrue(Str::is('*@*', 'app\Class@')); - $this->assertTrue(Str::is('*@*', '@method')); - - // is case sensitive - $this->assertFalse(Str::is('*BAZ*', 'foo/bar/baz')); - $this->assertFalse(Str::is('*FOO*', 'foo/bar/baz')); - $this->assertFalse(Str::is('A', 'a')); - - // Accepts array of patterns - $this->assertTrue(Str::is(['a*', 'b*'], 'a/')); - $this->assertTrue(Str::is(['a*', 'b*'], 'b/')); - $this->assertFalse(Str::is(['a*', 'b*'], 'f/')); - - // numeric values and patterns - $this->assertFalse(Str::is(['a*', 'b*'], 123)); - $this->assertTrue(Str::is(['*2*', 'b*'], 11211)); - - $this->assertTrue(Str::is('*/foo', 'blah/baz/foo')); - - $valueObject = new StringableObjectStub('foo/bar/baz'); - $patternObject = new StringableObjectStub('foo/*'); - - $this->assertTrue(Str::is('foo/bar/baz', $valueObject)); - $this->assertTrue(Str::is($patternObject, $valueObject)); - - // empty patterns - $this->assertFalse(Str::is([], 'test')); - - $this->assertFalse(Str::is('', 0)); - $this->assertFalse(Str::is([null], 0)); - $this->assertTrue(Str::is([null], null)); - } - - public function testIsWithMultilineStrings() - { - $this->assertFalse(Str::is('/', "/\n")); - $this->assertTrue(Str::is('/*', "/\n")); - $this->assertTrue(Str::is('*/*', "/\n")); - $this->assertTrue(Str::is('*/*', "\n/\n")); - - $this->assertTrue(Str::is('*', "\n")); - $this->assertTrue(Str::is('*', "\n\n")); - $this->assertFalse(Str::is('', "\n")); - $this->assertFalse(Str::is('', "\n\n")); - - $multilineValue = <<<'VALUE' - assertTrue(Str::is($multilineValue, $multilineValue)); - $this->assertTrue(Str::is('*', $multilineValue)); - $this->assertTrue(Str::is("*namespace Illuminate\Tests\*", $multilineValue)); - $this->assertFalse(Str::is("namespace Illuminate\Tests\*", $multilineValue)); - $this->assertFalse(Str::is("*namespace Illuminate\Tests", $multilineValue)); - $this->assertTrue(Str::is('assertTrue(Str::is("assertFalse(Str::is('use Exception;', $multilineValue)); - $this->assertFalse(Str::is('use Exception;*', $multilineValue)); - $this->assertTrue(Str::is('*use Exception;', $multilineValue)); - - $this->assertTrue(Str::is("assertTrue(Str::is(<<<'PATTERN' - assertTrue(Str::is(<<<'PATTERN' - assertTrue(Str::isUrl('https://laravel.com')); - $this->assertFalse(Str::isUrl('invalid url')); - } - - #[DataProvider('validUuidList')] - public function testIsUuidWithValidUuid($uuid) - { - $this->assertTrue(Str::isUuid($uuid)); - } - - #[DataProvider('invalidUuidList')] - public function testIsUuidWithInvalidUuid($uuid) - { - $this->assertFalse(Str::isUuid($uuid)); - } - public function testIsJson() { $this->assertTrue(Str::isJson('1')); @@ -608,44 +419,6 @@ public function testIsJson() $this->assertFalse(Str::isJson([])); } - public function testIsMatch() - { - $this->assertTrue(Str::isMatch('/.*,.*!/', 'Hello, Laravel!')); - $this->assertTrue(Str::isMatch('/^.*$(.*)/', 'Hello, Laravel!')); - $this->assertTrue(Str::isMatch('/laravel/i', 'Hello, Laravel!')); - $this->assertTrue(Str::isMatch('/^(.*(.*(.*)))/', 'Hello, Laravel!')); - - $this->assertFalse(Str::isMatch('/H.o/', 'Hello, Laravel!')); - $this->assertFalse(Str::isMatch('/^laravel!/i', 'Hello, Laravel!')); - $this->assertFalse(Str::isMatch('/laravel!(.*)/', 'Hello, Laravel!')); - $this->assertFalse(Str::isMatch('/^[a-zA-Z,!]+$/', 'Hello, Laravel!')); - - $this->assertTrue(Str::isMatch(['/.*,.*!/', '/H.o/'], 'Hello, Laravel!')); - $this->assertTrue(Str::isMatch(['/^laravel!/i', '/^.*$(.*)/'], 'Hello, Laravel!')); - $this->assertTrue(Str::isMatch(['/laravel/i', '/laravel!(.*)/'], 'Hello, Laravel!')); - $this->assertTrue(Str::isMatch(['/^[a-zA-Z,!]+$/', '/^(.*(.*(.*)))/'], 'Hello, Laravel!')); - } - - public function testKebab() - { - $this->assertSame('laravel-php-framework', Str::kebab('LaravelPhpFramework')); - $this->assertSame('laravel-php-framework', Str::kebab('Laravel Php Framework')); - $this->assertSame('laravel❤-php-framework', Str::kebab('Laravel ❤ Php Framework')); - $this->assertSame('', Str::kebab('')); - } - - public function testLower() - { - $this->assertSame('foo bar baz', Str::lower('FOO BAR BAZ')); - $this->assertSame('foo bar baz', Str::lower('fOo Bar bAz')); - } - - public function testUpper() - { - $this->assertSame('FOO BAR BAZ', Str::upper('foo bar baz')); - $this->assertSame('FOO BAR BAZ', Str::upper('foO bAr BaZ')); - } - public function testLimit() { $this->assertSame('Laravel is...', Str::limit('Laravel is a free, open source PHP web application framework.', 10)); @@ -674,179 +447,6 @@ public function testLength() $this->assertEquals(11, Str::length('foo bar baz', 'UTF-8')); } - public function testNumbers() - { - $this->assertSame('5551234567', Str::numbers('(555) 123-4567')); - $this->assertSame('443', Str::numbers('L4r4v3l!')); - $this->assertSame('', Str::numbers('Laravel!')); - - $arrayValue = ['(555) 123-4567', 'L4r4v3l', 'Laravel!']; - $arrayExpected = ['5551234567', '443', '']; - $this->assertSame($arrayExpected, Str::numbers($arrayValue)); - } - - public function testRandom() - { - $this->assertEquals(16, strlen(Str::random())); - $randomInteger = random_int(1, 100); - $this->assertEquals($randomInteger, strlen(Str::random($randomInteger))); - $this->assertIsString(Str::random()); - } - - public function testWhetherTheNumberOfGeneratedCharactersIsEquallyDistributed() - { - $results = []; - // take 6.200.000 samples, because there are 62 different characters - for ($i = 0; $i < 620000; $i++) { - $random = Str::random(1); - $results[$random] = ($results[$random] ?? 0) + 1; - } - - // each character should occur 100.000 times with a variance of 5%. - foreach ($results as $result) { - $this->assertEqualsWithDelta(10000, $result, 500); - } - } - - public function testRandomStringFactoryCanBeSet() - { - Str::createRandomStringsUsing(fn ($length) => 'length:'.$length); - - $this->assertSame('length:7', Str::random(7)); - $this->assertSame('length:7', Str::random(7)); - - Str::createRandomStringsNormally(); - - $this->assertNotSame('length:7', Str::random()); - } - - public function testItCanSpecifyASequenceOfRandomStringsToUtilise() - { - Str::createRandomStringsUsingSequence([ - 0 => 'x', - // 1 => just generate a random one here... - 2 => 'y', - 3 => 'z', - // ... => continue to generate random strings... - ]); - - $this->assertSame('x', Str::random()); - $this->assertSame(16, mb_strlen(Str::random())); - $this->assertSame('y', Str::random()); - $this->assertSame('z', Str::random()); - $this->assertSame(16, mb_strlen(Str::random())); - $this->assertSame(16, mb_strlen(Str::random())); - - Str::createRandomStringsNormally(); - } - - public function testItCanSpecifyAFallbackForARandomStringSequence() - { - Str::createRandomStringsUsingSequence([Str::random(), Str::random()], fn () => throw new Exception('Out of random strings.')); - Str::random(); - Str::random(); - - try { - $this->expectExceptionMessage('Out of random strings.'); - Str::random(); - $this->fail(); - } finally { - Str::createRandomStringsNormally(); - } - } - - public function testReplace() - { - $this->assertSame('foo bar laravel', Str::replace('baz', 'laravel', 'foo bar baz')); - $this->assertSame('foo bar laravel', Str::replace('baz', 'laravel', 'foo bar Baz', false)); - $this->assertSame('foo bar baz 8.x', Str::replace('?', '8.x', 'foo bar baz ?')); - $this->assertSame('foo bar baz 8.x', Str::replace('x', '8.x', 'foo bar baz X', false)); - $this->assertSame('foo/bar/baz', Str::replace(' ', '/', 'foo bar baz')); - $this->assertSame('foo bar baz', Str::replace(['?1', '?2', '?3'], ['foo', 'bar', 'baz'], '?1 ?2 ?3')); - $this->assertSame(['foo', 'bar', 'baz'], Str::replace(collect(['?1', '?2', '?3']), collect(['foo', 'bar', 'baz']), collect(['?1', '?2', '?3']))); - } - - public function testReplaceArray() - { - $this->assertSame('foo/bar/baz', Str::replaceArray('?', ['foo', 'bar', 'baz'], '?/?/?')); - $this->assertSame('foo/bar/baz/?', Str::replaceArray('?', ['foo', 'bar', 'baz'], '?/?/?/?')); - $this->assertSame('foo/bar', Str::replaceArray('?', ['foo', 'bar', 'baz'], '?/?')); - $this->assertSame('?/?/?', Str::replaceArray('x', ['foo', 'bar', 'baz'], '?/?/?')); - // Ensure recursive replacements are avoided - $this->assertSame('foo?/bar/baz', Str::replaceArray('?', ['foo?', 'bar', 'baz'], '?/?/?')); - // Test for associative array support - $this->assertSame('foo/bar', Str::replaceArray('?', [1 => 'foo', 2 => 'bar'], '?/?')); - $this->assertSame('foo/bar', Str::replaceArray('?', ['x' => 'foo', 'y' => 'bar'], '?/?')); - // Test does not crash on bad input - $this->assertSame('?', Str::replaceArray('?', [(object) ['foo' => 'bar']], '?')); - } - - public function testReplaceFirst() - { - $this->assertSame('fooqux foobar', Str::replaceFirst('bar', 'qux', 'foobar foobar')); - $this->assertSame('foo/qux? foo/bar?', Str::replaceFirst('bar?', 'qux?', 'foo/bar? foo/bar?')); - $this->assertSame('foo foobar', Str::replaceFirst('bar', '', 'foobar foobar')); - $this->assertSame('foobar foobar', Str::replaceFirst('xxx', 'yyy', 'foobar foobar')); - $this->assertSame('foobar foobar', Str::replaceFirst('', 'yyy', 'foobar foobar')); - $this->assertSame('1', Str::replaceFirst(0, '1', '0')); - // Test for multibyte string support - $this->assertSame('Jxxxnköping Malmö', Str::replaceFirst('ö', 'xxx', 'Jönköping Malmö')); - $this->assertSame('Jönköping Malmö', Str::replaceFirst('', 'yyy', 'Jönköping Malmö')); - } - - public function testReplaceStart() - { - $this->assertSame('foobar foobar', Str::replaceStart('bar', 'qux', 'foobar foobar')); - $this->assertSame('foo/bar? foo/bar?', Str::replaceStart('bar?', 'qux?', 'foo/bar? foo/bar?')); - $this->assertSame('quxbar foobar', Str::replaceStart('foo', 'qux', 'foobar foobar')); - $this->assertSame('qux? foo/bar?', Str::replaceStart('foo/bar?', 'qux?', 'foo/bar? foo/bar?')); - $this->assertSame('bar foobar', Str::replaceStart('foo', '', 'foobar foobar')); - $this->assertSame('1', Str::replaceStart(0, '1', '0')); - // Test for multibyte string support - $this->assertSame('xxxnköping Malmö', Str::replaceStart('Jö', 'xxx', 'Jönköping Malmö')); - $this->assertSame('Jönköping Malmö', Str::replaceStart('', 'yyy', 'Jönköping Malmö')); - } - - public function testReplaceLast() - { - $this->assertSame('foobar fooqux', Str::replaceLast('bar', 'qux', 'foobar foobar')); - $this->assertSame('foo/bar? foo/qux?', Str::replaceLast('bar?', 'qux?', 'foo/bar? foo/bar?')); - $this->assertSame('foobar foo', Str::replaceLast('bar', '', 'foobar foobar')); - $this->assertSame('foobar foobar', Str::replaceLast('xxx', 'yyy', 'foobar foobar')); - $this->assertSame('foobar foobar', Str::replaceLast('', 'yyy', 'foobar foobar')); - // Test for multibyte string support - $this->assertSame('Malmö Jönkxxxping', Str::replaceLast('ö', 'xxx', 'Malmö Jönköping')); - $this->assertSame('Malmö Jönköping', Str::replaceLast('', 'yyy', 'Malmö Jönköping')); - } - - public function testReplaceEnd() - { - $this->assertSame('foobar fooqux', Str::replaceEnd('bar', 'qux', 'foobar foobar')); - $this->assertSame('foo/bar? foo/qux?', Str::replaceEnd('bar?', 'qux?', 'foo/bar? foo/bar?')); - $this->assertSame('foobar foo', Str::replaceEnd('bar', '', 'foobar foobar')); - $this->assertSame('foobar foobar', Str::replaceEnd('xxx', 'yyy', 'foobar foobar')); - $this->assertSame('foobar foobar', Str::replaceEnd('', 'yyy', 'foobar foobar')); - $this->assertSame('fooxxx foobar', Str::replaceEnd('xxx', 'yyy', 'fooxxx foobar')); - - // // Test for multibyte string support - $this->assertSame('Malmö Jönköping', Str::replaceEnd('ö', 'xxx', 'Malmö Jönköping')); - $this->assertSame('Malmö Jönkyyy', Str::replaceEnd('öping', 'yyy', 'Malmö Jönköping')); - } - - public function testRemove() - { - $this->assertSame('Fbar', Str::remove('o', 'Foobar')); - $this->assertSame('Foo', Str::remove('bar', 'Foobar')); - $this->assertSame('oobar', Str::remove('F', 'Foobar')); - $this->assertSame('Foobar', Str::remove('f', 'Foobar')); - $this->assertSame('oobar', Str::remove('f', 'Foobar', false)); - - $this->assertSame('Fbr', Str::remove(['o', 'a'], 'Foobar')); - $this->assertSame('Fooar', Str::remove(['f', 'b'], 'Foobar')); - $this->assertSame('ooar', Str::remove(['f', 'b'], 'Foobar', false)); - $this->assertSame('Foobar', Str::remove(['f', '|'], 'Foo|bar')); - } - public function testReverse() { $this->assertSame('FooBar', Str::reverse('raBooF')); @@ -854,167 +454,6 @@ public function testReverse() $this->assertSame('❤MultiByte☆', Str::reverse('☆etyBitluM❤')); } - public function testSnake() - { - $this->assertSame('laravel_p_h_p_framework', Str::snake('LaravelPHPFramework')); - $this->assertSame('laravel_php_framework', Str::snake('LaravelPhpFramework')); - $this->assertSame('laravel php framework', Str::snake('LaravelPhpFramework', ' ')); - $this->assertSame('laravel_php_framework', Str::snake('Laravel Php Framework')); - $this->assertSame('laravel_php_framework', Str::snake('Laravel Php Framework ')); - // ensure cache keys don't overlap - $this->assertSame('laravel__php__framework', Str::snake('LaravelPhpFramework', '__')); - $this->assertSame('laravel_php_framework_', Str::snake('LaravelPhpFramework_', '_')); - $this->assertSame('laravel_php_framework', Str::snake('laravel php Framework')); - $this->assertSame('laravel_php_frame_work', Str::snake('laravel php FrameWork')); - // prevent breaking changes - $this->assertSame('foo-bar', Str::snake('foo-bar')); - $this->assertSame('foo-_bar', Str::snake('Foo-Bar')); - $this->assertSame('foo__bar', Str::snake('Foo_Bar')); - $this->assertSame('żółtałódka', Str::snake('ŻółtaŁódka')); - } - - public function testTrim() - { - $this->assertSame('foo bar', Str::trim(' foo bar ')); - $this->assertSame('foo bar', Str::trim('foo bar ')); - $this->assertSame('foo bar', Str::trim(' foo bar')); - $this->assertSame('foo bar', Str::trim('foo bar')); - $this->assertSame(' foo bar ', Str::trim(' foo bar ', '')); - $this->assertSame('foo bar', Str::trim(' foo bar ', ' ')); - $this->assertSame('foo bar', Str::trim('-foo bar_', '-_')); - - $this->assertSame('foo bar', Str::trim(' foo bar ')); - - $this->assertSame('123', Str::trim('  123   ')); - $this->assertSame('だ', Str::trim('だ')); - $this->assertSame('ム', Str::trim('ム')); - $this->assertSame('だ', Str::trim('  だ   ')); - $this->assertSame('ム', Str::trim('  ム   ')); - - $this->assertSame( - 'foo bar', - Str::trim(' - foo bar - ') - ); - $this->assertSame( - 'foo - bar', - Str::trim(' - foo - bar - ') - ); - - $this->assertSame("\xE9", Str::trim(" \xE9 ")); - - $trimDefaultChars = [' ', "\n", "\r", "\t", "\v", "\0"]; - - foreach ($trimDefaultChars as $char) { - $this->assertSame('', Str::trim(" {$char} ")); - $this->assertSame(trim(" {$char} "), Str::trim(" {$char} ")); - - $this->assertSame('foo bar', Str::trim("{$char} foo bar {$char}")); - $this->assertSame(trim("{$char} foo bar {$char}"), Str::trim("{$char} foo bar {$char}")); - } - } - - public function testLtrim() - { - $this->assertSame('foo bar ', Str::ltrim(' foo bar ')); - - $this->assertSame('123   ', Str::ltrim('  123   ')); - $this->assertSame('だ', Str::ltrim('だ')); - $this->assertSame('ム', Str::ltrim('ム')); - $this->assertSame('だ   ', Str::ltrim('  だ   ')); - $this->assertSame('ム   ', Str::ltrim('  ム   ')); - - $this->assertSame( - 'foo bar - ', - Str::ltrim(' - foo bar - ') - ); - $this->assertSame("\xE9 ", Str::ltrim(" \xE9 ")); - - $ltrimDefaultChars = [' ', "\n", "\r", "\t", "\v", "\0"]; - - foreach ($ltrimDefaultChars as $char) { - $this->assertSame('', Str::ltrim(" {$char} ")); - $this->assertSame(ltrim(" {$char} "), Str::ltrim(" {$char} ")); - - $this->assertSame("foo bar {$char}", Str::ltrim("{$char} foo bar {$char}")); - $this->assertSame(ltrim("{$char} foo bar {$char}"), Str::ltrim("{$char} foo bar {$char}")); - } - } - - public function testRtrim() - { - $this->assertSame(' foo bar', Str::rtrim(' foo bar ')); - - $this->assertSame('  123', Str::rtrim('  123   ')); - $this->assertSame('だ', Str::rtrim('だ')); - $this->assertSame('ム', Str::rtrim('ム')); - $this->assertSame('  だ', Str::rtrim('  だ   ')); - $this->assertSame('  ム', Str::rtrim('  ム   ')); - - $this->assertSame( - ' - foo bar', - Str::rtrim(' - foo bar - ') - ); - - $this->assertSame(" \xE9", Str::rtrim(" \xE9 ")); - - $rtrimDefaultChars = [' ', "\n", "\r", "\t", "\v", "\0"]; - - foreach ($rtrimDefaultChars as $char) { - $this->assertSame('', Str::rtrim(" {$char} ")); - $this->assertSame(rtrim(" {$char} "), Str::rtrim(" {$char} ")); - - $this->assertSame("{$char} foo bar", Str::rtrim("{$char} foo bar {$char}")); - $this->assertSame(rtrim("{$char} foo bar {$char}"), Str::rtrim("{$char} foo bar {$char}")); - } - } - - public function testSquish() - { - $this->assertSame('laravel php framework', Str::squish(' laravel php framework ')); - $this->assertSame('laravel php framework', Str::squish("laravel\t\tphp\n\nframework")); - $this->assertSame('laravel php framework', Str::squish(' - laravel - php - framework - ')); - $this->assertSame('laravel php framework', Str::squish('   laravel   php   framework   ')); - $this->assertSame('123', Str::squish('  123   ')); - $this->assertSame('だ', Str::squish('だ')); - $this->assertSame('ム', Str::squish('ム')); - $this->assertSame('だ', Str::squish('  だ   ')); - $this->assertSame('ム', Str::squish('  ム   ')); - $this->assertSame('laravel php framework', Str::squish('laravelㅤㅤㅤphpㅤframework')); - $this->assertSame('laravel php framework', Str::squish('laravelᅠᅠᅠᅠᅠᅠᅠᅠᅠᅠphpᅠᅠframework')); - } - - public function testStudly() - { - $this->assertSame('LaravelPHPFramework', Str::studly('laravel_p_h_p_framework')); - $this->assertSame('LaravelPhpFramework', Str::studly('laravel_php_framework')); - $this->assertSame('LaravelPhPFramework', Str::studly('laravel-phP-framework')); - $this->assertSame('LaravelPhpFramework', Str::studly('laravel -_- php -_- framework ')); - - $this->assertSame('FooBar', Str::studly('fooBar')); - $this->assertSame('FooBar', Str::studly('foo_bar')); - $this->assertSame('FooBar', Str::studly('foo_bar')); // test cache - $this->assertSame('FooBarBaz', Str::studly('foo-barBaz')); - $this->assertSame('FooBarBaz', Str::studly('foo-bar_baz')); - - $this->assertSame('ÖffentlicheÜberraschungen', Str::studly('öffentliche-überraschungen')); - } - public function testMask() { $this->assertSame('tay*************', Str::mask('taylor@email.com', '*', 3)); @@ -1050,42 +489,6 @@ public function testMask() $this->assertSame('***************', Str::mask('maria@email.com', '*', 0)); } - public function testMatch(): void - { - $this->assertSame('bar', Str::match('/bar/', 'foo bar')); - $this->assertSame('bar', Str::match('/foo (.*)/', 'foo bar')); - $this->assertEmpty(Str::match('/nothing/', 'foo bar')); - - $this->assertEquals(['bar', 'bar'], Str::matchAll('/bar/', 'bar foo bar')->all()); - - $this->assertEquals(['un', 'ly'], Str::matchAll('/f(\w*)/', 'bar fun bar fly')->all()); - $this->assertEmpty(Str::matchAll('/nothing/', 'bar fun bar fly')); - - $this->assertEmpty(Str::match('/pattern/', '')); - $this->assertEmpty(Str::matchAll('/pattern/', '')); - } - - public function testCamel(): void - { - $this->assertSame('laravelPHPFramework', Str::camel('Laravel_p_h_p_framework')); - $this->assertSame('laravelPhpFramework', Str::camel('Laravel_php_framework')); - $this->assertSame('laravelPhPFramework', Str::camel('Laravel-phP-framework')); - $this->assertSame('laravelPhpFramework', Str::camel('Laravel -_- php -_- framework ')); - - $this->assertSame('fooBar', Str::camel('FooBar')); - $this->assertSame('fooBar', Str::camel('foo_bar')); - $this->assertSame('fooBar', Str::camel('foo_bar')); // test cache - $this->assertSame('fooBarBaz', Str::camel('Foo-barBaz')); - $this->assertSame('fooBarBaz', Str::camel('foo-bar_baz')); - - $this->assertSame('', Str::camel('')); - $this->assertSame('lARAVELPHPFRAMEWORK', Str::camel('LARAVEL_PHP_FRAMEWORK')); - $this->assertSame('laravelPhpFramework', Str::camel(' laravel php framework ')); - - $this->assertSame('foo1Bar', Str::camel('foo1_bar')); - $this->assertSame('1FooBar', Str::camel('1 foo bar')); - } - public function testCharAt() { $this->assertEquals('р', Str::charAt('Привет, мир!', 1)); @@ -1142,13 +545,6 @@ public function testPosition() $this->assertFalse(Str::position('Hello, World!', 'X')); } - public function testSubstrReplace() - { - $this->assertSame('12:00', Str::substrReplace('1200', ':', 2, 0)); - $this->assertSame('The Laravel Framework', Str::substrReplace('The Framework', 'Laravel ', 4, 0)); - $this->assertSame('Laravel – The PHP Framework for Web Artisans', Str::substrReplace('Laravel Framework', '– The PHP Framework for Web Artisans', 8)); - } - public function testTake() { $this->assertSame('ab', Str::take('abcdef', 2)); @@ -1160,22 +556,6 @@ public function testTake() $this->assertSame('ü', Str::take('üöä', 1)); } - public function testLcfirst() - { - $this->assertSame('laravel', Str::lcfirst('Laravel')); - $this->assertSame('laravel framework', Str::lcfirst('Laravel framework')); - $this->assertSame('мама', Str::lcfirst('Мама')); - $this->assertSame('мама мыла раму', Str::lcfirst('Мама мыла раму')); - } - - public function testUcfirst() - { - $this->assertSame('Laravel', Str::ucfirst('laravel')); - $this->assertSame('Laravel framework', Str::ucfirst('laravel framework')); - $this->assertSame('Мама', Str::ucfirst('мама')); - $this->assertSame('Мама мыла раму', Str::ucfirst('мама мыла раму')); - } - public function testUcsplit() { $this->assertSame(['Laravel_p_h_p_framework'], Str::ucsplit('Laravel_p_h_p_framework')); @@ -1188,17 +568,10 @@ public function testUcsplit() $this->assertSame(['Öffentliche', 'Überraschungen'], Str::ucsplit('ÖffentlicheÜberraschungen')); } - public function testUuid() - { - $this->assertInstanceOf(UuidInterface::class, Str::uuid()); - $this->assertInstanceOf(UuidInterface::class, Str::orderedUuid()); - $this->assertInstanceOf(UuidInterface::class, Str::uuid7()); - } - public function testAsciiNull() { $this->assertSame('', Str::ascii(null)); - $this->assertTrue(Str::isAscii(null)); + $this->assertTrue(PatternMatcher::isAscii(null)); $this->assertSame('', Str::slug(null)); } @@ -1267,38 +640,6 @@ public function testWordWrap() $this->assertEquals('❤Multi
Byte☆❤☆❤☆❤', Str::wordWrap('❤Multi Byte☆❤☆❤☆❤', 3, '
')); } - public static function validUuidList() - { - return [ - ['a0a2a2d2-0b87-4a18-83f2-2529882be2de'], - ['145a1e72-d11d-11e8-a8d5-f2801f1b9fd1'], - ['00000000-0000-0000-0000-000000000000'], - ['e60d3f48-95d7-4d8d-aad0-856f29a27da2'], - ['ff6f8cb0-c57d-11e1-9b21-0800200c9a66'], - ['ff6f8cb0-c57d-21e1-9b21-0800200c9a66'], - ['ff6f8cb0-c57d-31e1-9b21-0800200c9a66'], - ['ff6f8cb0-c57d-41e1-9b21-0800200c9a66'], - ['ff6f8cb0-c57d-51e1-9b21-0800200c9a66'], - ['FF6F8CB0-C57D-11E1-9B21-0800200C9A66'], - ]; - } - - public static function invalidUuidList() - { - return [ - ['not a valid uuid so we can test this'], - ['zf6f8cb0-c57d-11e1-9b21-0800200c9a66'], - ['145a1e72-d11d-11e8-a8d5-f2801f1b9fd1'.PHP_EOL], - ['145a1e72-d11d-11e8-a8d5-f2801f1b9fd1 '], - [' 145a1e72-d11d-11e8-a8d5-f2801f1b9fd1'], - ['145a1e72-d11d-11e8-a8d5-f2z01f1b9fd1'], - ['3f6f8cb0-c57d-11e1-9b21-0800200c9a6'], - ['af6f8cb-c57d-11e1-9b21-0800200c9a66'], - ['af6f8cb0c57d11e19b210800200c9a66'], - ['ff6f8cb0-c57da-51e1-9b21-0800200c9a66'], - ]; - } - public static function strContainsProvider() { return [ @@ -1388,225 +729,6 @@ public function testTransliterateStrict(string $value, string $expected): void $this->assertSame($expected, Str::transliterate($value, '?', true)); } - public function testItCanFreezeUuids() - { - $this->assertNotSame((string) Str::uuid(), (string) Str::uuid()); - $this->assertNotSame(Str::uuid(), Str::uuid()); - - $uuid = Str::freezeUuids(); - - $this->assertSame($uuid, Str::uuid()); - $this->assertSame(Str::uuid(), Str::uuid()); - $this->assertSame((string) $uuid, (string) Str::uuid()); - $this->assertSame((string) Str::uuid(), (string) Str::uuid()); - - Str::createUuidsNormally(); - - $this->assertNotSame(Str::uuid(), Str::uuid()); - $this->assertNotSame((string) Str::uuid(), (string) Str::uuid()); - } - - public function testItCanFreezeUuidsInAClosure() - { - $uuids = []; - - $uuid = Str::freezeUuids(function ($uuid) use (&$uuids) { - $uuids[] = $uuid; - $uuids[] = Str::uuid(); - $uuids[] = Str::uuid(); - }); - - $this->assertSame($uuid, $uuids[0]); - $this->assertSame((string) $uuid, (string) $uuids[0]); - $this->assertSame((string) $uuids[0], (string) $uuids[1]); - $this->assertSame($uuids[0], $uuids[1]); - $this->assertSame((string) $uuids[0], (string) $uuids[1]); - $this->assertSame($uuids[1], $uuids[2]); - $this->assertSame((string) $uuids[1], (string) $uuids[2]); - $this->assertNotSame(Str::uuid(), Str::uuid()); - $this->assertNotSame((string) Str::uuid(), (string) Str::uuid()); - - Str::createUuidsNormally(); - } - - public function testItCreatesUuidsNormallyAfterFailureWithinFreezeMethod() - { - try { - Str::freezeUuids(function () { - Str::createUuidsUsing(fn () => Str::of('1234')); - $this->assertSame('1234', Str::uuid()->toString()); - throw new \Exception('Something failed.'); - }); - } catch (\Exception) { - $this->assertNotSame('1234', Str::uuid()->toString()); - } - } - - public function testItCanSpecifyASequenceOfUuidsToUtilise() - { - Str::createUuidsUsingSequence([ - 0 => ($zeroth = Str::uuid()), - 1 => ($first = Str::uuid7()), - // just generate a random one here... - 3 => ($third = Str::uuid()), - // continue to generate random uuids... - ]); - - $retrieved = Str::uuid(); - $this->assertSame($zeroth, $retrieved); - $this->assertSame((string) $zeroth, (string) $retrieved); - - $retrieved = Str::uuid(); - $this->assertSame($first, $retrieved); - $this->assertSame((string) $first, (string) $retrieved); - - $retrieved = Str::uuid(); - $this->assertFalse(in_array($retrieved, [$zeroth, $first, $third], true)); - $this->assertFalse(in_array((string) $retrieved, [(string) $zeroth, (string) $first, (string) $third], true)); - - $retrieved = Str::uuid(); - $this->assertSame($third, $retrieved); - $this->assertSame((string) $third, (string) $retrieved); - - $retrieved = Str::uuid(); - $this->assertFalse(in_array($retrieved, [$zeroth, $first, $third], true)); - $this->assertFalse(in_array((string) $retrieved, [(string) $zeroth, (string) $first, (string) $third], true)); - - Str::createUuidsNormally(); - } - - public function testItCanSpecifyAFallbackForASequence() - { - Str::createUuidsUsingSequence([Str::uuid(), Str::uuid()], fn () => throw new Exception('Out of Uuids.')); - Str::uuid(); - Str::uuid(); - - try { - $this->expectExceptionMessage('Out of Uuids.'); - Str::uuid(); - $this->fail(); - } finally { - Str::createUuidsNormally(); - } - } - - public function testItCanFreezeUlids() - { - $this->assertNotSame((string) Str::ulid(), (string) Str::ulid()); - $this->assertNotSame(Str::ulid(), Str::ulid()); - - $ulid = Str::freezeUlids(); - - $this->assertSame($ulid, Str::ulid()); - $this->assertSame(Str::ulid(), Str::ulid()); - $this->assertSame((string) $ulid, (string) Str::ulid()); - $this->assertSame((string) Str::ulid(), (string) Str::ulid()); - - Str::createUlidsNormally(); - - $this->assertNotSame(Str::ulid(), Str::ulid()); - $this->assertNotSame((string) Str::ulid(), (string) Str::ulid()); - } - - public function testItCanFreezeUlidsInAClosure() - { - $ulids = []; - - $ulid = Str::freezeUlids(function ($ulid) use (&$ulids) { - $ulids[] = $ulid; - $ulids[] = Str::ulid(); - $ulids[] = Str::ulid(); - }); - - $this->assertSame($ulid, $ulids[0]); - $this->assertSame((string) $ulid, (string) $ulids[0]); - $this->assertSame((string) $ulids[0], (string) $ulids[1]); - $this->assertSame($ulids[0], $ulids[1]); - $this->assertSame((string) $ulids[0], (string) $ulids[1]); - $this->assertSame($ulids[1], $ulids[2]); - $this->assertSame((string) $ulids[1], (string) $ulids[2]); - $this->assertNotSame(Str::ulid(), Str::ulid()); - $this->assertNotSame((string) Str::ulid(), (string) Str::ulid()); - - Str::createUlidsNormally(); - } - - public function testItCreatesUlidsNormallyAfterFailureWithinFreezeMethod() - { - try { - Str::freezeUlids(function () { - Str::createUlidsUsing(fn () => Str::of('1234')); - $this->assertSame('1234', (string) Str::ulid()); - throw new \Exception('Something failed'); - }); - } catch (\Exception) { - $this->assertNotSame('1234', (string) Str::ulid()); - } - } - - public function testItCanSpecifyASequenceOfUlidsToUtilise() - { - Str::createUlidsUsingSequence([ - 0 => ($zeroth = Str::ulid()), - 1 => ($first = Str::ulid()), - // just generate a random one here... - 3 => ($third = Str::ulid()), - // continue to generate random ulids... - ]); - - $retrieved = Str::ulid(); - $this->assertSame($zeroth, $retrieved); - $this->assertSame((string) $zeroth, (string) $retrieved); - - $retrieved = Str::ulid(); - $this->assertSame($first, $retrieved); - $this->assertSame((string) $first, (string) $retrieved); - - $retrieved = Str::ulid(); - $this->assertFalse(in_array($retrieved, [$zeroth, $first, $third], true)); - $this->assertFalse(in_array((string) $retrieved, [(string) $zeroth, (string) $first, (string) $third], true)); - - $retrieved = Str::ulid(); - $this->assertSame($third, $retrieved); - $this->assertSame((string) $third, (string) $retrieved); - - $retrieved = Str::ulid(); - $this->assertFalse(in_array($retrieved, [$zeroth, $first, $third], true)); - $this->assertFalse(in_array((string) $retrieved, [(string) $zeroth, (string) $first, (string) $third], true)); - - Str::createUlidsNormally(); - } - - public function testItCanSpecifyAFallbackForAUlidSequence() - { - Str::createUlidsUsingSequence( - [Str::ulid(), Str::ulid()], - fn () => throw new Exception('Out of Ulids'), - ); - Str::ulid(); - Str::ulid(); - - try { - $this->expectExceptionMessage('Out of Ulids'); - Str::ulid(); - $this->fail(); - } finally { - Str::createUlidsNormally(); - } - } - - public function testPasswordCreation() - { - $this->assertTrue(strlen(Str::password()) === 32); - - $this->assertStringNotContainsString(' ', Str::password()); - $this->assertStringContainsString(' ', Str::password(spaces: true)); - - $this->assertTrue( - Str::of(Str::password())->contains(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']) - ); - } - public function testToBase64() { $this->assertSame(base64_encode('foo'), Str::toBase64('foo')); From f6b4af4ee28fbcc230d6185aaa66400fbd20ecac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20H=C3=A4drich?= Date: Mon, 30 Sep 2024 14:14:45 +0200 Subject: [PATCH 04/14] Change the classes in unrelated tests as well --- .../Database/Eloquent/Concerns/QueriesRelationships.php | 3 ++- src/Illuminate/Foundation/Console/DocsCommand.php | 7 ++++--- src/Illuminate/Foundation/Console/ViewMakeCommand.php | 3 ++- src/Illuminate/Support/Stringable.php | 2 +- src/Illuminate/Validation/Concerns/ValidatesAttributes.php | 7 ++++--- 5 files changed, 13 insertions(+), 9 deletions(-) diff --git a/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php b/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php index 32a007573e5d..37cb55fe36c7 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php +++ b/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php @@ -12,6 +12,7 @@ use Illuminate\Database\Eloquent\Relations\Relation; use Illuminate\Database\Query\Builder as QueryBuilder; use Illuminate\Database\Query\Expression; +use Illuminate\Support\Casing; use Illuminate\Support\Str; use InvalidArgumentException; @@ -627,7 +628,7 @@ public function withAggregate($relations, $column, $function = null) unset($alias); - if (count($segments) === 3 && Str::lower($segments[1]) === 'as') { + if (count($segments) === 3 && Casing::lower($segments[1]) === 'as') { [$name, $alias] = [$segments[0], $segments[2]]; } diff --git a/src/Illuminate/Foundation/Console/DocsCommand.php b/src/Illuminate/Foundation/Console/DocsCommand.php index b8a36749ec2d..af9035ad87fc 100644 --- a/src/Illuminate/Foundation/Console/DocsCommand.php +++ b/src/Illuminate/Foundation/Console/DocsCommand.php @@ -7,6 +7,7 @@ use Illuminate\Contracts\Cache\Repository as Cache; use Illuminate\Http\Client\Factory as Http; use Illuminate\Support\Arr; +use Illuminate\Support\Casing; use Illuminate\Support\Collection; use Illuminate\Support\Env; use Illuminate\Support\Str; @@ -235,15 +236,15 @@ protected function askForPageViaAutocomplete() label: 'Which page would you like to open?', options: fn ($value) => $this->pages() ->mapWithKeys(fn ($option) => [ - Str::lower($option['title']) => $option['title'], + Casing::lower($option['title']) => $option['title'], ]) - ->filter(fn ($title) => str_contains(Str::lower($title), Str::lower($value))) + ->filter(fn ($title) => str_contains(Casing::lower($title), Casing::lower($value))) ->all(), placeholder: 'E.g. Collections' ); return $this->pages()->filter( - fn ($page) => $page['title'] === $choice || Str::lower($page['title']) === $choice + fn ($page) => $page['title'] === $choice || Casing::lower($page['title']) === $choice )->keys()->first() ?: $this->guessPage($choice); } diff --git a/src/Illuminate/Foundation/Console/ViewMakeCommand.php b/src/Illuminate/Foundation/Console/ViewMakeCommand.php index 3f8e4da6a639..6f91520af7c4 100644 --- a/src/Illuminate/Foundation/Console/ViewMakeCommand.php +++ b/src/Illuminate/Foundation/Console/ViewMakeCommand.php @@ -5,6 +5,7 @@ use Illuminate\Console\Concerns\CreatesMatchingTest; use Illuminate\Console\GeneratorCommand; use Illuminate\Foundation\Inspiring; +use Illuminate\Support\Casing; use Illuminate\Support\Facades\File; use Illuminate\Support\Str; use Symfony\Component\Console\Attribute\AsCommand; @@ -181,7 +182,7 @@ protected function testClassName() */ protected function testClassFullyQualifiedName() { - $name = Str::of(Str::lower($this->getNameInput()))->replace('.'.$this->option('extension'), ''); + $name = Str::of(Casing::lower($this->getNameInput()))->replace('.'.$this->option('extension'), ''); $namespacedName = Str::of( Str::of($name) diff --git a/src/Illuminate/Support/Stringable.php b/src/Illuminate/Support/Stringable.php index 6ae57e032066..b920e3568c32 100644 --- a/src/Illuminate/Support/Stringable.php +++ b/src/Illuminate/Support/Stringable.php @@ -459,7 +459,7 @@ public function limit($limit = 100, $end = '...', $preserveWords = false) */ public function lower() { - return new static(Str::lower($this->value)); + return new static(Casing::lower($this->value)); } /** diff --git a/src/Illuminate/Validation/Concerns/ValidatesAttributes.php b/src/Illuminate/Validation/Concerns/ValidatesAttributes.php index 5628e43783c9..522d2e1da4ef 100644 --- a/src/Illuminate/Validation/Concerns/ValidatesAttributes.php +++ b/src/Illuminate/Validation/Concerns/ValidatesAttributes.php @@ -18,6 +18,7 @@ use Illuminate\Container\Container; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Arr; +use Illuminate\Support\Casing; use Illuminate\Support\Exceptions\MathException; use Illuminate\Support\Facades\Date; use Illuminate\Support\Str; @@ -1353,7 +1354,7 @@ public function validateLte($attribute, $value, $parameters) */ public function validateLowercase($attribute, $value, $parameters) { - return Str::lower($value) === $value; + return Casing::lower($value) === $value; } /** @@ -1366,7 +1367,7 @@ public function validateLowercase($attribute, $value, $parameters) */ public function validateUppercase($attribute, $value, $parameters) { - return Str::upper($value) === $value; + return Casing::upper($value) === $value; } /** @@ -2290,7 +2291,7 @@ protected function convertValuesToBoolean($values) protected function convertValuesToNull($values) { return array_map(function ($value) { - return Str::lower($value) === 'null' ? null : $value; + return Casing::lower($value) === 'null' ? null : $value; }, $values); } From 7d58ebf6605b4268cff75ba7b6d3063eccfc1c03 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20H=C3=A4drich?= Date: Mon, 30 Sep 2024 17:43:12 +0200 Subject: [PATCH 05/14] refactor: :recycle: Replace classes in related Stringable class --- src/Illuminate/Support/Stringable.php | 66 +++++++++++++-------------- 1 file changed, 33 insertions(+), 33 deletions(-) diff --git a/src/Illuminate/Support/Stringable.php b/src/Illuminate/Support/Stringable.php index b920e3568c32..953389ccc841 100644 --- a/src/Illuminate/Support/Stringable.php +++ b/src/Illuminate/Support/Stringable.php @@ -196,7 +196,7 @@ public function betweenFirst($from, $to) */ public function camel() { - return new static(Str::camel($this->value)); + return new static(Casing::camel($this->value)); } /** @@ -232,7 +232,7 @@ public function containsAll($needles, $ignoreCase = false) */ public function convertCase(int $mode = MB_CASE_FOLD, ?string $encoding = 'UTF-8') { - return new static(Str::convertCase($this->value, $mode, $encoding)); + return new static(Casing::convertCase($this->value, $mode, $encoding)); } /** @@ -345,7 +345,7 @@ public function finish($cap) */ public function is($pattern) { - return Str::is($pattern, $this->value); + return PatternMatcher::is($pattern, $this->value); } /** @@ -355,7 +355,7 @@ public function is($pattern) */ public function isAscii() { - return Str::isAscii($this->value); + return PatternMatcher::isAscii($this->value); } /** @@ -375,7 +375,7 @@ public function isJson() */ public function isUrl() { - return Str::isUrl($this->value); + return PatternMatcher::isUrl($this->value); } /** @@ -385,7 +385,7 @@ public function isUrl() */ public function isUuid() { - return Str::isUuid($this->value); + return PatternMatcher::isUuid($this->value); } /** @@ -425,7 +425,7 @@ public function isNotEmpty() */ public function kebab() { - return new static(Str::kebab($this->value)); + return new static(Casing::kebab($this->value)); } /** @@ -507,7 +507,7 @@ public function mask($character, $index, $length = null, $encoding = 'UTF-8') */ public function match($pattern) { - return new static(Str::match($pattern, $this->value)); + return new static(PatternMatcher::match($pattern, $this->value)); } /** @@ -518,7 +518,7 @@ public function match($pattern) */ public function isMatch($pattern) { - return Str::isMatch($pattern, $this->value); + return PatternMatcher::isMatch($pattern, $this->value); } /** @@ -529,7 +529,7 @@ public function isMatch($pattern) */ public function matchAll($pattern) { - return Str::matchAll($pattern, $this->value); + return PatternMatcher::matchAll($pattern, $this->value); } /** @@ -550,7 +550,7 @@ public function test($pattern) */ public function numbers() { - return new static(Str::numbers($this->value)); + return new static(Replacer::numbers($this->value)); } /** @@ -619,7 +619,7 @@ public function pipe(callable $callback) */ public function plural($count = 2) { - return new static(Str::plural($this->value, $count)); + return new static(StrGrammar::plural($this->value, $count)); } /** @@ -630,7 +630,7 @@ public function plural($count = 2) */ public function pluralStudly($count = 2) { - return new static(Str::pluralStudly($this->value, $count)); + return new static(StrGrammar::pluralStudly($this->value, $count)); } /** @@ -666,7 +666,7 @@ public function prepend(...$values) */ public function remove($search, $caseSensitive = true) { - return new static(Str::remove($search, $this->value, $caseSensitive)); + return new static(Sanitizer::remove($search, $this->value, $caseSensitive)); } /** @@ -700,7 +700,7 @@ public function repeat(int $times) */ public function replace($search, $replace, $caseSensitive = true) { - return new static(Str::replace($search, $replace, $this->value, $caseSensitive)); + return new static(Replacer::replace($search, $replace, $this->value, $caseSensitive)); } /** @@ -712,7 +712,7 @@ public function replace($search, $replace, $caseSensitive = true) */ public function replaceArray($search, $replace) { - return new static(Str::replaceArray($search, $replace, $this->value)); + return new static(Replacer::replaceArray($search, $replace, $this->value)); } /** @@ -724,7 +724,7 @@ public function replaceArray($search, $replace) */ public function replaceFirst($search, $replace) { - return new static(Str::replaceFirst($search, $replace, $this->value)); + return new static(Replacer::replaceFirst($search, $replace, $this->value)); } /** @@ -736,7 +736,7 @@ public function replaceFirst($search, $replace) */ public function replaceStart($search, $replace) { - return new static(Str::replaceStart($search, $replace, $this->value)); + return new static(Replacer::replaceStart($search, $replace, $this->value)); } /** @@ -748,7 +748,7 @@ public function replaceStart($search, $replace) */ public function replaceLast($search, $replace) { - return new static(Str::replaceLast($search, $replace, $this->value)); + return new static(Replacer::replaceLast($search, $replace, $this->value)); } /** @@ -760,7 +760,7 @@ public function replaceLast($search, $replace) */ public function replaceEnd($search, $replace) { - return new static(Str::replaceEnd($search, $replace, $this->value)); + return new static(Replacer::replaceEnd($search, $replace, $this->value)); } /** @@ -798,7 +798,7 @@ public function scan($format) */ public function squish() { - return new static(Str::squish($this->value)); + return new static(Sanitizer::squish($this->value)); } /** @@ -830,7 +830,7 @@ public function stripTags($allowedTags = null) */ public function upper() { - return new static(Str::upper($this->value)); + return new static(Casing::upper($this->value)); } /** @@ -840,7 +840,7 @@ public function upper() */ public function title() { - return new static(Str::title($this->value)); + return new static(Casing::title($this->value)); } /** @@ -850,7 +850,7 @@ public function title() */ public function headline() { - return new static(Str::headline($this->value)); + return new static(Casing::headline($this->value)); } /** @@ -882,7 +882,7 @@ public function transliterate($unknown = '?', $strict = false) */ public function singular() { - return new static(Str::singular($this->value)); + return new static(StrGrammar::singular($this->value)); } /** @@ -906,7 +906,7 @@ public function slug($separator = '-', $language = 'en', $dictionary = ['@' => ' */ public function snake($delimiter = '_') { - return new static(Str::snake($this->value, $delimiter)); + return new static(Casing::snake($this->value, $delimiter)); } /** @@ -927,7 +927,7 @@ public function startsWith($needles) */ public function studly() { - return new static(Str::studly($this->value)); + return new static(Casing::studly($this->value)); } /** @@ -966,7 +966,7 @@ public function substrCount($needle, $offset = 0, $length = null) */ public function substrReplace($replace, $offset = 0, $length = null) { - return new static(Str::substrReplace($this->value, $replace, $offset, $length)); + return new static(Replacer::substrReplace($this->value, $replace, $offset, $length)); } /** @@ -1003,7 +1003,7 @@ public function take(int $limit) */ public function trim($characters = null) { - return new static(Str::trim(...array_merge([$this->value], func_get_args()))); + return new static(Sanitizer::trim(...array_merge([$this->value], func_get_args()))); } /** @@ -1014,7 +1014,7 @@ public function trim($characters = null) */ public function ltrim($characters = null) { - return new static(Str::ltrim(...array_merge([$this->value], func_get_args()))); + return new static(Sanitizer::ltrim(...array_merge([$this->value], func_get_args()))); } /** @@ -1025,7 +1025,7 @@ public function ltrim($characters = null) */ public function rtrim($characters = null) { - return new static(Str::rtrim(...array_merge([$this->value], func_get_args()))); + return new static(Sanitizer::rtrim(...array_merge([$this->value], func_get_args()))); } /** @@ -1035,7 +1035,7 @@ public function rtrim($characters = null) */ public function lcfirst() { - return new static(Str::lcfirst($this->value)); + return new static(Casing::lcfirst($this->value)); } /** @@ -1045,7 +1045,7 @@ public function lcfirst() */ public function ucfirst() { - return new static(Str::ucfirst($this->value)); + return new static(Casing::ucfirst($this->value)); } /** From c7ee1c647b6ef3c3f5f47103f8430697fd700f6c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20H=C3=A4drich?= Date: Mon, 30 Sep 2024 17:43:41 +0200 Subject: [PATCH 06/14] refactor: :recycle: Change the classes in other classes --- src/Illuminate/Auth/Access/Gate.php | 3 +- .../Passwords/DatabaseTokenRepository.php | 3 +- src/Illuminate/Auth/SessionGuard.php | 3 +- .../Broadcasters/AblyBroadcaster.php | 9 +- .../UsePusherChannelConventions.php | 3 +- src/Illuminate/Cache/DynamoDbStore.php | 3 +- src/Illuminate/Cache/Lock.php | 3 +- src/Illuminate/Cache/RedisStore.php | 3 +- src/Illuminate/Console/GeneratorCommand.php | 3 +- .../Console/Factories/FactoryMakeCommand.php | 6 +- .../Console/Migrations/MigrateMakeCommand.php | 3 +- .../Console/Seeds/SeederMakeCommand.php | 3 +- .../Database/Console/ShowModelCommand.php | 5 +- .../Eloquent/Concerns/HasAttributes.php | 27 +- .../Eloquent/Concerns/HasRelationships.php | 12 +- .../Database/Eloquent/Concerns/HasUuids.php | 5 +- .../Concerns/QueriesRelationships.php | 4 +- .../Database/Eloquent/Factories/Factory.php | 19 +- src/Illuminate/Database/Eloquent/Model.php | 10 +- .../Eloquent/Relations/BelongsToMany.php | 4 +- .../Eloquent/Relations/Concerns/AsPivot.php | 4 +- .../Concerns/SupportsInverseRelations.php | 7 +- .../Database/Migrations/MigrationCreator.php | 3 +- .../Database/Migrations/Migrator.php | 3 +- src/Illuminate/Database/Query/Builder.php | 3 +- .../Database/Query/Grammars/MySqlGrammar.php | 5 +- .../Database/Query/Grammars/SQLiteGrammar.php | 5 +- .../Query/Grammars/SqlServerGrammar.php | 3 +- src/Illuminate/Database/QueryException.php | 3 +- src/Illuminate/Events/Dispatcher.php | 7 +- .../Filesystem/FilesystemAdapter.php | 3 +- src/Illuminate/Foundation/Application.php | 3 +- .../Auth/Access/AuthorizesRequests.php | 3 +- .../Console/ComponentMakeCommand.php | 3 +- .../Foundation/Console/DownCommand.php | 3 +- .../Foundation/Console/MailMakeCommand.php | 5 +- .../Foundation/Console/ModelMakeCommand.php | 14 +- .../Console/NotificationMakeCommand.php | 3 +- .../Foundation/Console/PolicyMakeCommand.php | 11 +- .../Foundation/Console/TestMakeCommand.php | 3 +- .../Foundation/Events/DiscoverEvents.php | 8 +- .../Http/Middleware/TrimStrings.php | 3 +- src/Illuminate/Foundation/Vite.php | 3 +- src/Illuminate/Http/Client/Factory.php | 3 +- src/Illuminate/Http/FileHelpers.php | 3 +- src/Illuminate/Http/RedirectResponse.php | 3 +- src/Illuminate/Http/Request.php | 5 +- .../Http/Resources/CollectsResources.php | 5 +- src/Illuminate/Log/LogManager.php | 3 +- src/Illuminate/Mail/MailManager.php | 5 +- src/Illuminate/Mail/Mailable.php | 6 +- src/Illuminate/Mail/Message.php | 5 +- .../Notifications/Channels/MailChannel.php | 6 +- .../Notifications/RoutesNotifications.php | 3 +- src/Illuminate/Process/PendingProcess.php | 3 +- src/Illuminate/Queue/Console/ClearCommand.php | 3 +- src/Illuminate/Queue/RedisQueue.php | 3 +- .../Redis/Limiters/ConcurrencyLimiter.php | 3 +- .../Routing/AbstractRouteCollection.php | 3 +- .../Exceptions/UrlGenerationException.php | 4 +- .../Routing/ImplicitRouteBinding.php | 3 +- src/Illuminate/Routing/ResourceRegistrar.php | 3 +- src/Illuminate/Routing/Route.php | 3 +- src/Illuminate/Routing/Router.php | 3 +- src/Illuminate/Session/Store.php | 6 +- src/Illuminate/Support/Manager.php | 2 +- src/Illuminate/Support/MessageBag.php | 2 +- .../Support/MultipleInstanceManager.php | 2 +- .../Support/Testing/Fakes/EventFake.php | 3 +- src/Illuminate/Testing/ParallelTesting.php | 2 +- src/Illuminate/Translation/Translator.php | 5 +- .../Validation/Concerns/FormatsMessages.php | 20 +- .../Concerns/ValidatesAttributes.php | 13 +- src/Illuminate/Validation/Factory.php | 7 +- .../Validation/ValidationRuleParser.php | 5 +- src/Illuminate/Validation/Validator.php | 21 +- .../View/Compilers/BladeCompiler.php | 5 +- .../View/Compilers/ComponentTagCompiler.php | 12 +- src/Illuminate/View/ComponentAttributeBag.php | 3 +- .../View/Concerns/ManagesLayouts.php | 3 +- src/Illuminate/View/DynamicComponent.php | 7 +- src/Illuminate/View/View.php | 3 +- tests/Foundation/FoundationViteTest.php | 53 +-- tests/Integration/Auth/AuthenticationTest.php | 3 +- tests/Integration/Auth/ForgotPasswordTest.php | 3 +- ...ForgotPasswordWithoutDefaultRoutesTest.php | 3 +- .../RedirectIfAuthenticatedTest.php | 3 +- tests/Integration/Cache/DynamoDbStoreTest.php | 3 +- .../Integration/Console/CommandEventsTest.php | 3 +- .../Console/CommandSchedulingTest.php | 3 +- tests/Integration/Cookie/CookieTest.php | 3 +- ...abaseEloquentModelAttributeCastingTest.php | 11 +- .../Database/EloquentBelongsToManyTest.php | 327 +++++++++--------- .../Database/EloquentBelongsToTest.php | 3 +- .../Database/EloquentHasManyTest.php | 9 +- .../Database/EloquentHasManyThroughTest.php | 17 +- .../Database/EloquentModelTest.php | 9 +- .../Database/EloquentMorphManyTest.php | 3 +- ...EloquentTouchParentWithGlobalScopeTest.php | 5 +- .../EloquentUniqueStringPrimaryKeysTest.php | 25 +- .../Database/EloquentUpdateTest.php | 9 +- .../Database/MySql/JoinLateralTest.php | 11 +- .../Database/Postgres/JoinLateralTest.php | 11 +- .../Database/SqlServer/JoinLateralTest.php | 11 +- .../Sqlite/EloquentModelConnectionsTest.php | 9 +- .../RouteServiceProviderHealthTest.php | 3 +- tests/Integration/Queue/JobEncryptionTest.php | 3 +- .../Queue/RateLimitedWithRedisTest.php | 3 +- .../ThrottlesExceptionsWithRedisTest.php | 7 +- .../Session/CookieSessionHandlerTest.php | 3 +- .../Session/SessionPersistenceTest.php | 3 +- .../Support/PluralizerPortugueseTest.php | 64 ++-- tests/Routing/RoutingRouteTest.php | 13 +- tests/Session/SessionStoreTest.php | 7 +- 114 files changed, 599 insertions(+), 482 deletions(-) diff --git a/src/Illuminate/Auth/Access/Gate.php b/src/Illuminate/Auth/Access/Gate.php index 746164843907..66d1a8982949 100644 --- a/src/Illuminate/Auth/Access/Gate.php +++ b/src/Illuminate/Auth/Access/Gate.php @@ -10,6 +10,7 @@ use Illuminate\Contracts\Container\Container; use Illuminate\Contracts\Events\Dispatcher; use Illuminate\Support\Arr; +use Illuminate\Support\Casing; use Illuminate\Support\Collection; use Illuminate\Support\Str; use InvalidArgumentException; @@ -825,7 +826,7 @@ protected function callPolicyMethod($policy, $method, $user, array $arguments) */ protected function formatAbilityToMethod($ability) { - return str_contains($ability, '-') ? Str::camel($ability) : $ability; + return str_contains($ability, '-') ? Casing::camel($ability) : $ability; } /** diff --git a/src/Illuminate/Auth/Passwords/DatabaseTokenRepository.php b/src/Illuminate/Auth/Passwords/DatabaseTokenRepository.php index 5449603fbc6b..7844592806a3 100755 --- a/src/Illuminate/Auth/Passwords/DatabaseTokenRepository.php +++ b/src/Illuminate/Auth/Passwords/DatabaseTokenRepository.php @@ -6,6 +6,7 @@ use Illuminate\Contracts\Hashing\Hasher as HasherContract; use Illuminate\Database\ConnectionInterface; use Illuminate\Support\Carbon; +use Illuminate\Support\Generator; use Illuminate\Support\Str; class DatabaseTokenRepository implements TokenRepositoryInterface @@ -211,7 +212,7 @@ public function deleteExpired() */ public function createNewToken() { - return hash_hmac('sha256', Str::random(40), $this->hashKey); + return hash_hmac('sha256', Generator::random(40), $this->hashKey); } /** diff --git a/src/Illuminate/Auth/SessionGuard.php b/src/Illuminate/Auth/SessionGuard.php index e4a46c611eb0..47956a04dc46 100644 --- a/src/Illuminate/Auth/SessionGuard.php +++ b/src/Illuminate/Auth/SessionGuard.php @@ -19,6 +19,7 @@ use Illuminate\Contracts\Session\Session; use Illuminate\Support\Arr; use Illuminate\Support\Facades\Hash; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use Illuminate\Support\Timebox; use Illuminate\Support\Traits\Macroable; @@ -671,7 +672,7 @@ protected function clearUserDataFromStorage() */ protected function cycleRememberToken(AuthenticatableContract $user) { - $user->setRememberToken($token = Str::random(60)); + $user->setRememberToken($token = Generator::random(60)); $this->provider->updateRememberToken($user, $token); } diff --git a/src/Illuminate/Broadcasting/Broadcasters/AblyBroadcaster.php b/src/Illuminate/Broadcasting/Broadcasters/AblyBroadcaster.php index 01c673c22f32..55128f67b939 100644 --- a/src/Illuminate/Broadcasting/Broadcasters/AblyBroadcaster.php +++ b/src/Illuminate/Broadcasting/Broadcasters/AblyBroadcaster.php @@ -6,6 +6,7 @@ use Ably\Exceptions\AblyException; use Ably\Models\Message as AblyMessage; use Illuminate\Broadcasting\BroadcastException; +use Illuminate\Support\Replacer; use Illuminate\Support\Str; use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; @@ -175,8 +176,8 @@ public function normalizeChannelName($channel) { if ($this->isGuardedChannel($channel)) { return str_starts_with($channel, 'private-') - ? Str::replaceFirst('private-', '', $channel) - : Str::replaceFirst('presence-', '', $channel); + ? Replacer::replaceFirst('private-', '', $channel) + : Replacer::replaceFirst('presence-', '', $channel); } return $channel; @@ -195,8 +196,8 @@ protected function formatChannels(array $channels) if (Str::startsWith($channel, ['private-', 'presence-'])) { return str_starts_with($channel, 'private-') - ? Str::replaceFirst('private-', 'private:', $channel) - : Str::replaceFirst('presence-', 'presence:', $channel); + ? Replacer::replaceFirst('private-', 'private:', $channel) + : Replacer::replaceFirst('presence-', 'presence:', $channel); } return 'public:'.$channel; diff --git a/src/Illuminate/Broadcasting/Broadcasters/UsePusherChannelConventions.php b/src/Illuminate/Broadcasting/Broadcasters/UsePusherChannelConventions.php index 690cf3d4aca2..5bec3b578016 100644 --- a/src/Illuminate/Broadcasting/Broadcasters/UsePusherChannelConventions.php +++ b/src/Illuminate/Broadcasting/Broadcasters/UsePusherChannelConventions.php @@ -2,6 +2,7 @@ namespace Illuminate\Broadcasting\Broadcasters; +use Illuminate\Support\Replacer; use Illuminate\Support\Str; trait UsePusherChannelConventions @@ -27,7 +28,7 @@ public function normalizeChannelName($channel) { foreach (['private-encrypted-', 'private-', 'presence-'] as $prefix) { if (Str::startsWith($channel, $prefix)) { - return Str::replaceFirst($prefix, '', $channel); + return Replacer::replaceFirst($prefix, '', $channel); } } diff --git a/src/Illuminate/Cache/DynamoDbStore.php b/src/Illuminate/Cache/DynamoDbStore.php index 88c7cf3be436..4371c3cef4c4 100644 --- a/src/Illuminate/Cache/DynamoDbStore.php +++ b/src/Illuminate/Cache/DynamoDbStore.php @@ -8,6 +8,7 @@ use Illuminate\Contracts\Cache\Store; use Illuminate\Support\Carbon; use Illuminate\Support\InteractsWithTime; +use Illuminate\Support\Replacer; use Illuminate\Support\Str; use RuntimeException; @@ -167,7 +168,7 @@ public function many(array $keys) ); } - return [Str::replaceFirst($this->prefix, '', $response[$this->keyAttribute]['S']) => $value]; + return [Replacer::replaceFirst($this->prefix, '', $response[$this->keyAttribute]['S']) => $value]; })->all()); } diff --git a/src/Illuminate/Cache/Lock.php b/src/Illuminate/Cache/Lock.php index 18cd86a5690e..af999c5c22b2 100644 --- a/src/Illuminate/Cache/Lock.php +++ b/src/Illuminate/Cache/Lock.php @@ -4,6 +4,7 @@ use Illuminate\Contracts\Cache\Lock as LockContract; use Illuminate\Contracts\Cache\LockTimeoutException; +use Illuminate\Support\Generator; use Illuminate\Support\InteractsWithTime; use Illuminate\Support\Sleep; use Illuminate\Support\Str; @@ -51,7 +52,7 @@ abstract class Lock implements LockContract public function __construct($name, $seconds, $owner = null) { if (is_null($owner)) { - $owner = Str::random(); + $owner = Generator::random(); } $this->name = $name; diff --git a/src/Illuminate/Cache/RedisStore.php b/src/Illuminate/Cache/RedisStore.php index f953d30d5857..7fb9fe1e3b63 100755 --- a/src/Illuminate/Cache/RedisStore.php +++ b/src/Illuminate/Cache/RedisStore.php @@ -7,6 +7,7 @@ use Illuminate\Redis\Connections\PhpRedisConnection; use Illuminate\Redis\Connections\PredisConnection; use Illuminate\Support\LazyCollection; +use Illuminate\Support\PatternMatcher; use Illuminate\Support\Str; class RedisStore extends TaggableStore implements LockProvider @@ -317,7 +318,7 @@ protected function currentTags($chunkSize = 1000) yield $tag; } } while (((string) $cursor) !== $defaultCursorValue); - })->map(fn (string $tagKey) => Str::match('/^'.preg_quote($prefix, '/').'tag:(.*):entries$/', $tagKey)); + })->map(fn (string $tagKey) => PatternMatcher::match('/^'.preg_quote($prefix, '/').'tag:(.*):entries$/', $tagKey)); } /** diff --git a/src/Illuminate/Console/GeneratorCommand.php b/src/Illuminate/Console/GeneratorCommand.php index 0d662f33800e..b84ecc867dc1 100644 --- a/src/Illuminate/Console/GeneratorCommand.php +++ b/src/Illuminate/Console/GeneratorCommand.php @@ -5,6 +5,7 @@ use Illuminate\Console\Concerns\CreatesMatchingTest; use Illuminate\Contracts\Console\PromptsForMissingInput; use Illuminate\Filesystem\Filesystem; +use Illuminate\Support\Replacer; use Illuminate\Support\Str; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Finder\Finder; @@ -305,7 +306,7 @@ protected function alreadyExists($rawName) */ protected function getPath($name) { - $name = Str::replaceFirst($this->rootNamespace(), '', $name); + $name = Replacer::replaceFirst($this->rootNamespace(), '', $name); return $this->laravel['path'].'/'.str_replace('\\', '/', $name).'.php'; } diff --git a/src/Illuminate/Database/Console/Factories/FactoryMakeCommand.php b/src/Illuminate/Database/Console/Factories/FactoryMakeCommand.php index ba8df30531f9..be9fc7b4656c 100644 --- a/src/Illuminate/Database/Console/Factories/FactoryMakeCommand.php +++ b/src/Illuminate/Database/Console/Factories/FactoryMakeCommand.php @@ -3,6 +3,8 @@ namespace Illuminate\Database\Console\Factories; use Illuminate\Console\GeneratorCommand; +use Illuminate\Support\Casing; +use Illuminate\Support\Replacer; use Illuminate\Support\Str; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputOption; @@ -62,7 +64,7 @@ protected function resolveStubPath($stub) */ protected function buildClass($name) { - $factory = class_basename(Str::ucfirst(str_replace('Factory', '', $name))); + $factory = class_basename(Casing::ucfirst(str_replace('Factory', '', $name))); $namespaceModel = $this->option('model') ? $this->qualifyModel($this->option('model')) @@ -71,7 +73,7 @@ protected function buildClass($name) $model = class_basename($namespaceModel); $namespace = $this->getNamespace( - Str::replaceFirst($this->rootNamespace(), 'Database\\Factories\\', $this->qualifyClass($this->getNameInput())) + Replacer::replaceFirst($this->rootNamespace(), 'Database\\Factories\\', $this->qualifyClass($this->getNameInput())) ); $replace = [ diff --git a/src/Illuminate/Database/Console/Migrations/MigrateMakeCommand.php b/src/Illuminate/Database/Console/Migrations/MigrateMakeCommand.php index 367f14839e64..627c3386ec48 100644 --- a/src/Illuminate/Database/Console/Migrations/MigrateMakeCommand.php +++ b/src/Illuminate/Database/Console/Migrations/MigrateMakeCommand.php @@ -4,6 +4,7 @@ use Illuminate\Contracts\Console\PromptsForMissingInput; use Illuminate\Database\Migrations\MigrationCreator; +use Illuminate\Support\Casing; use Illuminate\Support\Composer; use Illuminate\Support\Str; use Symfony\Component\Console\Attribute\AsCommand; @@ -71,7 +72,7 @@ public function handle() // It's possible for the developer to specify the tables to modify in this // schema operation. The developer may also specify if this table needs // to be freshly created so we can create the appropriate migrations. - $name = Str::snake(trim($this->input->getArgument('name'))); + $name = Casing::snake(trim($this->input->getArgument('name'))); $table = $this->input->getOption('table'); diff --git a/src/Illuminate/Database/Console/Seeds/SeederMakeCommand.php b/src/Illuminate/Database/Console/Seeds/SeederMakeCommand.php index c021bbbe54fb..804323f28768 100644 --- a/src/Illuminate/Database/Console/Seeds/SeederMakeCommand.php +++ b/src/Illuminate/Database/Console/Seeds/SeederMakeCommand.php @@ -3,6 +3,7 @@ namespace Illuminate\Database\Console\Seeds; use Illuminate\Console\GeneratorCommand; +use Illuminate\Support\Replacer; use Illuminate\Support\Str; use Symfony\Component\Console\Attribute\AsCommand; @@ -71,7 +72,7 @@ protected function resolveStubPath($stub) */ protected function getPath($name) { - $name = str_replace('\\', '/', Str::replaceFirst($this->rootNamespace(), '', $name)); + $name = str_replace('\\', '/', Replacer::replaceFirst($this->rootNamespace(), '', $name)); if (is_dir($this->laravel->databasePath().'/seeds')) { return $this->laravel->databasePath().'/seeds/'.$name.'.php'; diff --git a/src/Illuminate/Database/Console/ShowModelCommand.php b/src/Illuminate/Database/Console/ShowModelCommand.php index d7a44ccf37f9..f7c9c5bb3336 100644 --- a/src/Illuminate/Database/Console/ShowModelCommand.php +++ b/src/Illuminate/Database/Console/ShowModelCommand.php @@ -6,6 +6,7 @@ use Illuminate\Contracts\Container\BindingResolutionException; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\Relation; +use Illuminate\Support\Casing; use Illuminate\Support\Facades\Gate; use Illuminate\Support\Str; use ReflectionClass; @@ -160,9 +161,9 @@ protected function getVirtualAttributes($model, $columns) ) ->mapWithKeys(function (ReflectionMethod $method) use ($model) { if (preg_match('/^get(.+)Attribute$/', $method->getName(), $matches) === 1) { - return [Str::snake($matches[1]) => 'accessor']; + return [Casing::snake($matches[1]) => 'accessor']; } elseif ($model->hasAttributeMutator($method->getName())) { - return [Str::snake($method->getName()) => 'attribute']; + return [Casing::snake($method->getName()) => 'attribute']; } else { return []; } diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php b/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php index f3bb5fd11f08..cc4c1f1baa64 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php @@ -28,6 +28,7 @@ use Illuminate\Database\LazyLoadingViolationException; use Illuminate\Support\Arr; use Illuminate\Support\Carbon; +use Illuminate\Support\Casing; use Illuminate\Support\Collection as BaseCollection; use Illuminate\Support\Exceptions\MathException; use Illuminate\Support\Facades\Crypt; @@ -388,7 +389,7 @@ public function relationsToArray() // key so that the relation attribute is snake cased in this returned // array to the developers, making this consistent with attributes. if (static::$snakeAttributes) { - $key = Str::snake($key); + $key = Casing::snake($key); } // If the relation value has been set, we will set it on this attributes @@ -629,7 +630,7 @@ protected function getRelationshipFromMethod($method) */ public function hasGetMutator($key) { - return method_exists($this, 'get'.Str::studly($key).'Attribute'); + return method_exists($this, 'get'.Casing::studly($key).'Attribute'); } /** @@ -644,7 +645,7 @@ public function hasAttributeMutator($key) return static::$attributeMutatorCache[get_class($this)][$key]; } - if (! method_exists($this, $method = Str::camel($key))) { + if (! method_exists($this, $method = Casing::camel($key))) { return static::$attributeMutatorCache[get_class($this)][$key] = false; } @@ -671,7 +672,7 @@ public function hasAttributeGetMutator($key) return static::$getAttributeMutatorCache[get_class($this)][$key] = false; } - return static::$getAttributeMutatorCache[get_class($this)][$key] = is_callable($this->{Str::camel($key)}()->get); + return static::$getAttributeMutatorCache[get_class($this)][$key] = is_callable($this->{Casing::camel($key)}()->get); } /** @@ -683,7 +684,7 @@ public function hasAttributeGetMutator($key) */ protected function mutateAttribute($key, $value) { - return $this->{'get'.Str::studly($key).'Attribute'}($value); + return $this->{'get'.Casing::studly($key).'Attribute'}($value); } /** @@ -699,7 +700,7 @@ protected function mutateAttributeMarkedAttribute($key, $value) return $this->attributeCastCache[$key]; } - $attribute = $this->{Str::camel($key)}(); + $attribute = $this->{Casing::camel($key)}(); $value = call_user_func($attribute->get ?: function ($value) { return $value; @@ -1067,7 +1068,7 @@ public function setAttribute($key, $value) */ public function hasSetMutator($key) { - return method_exists($this, 'set'.Str::studly($key).'Attribute'); + return method_exists($this, 'set'.Casing::studly($key).'Attribute'); } /** @@ -1084,7 +1085,7 @@ public function hasAttributeSetMutator($key) return static::$setAttributeMutatorCache[$class][$key]; } - if (! method_exists($this, $method = Str::camel($key))) { + if (! method_exists($this, $method = Casing::camel($key))) { return static::$setAttributeMutatorCache[$class][$key] = false; } @@ -1105,7 +1106,7 @@ public function hasAttributeSetMutator($key) */ protected function setMutatedAttributeValue($key, $value) { - return $this->{'set'.Str::studly($key).'Attribute'}($value); + return $this->{'set'.Casing::studly($key).'Attribute'}($value); } /** @@ -1117,7 +1118,7 @@ protected function setMutatedAttributeValue($key, $value) */ protected function setAttributeMarkedMutatedAttributeValue($key, $value) { - $attribute = $this->{Str::camel($key)}(); + $attribute = $this->{Casing::camel($key)}(); $callback = $attribute->set ?: function ($value) use ($key) { $this->attributes[$key] = $value; @@ -1838,7 +1839,7 @@ protected function mergeAttributesFromClassCasts() protected function mergeAttributesFromAttributeCasts() { foreach ($this->attributeCastCache as $key => $value) { - $attribute = $this->{Str::camel($key)}(); + $attribute = $this->{Casing::camel($key)}(); if ($attribute->get && ! $attribute->set) { continue; @@ -2317,13 +2318,13 @@ public static function cacheMutatedAttributes($classOrInstance) static::$getAttributeMutatorCache[$class] = collect($attributeMutatorMethods = static::getAttributeMarkedMutatorMethods($classOrInstance)) ->mapWithKeys(function ($match) { - return [lcfirst(static::$snakeAttributes ? Str::snake($match) : $match) => true]; + return [lcfirst(static::$snakeAttributes ? Casing::snake($match) : $match) => true]; })->all(); static::$mutatorCache[$class] = collect(static::getMutatorMethods($class)) ->merge($attributeMutatorMethods) ->map(function ($match) { - return lcfirst(static::$snakeAttributes ? Str::snake($match) : $match); + return lcfirst(static::$snakeAttributes ? Casing::snake($match) : $match); })->all(); } diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php index 188c271abc38..a1411fa1b16f 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php @@ -21,7 +21,9 @@ use Illuminate\Database\Eloquent\Relations\Pivot; use Illuminate\Database\Eloquent\Relations\Relation; use Illuminate\Support\Arr; +use Illuminate\Support\Casing; use Illuminate\Support\Str; +use Illuminate\Support\StrGrammar; trait HasRelationships { @@ -247,7 +249,7 @@ public function belongsTo($related, $foreignKey = null, $ownerKey = null, $relat // foreign key name by using the name of the relationship function, which // when combined with an "_id" should conventionally match the columns. if (is_null($foreignKey)) { - $foreignKey = Str::snake($relation).'_'.$instance->getKeyName(); + $foreignKey = Casing::snake($relation).'_'.$instance->getKeyName(); } // Once we have the foreign key names we'll just create a new Eloquent query @@ -295,7 +297,7 @@ public function morphTo($name = null, $type = null, $id = null, $ownerKey = null $name = $name ?: $this->guessBelongsToRelation(); [$type, $id] = $this->getMorphs( - Str::snake($name), $type, $id + Casing::snake($name), $type, $id ); // If the type value is null it is probably safe to assume we're eager loading @@ -654,7 +656,7 @@ public function morphToMany($related, $name, $table = null, $foreignPivotKey = n $lastWord = array_pop($words); - $table = implode('', $words).Str::plural($lastWord); + $table = implode('', $words).StrGrammar::plural($lastWord); } return $this->newMorphToMany( @@ -752,7 +754,7 @@ public function joiningTable($related, $instance = null) // just sort the models and join them together to get the table name. $segments = [ $instance ? $instance->joiningTableSegment() - : Str::snake(class_basename($related)), + : Casing::snake(class_basename($related)), $this->joiningTableSegment(), ]; @@ -771,7 +773,7 @@ public function joiningTable($related, $instance = null) */ public function joiningTableSegment() { - return Str::snake(class_basename($this)); + return Casing::snake(class_basename($this)); } /** diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasUuids.php b/src/Illuminate/Database/Eloquent/Concerns/HasUuids.php index 0755befdc3e1..79a209b9c9f7 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasUuids.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasUuids.php @@ -3,6 +3,7 @@ namespace Illuminate\Database\Eloquent\Concerns; use Illuminate\Database\Eloquent\ModelNotFoundException; +use Illuminate\Support\PatternMatcher; use Illuminate\Support\Str; trait HasUuids @@ -49,11 +50,11 @@ public function newUniqueId() */ public function resolveRouteBindingQuery($query, $value, $field = null) { - if ($field && in_array($field, $this->uniqueIds()) && ! Str::isUuid($value)) { + if ($field && in_array($field, $this->uniqueIds()) && ! PatternMatcher::isUuid($value)) { throw (new ModelNotFoundException)->setModel(get_class($this), $value); } - if (! $field && in_array($this->getRouteKeyName(), $this->uniqueIds()) && ! Str::isUuid($value)) { + if (! $field && in_array($this->getRouteKeyName(), $this->uniqueIds()) && ! PatternMatcher::isUuid($value)) { throw (new ModelNotFoundException)->setModel(get_class($this), $value); } diff --git a/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php b/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php index 37cb55fe36c7..50d6b3979d46 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php +++ b/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php @@ -564,7 +564,7 @@ public function whereBelongsTo($related, $relationshipName = null, $boolean = 'a } if ($relationshipName === null) { - $relationshipName = Str::camel(class_basename($related)); + $relationshipName = Casing::camel(class_basename($related)); } try { @@ -675,7 +675,7 @@ public function withAggregate($relations, $column, $function = null) // Finally, we will make the proper column alias to the query and run this sub-select on // the query builder. Then, we will return the builder instance back to the developer // for further constraint chaining that needs to take place on the query as needed. - $alias ??= Str::snake( + $alias ??= Casing::snake( preg_replace('/[^[:alnum:][:space:]_]/u', '', "$name $function {$this->getQuery()->getGrammar()->getValue($column)}") ); diff --git a/src/Illuminate/Database/Eloquent/Factories/Factory.php b/src/Illuminate/Database/Eloquent/Factories/Factory.php index 64d641617478..23fc945ed2cb 100644 --- a/src/Illuminate/Database/Eloquent/Factories/Factory.php +++ b/src/Illuminate/Database/Eloquent/Factories/Factory.php @@ -10,9 +10,12 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Support\Carbon; +use Illuminate\Support\Casing; use Illuminate\Support\Collection; use Illuminate\Support\Enumerable; +use Illuminate\Support\Replacer; use Illuminate\Support\Str; +use Illuminate\Support\StrGrammar; use Illuminate\Support\Traits\Conditionable; use Illuminate\Support\Traits\ForwardsCalls; use Illuminate\Support\Traits\Macroable; @@ -587,9 +590,9 @@ public function has(self $factory, $relationship = null) */ protected function guessRelationship(string $related) { - $guess = Str::camel(Str::plural(class_basename($related))); + $guess = Casing::camel(StrGrammar::plural(class_basename($related))); - return method_exists($this->modelName(), $guess) ? $guess : Str::singular($guess); + return method_exists($this->modelName(), $guess) ? $guess : StrGrammar::singular($guess); } /** @@ -606,7 +609,7 @@ public function hasAttached($factory, $pivot = [], $relationship = null) 'has' => $this->has->concat([new BelongsToManyRelationship( $factory, $pivot, - $relationship ?? Str::camel(Str::plural(class_basename( + $relationship ?? Casing::camel(StrGrammar::plural(class_basename( $factory instanceof Factory ? $factory->modelName() : Collection::wrap($factory)->first() @@ -626,7 +629,7 @@ public function for($factory, $relationship = null) { return $this->newInstance(['for' => $this->for->concat([new BelongsToRelationship( $factory, - $relationship ?? Str::camel(class_basename( + $relationship ?? Casing::camel(class_basename( $factory instanceof Factory ? $factory->modelName() : $factory )) )])]); @@ -780,11 +783,11 @@ public function newModel(array $attributes = []) public function modelName() { $resolver = static::$modelNameResolver ?? function (self $factory) { - $namespacedFactoryBasename = Str::replaceLast( - 'Factory', '', Str::replaceFirst(static::$namespace, '', get_class($factory)) + $namespacedFactoryBasename = Replacer::replaceLast( + 'Factory', '', Replacer::replaceFirst(static::$namespace, '', get_class($factory)) ); - $factoryBasename = Str::replaceLast('Factory', '', class_basename($factory)); + $factoryBasename = Replacer::replaceLast('Factory', '', class_basename($factory)); $appNamespace = static::appNamespace(); @@ -916,7 +919,7 @@ public function __call($method, $parameters) static::throwBadMethodCallException($method); } - $relationship = Str::camel(Str::substr($method, 3)); + $relationship = Casing::camel(Str::substr($method, 3)); $relatedModel = get_class($this->newModel()->{$relationship}()->getRelated()); diff --git a/src/Illuminate/Database/Eloquent/Model.php b/src/Illuminate/Database/Eloquent/Model.php index 7afa59933416..3bc8e728aa5d 100644 --- a/src/Illuminate/Database/Eloquent/Model.php +++ b/src/Illuminate/Database/Eloquent/Model.php @@ -17,8 +17,10 @@ use Illuminate\Database\Eloquent\Relations\HasManyThrough; use Illuminate\Database\Eloquent\Relations\Pivot; use Illuminate\Support\Arr; +use Illuminate\Support\Casing; use Illuminate\Support\Collection as BaseCollection; use Illuminate\Support\Str; +use Illuminate\Support\StrGrammar; use Illuminate\Support\Traits\ForwardsCalls; use JsonException; use JsonSerializable; @@ -1888,7 +1890,7 @@ public static function unsetConnectionResolver() */ public function getTable() { - return $this->table ?? Str::snake(Str::pluralStudly(class_basename($this))); + return $this->table ?? Casing::snake(StrGrammar::pluralStudly(class_basename($this))); } /** @@ -2149,7 +2151,7 @@ protected function resolveChildRouteBindingQuery($childType, $value, $field) */ protected function childRouteBindingRelationshipName($childType) { - return Str::plural(Str::camel($childType)); + return StrGrammar::plural(Casing::camel($childType)); } /** @@ -2172,7 +2174,7 @@ public function resolveRouteBindingQuery($query, $value, $field = null) */ public function getForeignKey() { - return Str::snake(class_basename($this)).'_'.$this->getKeyName(); + return Casing::snake(class_basename($this)).'_'.$this->getKeyName(); } /** @@ -2235,7 +2237,7 @@ public static function preventsAccessingMissingAttributes() */ public function broadcastChannelRoute() { - return str_replace('\\', '.', get_class($this)).'.{'.Str::camel(class_basename($this)).'}'; + return str_replace('\\', '.', get_class($this)).'.{'.Casing::camel(class_basename($this)).'}'; } /** diff --git a/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php b/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php index 121abb5b026c..14cd315bf91b 100755 --- a/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php +++ b/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php @@ -13,7 +13,9 @@ use Illuminate\Database\Eloquent\Relations\Concerns\InteractsWithPivotTable; use Illuminate\Database\Query\Grammars\MySqlGrammar; use Illuminate\Database\UniqueConstraintViolationException; +use Illuminate\Support\Casing; use Illuminate\Support\Str; +use Illuminate\Support\StrGrammar; use InvalidArgumentException; /** @@ -1227,7 +1229,7 @@ protected function touchingParent() */ protected function guessInverseRelation() { - return Str::camel(Str::pluralStudly(class_basename($this->getParent()))); + return Casing::camel(StrGrammar::pluralStudly(class_basename($this->getParent()))); } /** diff --git a/src/Illuminate/Database/Eloquent/Relations/Concerns/AsPivot.php b/src/Illuminate/Database/Eloquent/Relations/Concerns/AsPivot.php index ac2411f806c6..648b678d3ac0 100644 --- a/src/Illuminate/Database/Eloquent/Relations/Concerns/AsPivot.php +++ b/src/Illuminate/Database/Eloquent/Relations/Concerns/AsPivot.php @@ -3,7 +3,9 @@ namespace Illuminate\Database\Eloquent\Relations\Concerns; use Illuminate\Database\Eloquent\Model; +use Illuminate\Support\Casing; use Illuminate\Support\Str; +use Illuminate\Support\StrGrammar; trait AsPivot { @@ -161,7 +163,7 @@ public function getTable() { if (! isset($this->table)) { $this->setTable(str_replace( - '\\', '', Str::snake(Str::singular(class_basename($this))) + '\\', '', Casing::snake(StrGrammar::singular(class_basename($this))) )); } diff --git a/src/Illuminate/Database/Eloquent/Relations/Concerns/SupportsInverseRelations.php b/src/Illuminate/Database/Eloquent/Relations/Concerns/SupportsInverseRelations.php index 6fd76ec0cae4..0d5a0ede29be 100644 --- a/src/Illuminate/Database/Eloquent/Relations/Concerns/SupportsInverseRelations.php +++ b/src/Illuminate/Database/Eloquent/Relations/Concerns/SupportsInverseRelations.php @@ -5,6 +5,7 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\RelationNotFoundException; use Illuminate\Support\Arr; +use Illuminate\Support\Casing; use Illuminate\Support\Str; trait SupportsInverseRelations @@ -77,9 +78,9 @@ protected function guessInverseRelation(): string|null protected function getPossibleInverseRelations(): array { return array_filter(array_unique([ - Str::camel(Str::beforeLast($this->getForeignKeyName(), $this->getParent()->getKeyName())), - Str::camel(Str::beforeLast($this->getParent()->getForeignKey(), $this->getParent()->getKeyName())), - Str::camel(class_basename($this->getParent())), + Casing::camel(Str::beforeLast($this->getForeignKeyName(), $this->getParent()->getKeyName())), + Casing::camel(Str::beforeLast($this->getParent()->getForeignKey(), $this->getParent()->getKeyName())), + Casing::camel(class_basename($this->getParent())), 'owner', get_class($this->getParent()) === get_class($this->getModel()) ? 'parent' : null, ])); diff --git a/src/Illuminate/Database/Migrations/MigrationCreator.php b/src/Illuminate/Database/Migrations/MigrationCreator.php index d8f1ce9d0b1e..37fb43060da7 100755 --- a/src/Illuminate/Database/Migrations/MigrationCreator.php +++ b/src/Illuminate/Database/Migrations/MigrationCreator.php @@ -4,6 +4,7 @@ use Closure; use Illuminate\Filesystem\Filesystem; +use Illuminate\Support\Casing; use Illuminate\Support\Str; use InvalidArgumentException; @@ -159,7 +160,7 @@ protected function populateStub($stub, $table) */ protected function getClassName($name) { - return Str::studly($name); + return Casing::studly($name); } /** diff --git a/src/Illuminate/Database/Migrations/Migrator.php b/src/Illuminate/Database/Migrations/Migrator.php index ef500b5bee24..c80b37ef42e7 100755 --- a/src/Illuminate/Database/Migrations/Migrator.php +++ b/src/Illuminate/Database/Migrations/Migrator.php @@ -15,6 +15,7 @@ use Illuminate\Database\Events\NoPendingMigrations; use Illuminate\Filesystem\Filesystem; use Illuminate\Support\Arr; +use Illuminate\Support\Casing; use Illuminate\Support\Collection; use Illuminate\Support\Str; use ReflectionClass; @@ -524,7 +525,7 @@ protected function resolvePath(string $path) */ protected function getMigrationClass(string $migrationName): string { - return Str::studly(implode('_', array_slice(explode('_', $migrationName), 4))); + return Casing::studly(implode('_', array_slice(explode('_', $migrationName), 4))); } /** diff --git a/src/Illuminate/Database/Query/Builder.php b/src/Illuminate/Database/Query/Builder.php index bf2831bce5a2..08095503df7b 100755 --- a/src/Illuminate/Database/Query/Builder.php +++ b/src/Illuminate/Database/Query/Builder.php @@ -19,6 +19,7 @@ use Illuminate\Database\Query\Processors\Processor; use Illuminate\Pagination\Paginator; use Illuminate\Support\Arr; +use Illuminate\Support\Casing; use Illuminate\Support\Collection; use Illuminate\Support\LazyCollection; use Illuminate\Support\Str; @@ -2241,7 +2242,7 @@ protected function addDynamic($segment, $connector, $parameters, $index) // clause on the query. Then we'll increment the parameter index values. $bool = strtolower($connector); - $this->where(Str::snake($segment), '=', $parameters[$index], $bool); + $this->where(Casing::snake($segment), '=', $parameters[$index], $bool); } /** diff --git a/src/Illuminate/Database/Query/Grammars/MySqlGrammar.php b/src/Illuminate/Database/Query/Grammars/MySqlGrammar.php index f2823fd8e8d8..4384b6e1ba5f 100755 --- a/src/Illuminate/Database/Query/Grammars/MySqlGrammar.php +++ b/src/Illuminate/Database/Query/Grammars/MySqlGrammar.php @@ -4,6 +4,7 @@ use Illuminate\Database\Query\Builder; use Illuminate\Database\Query\JoinLateralClause; +use Illuminate\Support\Replacer; use Illuminate\Support\Str; class MySqlGrammar extends Grammar @@ -196,7 +197,7 @@ protected function compileLegacyGroupLimit(Builder $query) */ public function compileInsertOrIgnore(Builder $query, array $values) { - return Str::replaceFirst('insert', 'insert ignore', $this->compileInsert($query, $values)); + return Replacer::replaceFirst('insert', 'insert ignore', $this->compileInsert($query, $values)); } /** @@ -209,7 +210,7 @@ public function compileInsertOrIgnore(Builder $query, array $values) */ public function compileInsertOrIgnoreUsing(Builder $query, array $columns, string $sql) { - return Str::replaceFirst('insert', 'insert ignore', $this->compileInsertUsing($query, $columns, $sql)); + return Replacer::replaceFirst('insert', 'insert ignore', $this->compileInsertUsing($query, $columns, $sql)); } /** diff --git a/src/Illuminate/Database/Query/Grammars/SQLiteGrammar.php b/src/Illuminate/Database/Query/Grammars/SQLiteGrammar.php index 5b9e9761f381..9e998ab7e2ec 100755 --- a/src/Illuminate/Database/Query/Grammars/SQLiteGrammar.php +++ b/src/Illuminate/Database/Query/Grammars/SQLiteGrammar.php @@ -4,6 +4,7 @@ use Illuminate\Database\Query\Builder; use Illuminate\Support\Arr; +use Illuminate\Support\Replacer; use Illuminate\Support\Str; class SQLiteGrammar extends Grammar @@ -261,7 +262,7 @@ public function compileUpdate(Builder $query, array $values) */ public function compileInsertOrIgnore(Builder $query, array $values) { - return Str::replaceFirst('insert', 'insert or ignore', $this->compileInsert($query, $values)); + return Replacer::replaceFirst('insert', 'insert or ignore', $this->compileInsert($query, $values)); } /** @@ -274,7 +275,7 @@ public function compileInsertOrIgnore(Builder $query, array $values) */ public function compileInsertOrIgnoreUsing(Builder $query, array $columns, string $sql) { - return Str::replaceFirst('insert', 'insert or ignore', $this->compileInsertUsing($query, $columns, $sql)); + return Replacer::replaceFirst('insert', 'insert or ignore', $this->compileInsertUsing($query, $columns, $sql)); } /** diff --git a/src/Illuminate/Database/Query/Grammars/SqlServerGrammar.php b/src/Illuminate/Database/Query/Grammars/SqlServerGrammar.php index 9d42682a5384..25ba0f98d0a7 100755 --- a/src/Illuminate/Database/Query/Grammars/SqlServerGrammar.php +++ b/src/Illuminate/Database/Query/Grammars/SqlServerGrammar.php @@ -5,6 +5,7 @@ use Illuminate\Database\Query\Builder; use Illuminate\Database\Query\JoinLateralClause; use Illuminate\Support\Arr; +use Illuminate\Support\Replacer; use Illuminate\Support\Str; class SqlServerGrammar extends Grammar @@ -280,7 +281,7 @@ protected function compileDeleteWithoutJoins(Builder $query, $table, $where) $sql = parent::compileDeleteWithoutJoins($query, $table, $where); return ! is_null($query->limit) && $query->limit > 0 && $query->offset <= 0 - ? Str::replaceFirst('delete', 'delete top ('.$query->limit.')', $sql) + ? Replacer::replaceFirst('delete', 'delete top ('.$query->limit.')', $sql) : $sql; } diff --git a/src/Illuminate/Database/QueryException.php b/src/Illuminate/Database/QueryException.php index 84aebb1a670b..743d3122da10 100644 --- a/src/Illuminate/Database/QueryException.php +++ b/src/Illuminate/Database/QueryException.php @@ -2,6 +2,7 @@ namespace Illuminate\Database; +use Illuminate\Support\Replacer; use Illuminate\Support\Str; use PDOException; use Throwable; @@ -64,7 +65,7 @@ public function __construct($connectionName, $sql, array $bindings, Throwable $p */ protected function formatMessage($connectionName, $sql, $bindings, Throwable $previous) { - return $previous->getMessage().' (Connection: '.$connectionName.', SQL: '.Str::replaceArray('?', $bindings, $sql).')'; + return $previous->getMessage().' (Connection: '.$connectionName.', SQL: '.Replacer::replaceArray('?', $bindings, $sql).')'; } /** diff --git a/src/Illuminate/Events/Dispatcher.php b/src/Illuminate/Events/Dispatcher.php index 30860a39d1bc..003a64291005 100755 --- a/src/Illuminate/Events/Dispatcher.php +++ b/src/Illuminate/Events/Dispatcher.php @@ -15,6 +15,7 @@ use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Contracts\Queue\ShouldQueueAfterCommit; use Illuminate\Support\Arr; +use Illuminate\Support\PatternMatcher; use Illuminate\Support\Str; use Illuminate\Support\Traits\Macroable; use Illuminate\Support\Traits\ReflectsClosures; @@ -145,7 +146,7 @@ public function hasListeners($eventName) public function hasWildcardListeners($eventName) { foreach ($this->wildcards as $key => $listeners) { - if (Str::is($key, $eventName)) { + if (PatternMatcher::is($key, $eventName)) { return true; } } @@ -386,7 +387,7 @@ protected function getWildcardListeners($eventName) $wildcards = []; foreach ($this->wildcards as $key => $listeners) { - if (Str::is($key, $eventName)) { + if (PatternMatcher::is($key, $eventName)) { foreach ($listeners as $listener) { $wildcards[] = $this->makeListener($listener, true); } @@ -699,7 +700,7 @@ public function forget($event) } foreach ($this->wildcardsCache as $key => $listeners) { - if (Str::is($event, $key)) { + if (PatternMatcher::is($event, $key)) { unset($this->wildcardsCache[$key]); } } diff --git a/src/Illuminate/Filesystem/FilesystemAdapter.php b/src/Illuminate/Filesystem/FilesystemAdapter.php index e4a90420dc1e..956757383224 100644 --- a/src/Illuminate/Filesystem/FilesystemAdapter.php +++ b/src/Illuminate/Filesystem/FilesystemAdapter.php @@ -9,6 +9,7 @@ use Illuminate\Http\Request; use Illuminate\Http\UploadedFile; use Illuminate\Support\Arr; +use Illuminate\Support\Replacer; use Illuminate\Support\Str; use Illuminate\Support\Traits\Conditionable; use Illuminate\Support\Traits\Macroable; @@ -734,7 +735,7 @@ protected function getLocalUrl($path) // the default disk to generate the path instead of the "public" disk like they // are really supposed to use. We will remove the public from this path here. if (str_contains($path, '/storage/public/')) { - return Str::replaceFirst('/public/', '/', $path); + return Replacer::replaceFirst('/public/', '/', $path); } return $path; diff --git a/src/Illuminate/Foundation/Application.php b/src/Illuminate/Foundation/Application.php index 113c31e70b4c..216856d84adf 100755 --- a/src/Illuminate/Foundation/Application.php +++ b/src/Illuminate/Foundation/Application.php @@ -22,6 +22,7 @@ use Illuminate\Support\Arr; use Illuminate\Support\Collection; use Illuminate\Support\Env; +use Illuminate\Support\PatternMatcher; use Illuminate\Support\ServiceProvider; use Illuminate\Support\Str; use Illuminate\Support\Traits\Macroable; @@ -725,7 +726,7 @@ public function environment(...$environments) if (count($environments) > 0) { $patterns = is_array($environments[0]) ? $environments[0] : $environments; - return Str::is($patterns, $this['env']); + return PatternMatcher::is($patterns, $this['env']); } return $this['env']; diff --git a/src/Illuminate/Foundation/Auth/Access/AuthorizesRequests.php b/src/Illuminate/Foundation/Auth/Access/AuthorizesRequests.php index 19dc16416746..f1b474774ab6 100644 --- a/src/Illuminate/Foundation/Auth/Access/AuthorizesRequests.php +++ b/src/Illuminate/Foundation/Auth/Access/AuthorizesRequests.php @@ -3,6 +3,7 @@ namespace Illuminate\Foundation\Auth\Access; use Illuminate\Contracts\Auth\Access\Gate; +use Illuminate\Support\Casing; use Illuminate\Support\Str; trait AuthorizesRequests @@ -86,7 +87,7 @@ public function authorizeResource($model, $parameter = null, array $options = [] $parameter = is_array($parameter) ? implode(',', $parameter) : $parameter; - $parameter = $parameter ?: Str::snake(class_basename($model)); + $parameter = $parameter ?: Casing::snake(class_basename($model)); $middleware = []; diff --git a/src/Illuminate/Foundation/Console/ComponentMakeCommand.php b/src/Illuminate/Foundation/Console/ComponentMakeCommand.php index faf863285c72..5402aa827492 100644 --- a/src/Illuminate/Foundation/Console/ComponentMakeCommand.php +++ b/src/Illuminate/Foundation/Console/ComponentMakeCommand.php @@ -5,6 +5,7 @@ use Illuminate\Console\Concerns\CreatesMatchingTest; use Illuminate\Console\GeneratorCommand; use Illuminate\Foundation\Inspiring; +use Illuminate\Support\Casing; use Illuminate\Support\Str; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputOption; @@ -130,7 +131,7 @@ protected function getView() $path[] = $name; return collect($path) - ->map(fn ($segment) => Str::kebab($segment)) + ->map(fn ($segment) => Casing::kebab($segment)) ->implode('.'); } diff --git a/src/Illuminate/Foundation/Console/DownCommand.php b/src/Illuminate/Foundation/Console/DownCommand.php index 86b2c2841375..b15bcc1d6c9c 100644 --- a/src/Illuminate/Foundation/Console/DownCommand.php +++ b/src/Illuminate/Foundation/Console/DownCommand.php @@ -7,6 +7,7 @@ use Illuminate\Console\Command; use Illuminate\Foundation\Events\MaintenanceModeEnabled; use Illuminate\Foundation\Exceptions\RegisterErrorViewPaths; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use Symfony\Component\Console\Attribute\AsCommand; use Throwable; @@ -155,7 +156,7 @@ protected function getSecret() { return match (true) { ! is_null($this->option('secret')) => $this->option('secret'), - $this->option('with-secret') => Str::random(), + $this->option('with-secret') => Generator::random(), default => null, }; } diff --git a/src/Illuminate/Foundation/Console/MailMakeCommand.php b/src/Illuminate/Foundation/Console/MailMakeCommand.php index 2ec59a15d5a1..efcc8381721d 100644 --- a/src/Illuminate/Foundation/Console/MailMakeCommand.php +++ b/src/Illuminate/Foundation/Console/MailMakeCommand.php @@ -5,6 +5,7 @@ use Illuminate\Console\Concerns\CreatesMatchingTest; use Illuminate\Console\GeneratorCommand; use Illuminate\Foundation\Inspiring; +use Illuminate\Support\Casing; use Illuminate\Support\Str; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputInterface; @@ -111,7 +112,7 @@ protected function buildClass($name) { $class = str_replace( '{{ subject }}', - Str::headline(str_replace($this->getNamespace($name).'\\', '', $name)), + Casing::headline(str_replace($this->getNamespace($name).'\\', '', $name)), parent::buildClass($name) ); @@ -135,7 +136,7 @@ protected function getView() $name = str_replace('\\', '/', $this->argument('name')); $view = 'mail.'.collect(explode('/', $name)) - ->map(fn ($part) => Str::kebab($part)) + ->map(fn ($part) => Casing::kebab($part)) ->implode('.'); } diff --git a/src/Illuminate/Foundation/Console/ModelMakeCommand.php b/src/Illuminate/Foundation/Console/ModelMakeCommand.php index f4b4bd66df9e..5ef1ccaea5a3 100644 --- a/src/Illuminate/Foundation/Console/ModelMakeCommand.php +++ b/src/Illuminate/Foundation/Console/ModelMakeCommand.php @@ -4,7 +4,9 @@ use Illuminate\Console\Concerns\CreatesMatchingTest; use Illuminate\Console\GeneratorCommand; +use Illuminate\Support\Casing; use Illuminate\Support\Str; +use Illuminate\Support\StrGrammar; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; @@ -86,7 +88,7 @@ public function handle() */ protected function createFactory() { - $factory = Str::studly($this->argument('name')); + $factory = Casing::studly($this->argument('name')); $this->call('make:factory', [ 'name' => "{$factory}Factory", @@ -101,10 +103,10 @@ protected function createFactory() */ protected function createMigration() { - $table = Str::snake(Str::pluralStudly(class_basename($this->argument('name')))); + $table = Casing::snake(StrGrammar::pluralStudly(class_basename($this->argument('name')))); if ($this->option('pivot')) { - $table = Str::singular($table); + $table = StrGrammar::singular($table); } $this->call('make:migration', [ @@ -120,7 +122,7 @@ protected function createMigration() */ protected function createSeeder() { - $seeder = Str::studly(class_basename($this->argument('name'))); + $seeder = Casing::studly(class_basename($this->argument('name'))); $this->call('make:seeder', [ 'name' => "{$seeder}Seeder", @@ -134,7 +136,7 @@ protected function createSeeder() */ protected function createController() { - $controller = Str::studly(class_basename($this->argument('name'))); + $controller = Casing::studly(class_basename($this->argument('name'))); $modelName = $this->qualifyClass($this->getNameInput()); @@ -155,7 +157,7 @@ protected function createController() */ protected function createPolicy() { - $policy = Str::studly(class_basename($this->argument('name'))); + $policy = Casing::studly(class_basename($this->argument('name'))); $this->call('make:policy', [ 'name' => "{$policy}Policy", diff --git a/src/Illuminate/Foundation/Console/NotificationMakeCommand.php b/src/Illuminate/Foundation/Console/NotificationMakeCommand.php index d6105af9192f..7f93aee179c1 100644 --- a/src/Illuminate/Foundation/Console/NotificationMakeCommand.php +++ b/src/Illuminate/Foundation/Console/NotificationMakeCommand.php @@ -4,6 +4,7 @@ use Illuminate\Console\Concerns\CreatesMatchingTest; use Illuminate\Console\GeneratorCommand; +use Illuminate\Support\Casing; use Illuminate\Support\Str; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputInterface; @@ -145,7 +146,7 @@ protected function afterPromptingForMissingArguments(InputInterface $input, Outp if ($wantsMarkdownView) { $defaultMarkdownView = collect(explode('/', str_replace('\\', '/', $this->argument('name')))) - ->map(fn ($path) => Str::kebab($path)) + ->map(fn ($path) => Casing::kebab($path)) ->prepend('mail') ->implode('.'); diff --git a/src/Illuminate/Foundation/Console/PolicyMakeCommand.php b/src/Illuminate/Foundation/Console/PolicyMakeCommand.php index a48eefe2c30d..fb1b307458ee 100644 --- a/src/Illuminate/Foundation/Console/PolicyMakeCommand.php +++ b/src/Illuminate/Foundation/Console/PolicyMakeCommand.php @@ -3,6 +3,7 @@ namespace Illuminate\Foundation\Console; use Illuminate\Console\GeneratorCommand; +use Illuminate\Support\Casing; use Illuminate\Support\Str; use LogicException; use Symfony\Component\Console\Attribute\AsCommand; @@ -121,7 +122,7 @@ protected function replaceModel($stub, $model) $dummyUser = class_basename($this->userProviderModel()); - $dummyModel = Str::camel($model) === 'user' ? 'model' : $model; + $dummyModel = Casing::camel($model) === 'user' ? 'model' : $model; $replace = [ 'NamespacedDummyModel' => $namespacedModel, @@ -130,13 +131,13 @@ protected function replaceModel($stub, $model) 'DummyModel' => $model, '{{ model }}' => $model, '{{model}}' => $model, - 'dummyModel' => Str::camel($dummyModel), - '{{ modelVariable }}' => Str::camel($dummyModel), - '{{modelVariable}}' => Str::camel($dummyModel), + 'dummyModel' => Casing::camel($dummyModel), + '{{ modelVariable }}' => Casing::camel($dummyModel), + '{{modelVariable}}' => Casing::camel($dummyModel), 'DummyUser' => $dummyUser, '{{ user }}' => $dummyUser, '{{user}}' => $dummyUser, - '$user' => '$'.Str::camel($dummyUser), + '$user' => '$'.Casing::camel($dummyUser), ]; $stub = str_replace( diff --git a/src/Illuminate/Foundation/Console/TestMakeCommand.php b/src/Illuminate/Foundation/Console/TestMakeCommand.php index 85440589f52d..6f5e8260ae8b 100644 --- a/src/Illuminate/Foundation/Console/TestMakeCommand.php +++ b/src/Illuminate/Foundation/Console/TestMakeCommand.php @@ -3,6 +3,7 @@ namespace Illuminate\Foundation\Console; use Illuminate\Console\GeneratorCommand; +use Illuminate\Support\Replacer; use Illuminate\Support\Str; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputInterface; @@ -70,7 +71,7 @@ protected function resolveStubPath($stub) */ protected function getPath($name) { - $name = Str::replaceFirst($this->rootNamespace(), '', $name); + $name = Replacer::replaceFirst($this->rootNamespace(), '', $name); return base_path('tests').str_replace('\\', '/', $name).'.php'; } diff --git a/src/Illuminate/Foundation/Events/DiscoverEvents.php b/src/Illuminate/Foundation/Events/DiscoverEvents.php index a4728c2ef3ed..fd6d7414e026 100644 --- a/src/Illuminate/Foundation/Events/DiscoverEvents.php +++ b/src/Illuminate/Foundation/Events/DiscoverEvents.php @@ -2,7 +2,9 @@ namespace Illuminate\Foundation\Events; +use Illuminate\Support\PatternMatcher; use Illuminate\Support\Reflector; +use Illuminate\Support\Replacer; use Illuminate\Support\Str; use ReflectionClass; use ReflectionException; @@ -72,7 +74,7 @@ protected static function getListenerEvents($listeners, $basePath) } foreach ($listener->getMethods(ReflectionMethod::IS_PUBLIC) as $method) { - if ((! Str::is('handle*', $method->name) && ! Str::is('__invoke', $method->name)) || + if ((! PatternMatcher::is('handle*', $method->name) && ! PatternMatcher::is('__invoke', $method->name)) || ! isset($method->getParameters()[0])) { continue; } @@ -98,12 +100,12 @@ protected static function classFromFile(SplFileInfo $file, $basePath) return call_user_func(static::$guessClassNamesUsingCallback, $file, $basePath); } - $class = trim(Str::replaceFirst($basePath, '', $file->getRealPath()), DIRECTORY_SEPARATOR); + $class = trim(Replacer::replaceFirst($basePath, '', $file->getRealPath()), DIRECTORY_SEPARATOR); return str_replace( [DIRECTORY_SEPARATOR, ucfirst(basename(app()->path())).'\\'], ['\\', app()->getNamespace()], - ucfirst(Str::replaceLast('.php', '', $class)) + ucfirst(Replacer::replaceLast('.php', '', $class)) ); } diff --git a/src/Illuminate/Foundation/Http/Middleware/TrimStrings.php b/src/Illuminate/Foundation/Http/Middleware/TrimStrings.php index 80be7a476e90..abe70921efc5 100644 --- a/src/Illuminate/Foundation/Http/Middleware/TrimStrings.php +++ b/src/Illuminate/Foundation/Http/Middleware/TrimStrings.php @@ -4,6 +4,7 @@ use Closure; use Illuminate\Support\Arr; +use Illuminate\Support\Sanitizer; use Illuminate\Support\Str; class TrimStrings extends TransformsRequest @@ -66,7 +67,7 @@ protected function transform($key, $value) return $value; } - return Str::trim($value); + return Sanitizer::trim($value); } /** diff --git a/src/Illuminate/Foundation/Vite.php b/src/Illuminate/Foundation/Vite.php index 7922f8309253..d85841d37c9f 100644 --- a/src/Illuminate/Foundation/Vite.php +++ b/src/Illuminate/Foundation/Vite.php @@ -4,6 +4,7 @@ use Illuminate\Contracts\Support\Htmlable; use Illuminate\Support\Collection; +use Illuminate\Support\Generator; use Illuminate\Support\HtmlString; use Illuminate\Support\Js; use Illuminate\Support\Str; @@ -146,7 +147,7 @@ public function cspNonce() */ public function useCspNonce($nonce = null) { - return $this->nonce = $nonce ?? Str::random(40); + return $this->nonce = $nonce ?? Generator::random(40); } /** diff --git a/src/Illuminate/Http/Client/Factory.php b/src/Illuminate/Http/Client/Factory.php index b6679f200671..c5bca0c40e88 100644 --- a/src/Illuminate/Http/Client/Factory.php +++ b/src/Illuminate/Http/Client/Factory.php @@ -9,6 +9,7 @@ use GuzzleHttp\Psr7\Response as Psr7Response; use GuzzleHttp\TransferStats; use Illuminate\Contracts\Events\Dispatcher; +use Illuminate\Support\PatternMatcher; use Illuminate\Support\Str; use Illuminate\Support\Traits\Macroable; use PHPUnit\Framework\Assert as PHPUnit; @@ -244,7 +245,7 @@ public function fakeSequence($url = '*') public function stubUrl($url, $callback) { return $this->fake(function ($request, $options) use ($url, $callback) { - if (! Str::is(Str::start($url, '*'), $request->url())) { + if (! PatternMatcher::is(Str::start($url, '*'), $request->url())) { return; } diff --git a/src/Illuminate/Http/FileHelpers.php b/src/Illuminate/Http/FileHelpers.php index 72d562b98f7a..ede4b4a55c47 100644 --- a/src/Illuminate/Http/FileHelpers.php +++ b/src/Illuminate/Http/FileHelpers.php @@ -2,6 +2,7 @@ namespace Illuminate\Http; +use Illuminate\Support\Generator; use Illuminate\Support\Str; trait FileHelpers @@ -45,7 +46,7 @@ public function hashName($path = null) $path = rtrim($path, '/').'/'; } - $hash = $this->hashName ?: $this->hashName = Str::random(40); + $hash = $this->hashName ?: $this->hashName = Generator::random(40); if ($extension = $this->guessExtension()) { $extension = '.'.$extension; diff --git a/src/Illuminate/Http/RedirectResponse.php b/src/Illuminate/Http/RedirectResponse.php index 5c506ba6b00b..54c6e587084a 100755 --- a/src/Illuminate/Http/RedirectResponse.php +++ b/src/Illuminate/Http/RedirectResponse.php @@ -4,6 +4,7 @@ use Illuminate\Contracts\Support\MessageProvider; use Illuminate\Session\Store as SessionStore; +use Illuminate\Support\Casing; use Illuminate\Support\MessageBag; use Illuminate\Support\Str; use Illuminate\Support\Traits\ForwardsCalls; @@ -250,7 +251,7 @@ public function __call($method, $parameters) } if (str_starts_with($method, 'with')) { - return $this->with(Str::snake(substr($method, 4)), $parameters[0]); + return $this->with(Casing::snake(substr($method, 4)), $parameters[0]); } static::throwBadMethodCallException($method); diff --git a/src/Illuminate/Http/Request.php b/src/Illuminate/Http/Request.php index 55c0d9c447d2..3aaa4fb4d877 100644 --- a/src/Illuminate/Http/Request.php +++ b/src/Illuminate/Http/Request.php @@ -7,6 +7,7 @@ use Illuminate\Contracts\Support\Arrayable; use Illuminate\Session\SymfonySessionDecorator; use Illuminate\Support\Arr; +use Illuminate\Support\PatternMatcher; use Illuminate\Support\Str; use Illuminate\Support\Traits\Macroable; use RuntimeException; @@ -212,7 +213,7 @@ public function is(...$patterns) { $path = $this->decodedPath(); - return collect($patterns)->contains(fn ($pattern) => Str::is($pattern, $path)); + return collect($patterns)->contains(fn ($pattern) => PatternMatcher::is($pattern, $path)); } /** @@ -236,7 +237,7 @@ public function fullUrlIs(...$patterns) { $url = $this->fullUrl(); - return collect($patterns)->contains(fn ($pattern) => Str::is($pattern, $url)); + return collect($patterns)->contains(fn ($pattern) => PatternMatcher::is($pattern, $url)); } /** diff --git a/src/Illuminate/Http/Resources/CollectsResources.php b/src/Illuminate/Http/Resources/CollectsResources.php index b84c34453908..f53331c8edeb 100644 --- a/src/Illuminate/Http/Resources/CollectsResources.php +++ b/src/Illuminate/Http/Resources/CollectsResources.php @@ -6,6 +6,7 @@ use Illuminate\Pagination\AbstractCursorPaginator; use Illuminate\Pagination\AbstractPaginator; use Illuminate\Support\Collection; +use Illuminate\Support\Replacer; use Illuminate\Support\Str; use LogicException; use ReflectionClass; @@ -52,8 +53,8 @@ protected function collects() if ($this->collects) { $collects = $this->collects; } elseif (str_ends_with(class_basename($this), 'Collection') && - (class_exists($class = Str::replaceLast('Collection', '', get_class($this))) || - class_exists($class = Str::replaceLast('Collection', 'Resource', get_class($this))))) { + (class_exists($class = Replacer::replaceLast('Collection', '', get_class($this))) || + class_exists($class = Replacer::replaceLast('Collection', 'Resource', get_class($this))))) { $collects = $class; } diff --git a/src/Illuminate/Log/LogManager.php b/src/Illuminate/Log/LogManager.php index 954d1c2e7fdd..d4c386f6a33e 100644 --- a/src/Illuminate/Log/LogManager.php +++ b/src/Illuminate/Log/LogManager.php @@ -4,6 +4,7 @@ use Closure; use Illuminate\Log\Context\Repository as ContextRepository; +use Illuminate\Support\Casing; use Illuminate\Support\Str; use InvalidArgumentException; use Monolog\Formatter\LineFormatter; @@ -367,7 +368,7 @@ protected function createSyslogDriver(array $config) { return new Monolog($this->parseChannel($config), [ $this->prepareHandler(new SyslogHandler( - Str::snake($this->app['config']['app.name'], '-'), + Casing::snake($this->app['config']['app.name'], '-'), $config['facility'] ?? LOG_USER, $this->level($config) ), $config), ], $config['replace_placeholders'] ?? false ? [new PsrLogMessageProcessor()] : []); diff --git a/src/Illuminate/Mail/MailManager.php b/src/Illuminate/Mail/MailManager.php index a9b72f419834..d01469ad568a 100644 --- a/src/Illuminate/Mail/MailManager.php +++ b/src/Illuminate/Mail/MailManager.php @@ -13,6 +13,7 @@ use Illuminate\Mail\Transport\SesTransport; use Illuminate\Mail\Transport\SesV2Transport; use Illuminate\Support\Arr; +use Illuminate\Support\Casing; use Illuminate\Support\ConfigurationUrlParser; use Illuminate\Support\Str; use InvalidArgumentException; @@ -161,7 +162,7 @@ public function createSymfonyTransport(array $config) } if (trim($transport ?? '') === '' || - ! method_exists($this, $method = 'create'.ucfirst(Str::camel($transport)).'Transport')) { + ! method_exists($this, $method = 'create'.ucfirst(Casing::camel($transport)).'Transport')) { throw new InvalidArgumentException("Unsupported mail transport [{$transport}]."); } @@ -476,7 +477,7 @@ protected function setGlobalAddress($mailer, array $config, string $type) $address = Arr::get($config, $type, $this->app['config']['mail.'.$type]); if (is_array($address) && isset($address['address'])) { - $mailer->{'always'.Str::studly($type)}($address['address'], $address['name']); + $mailer->{'always'.Casing::studly($type)}($address['address'], $address['name']); } } diff --git a/src/Illuminate/Mail/Mailable.php b/src/Illuminate/Mail/Mailable.php index 48831c0e551a..ca68e3e6e944 100644 --- a/src/Illuminate/Mail/Mailable.php +++ b/src/Illuminate/Mail/Mailable.php @@ -12,9 +12,9 @@ use Illuminate\Contracts\Support\Htmlable; use Illuminate\Contracts\Support\Renderable; use Illuminate\Contracts\Translation\HasLocalePreference; +use Illuminate\Support\Casing; use Illuminate\Support\Collection; use Illuminate\Support\HtmlString; -use Illuminate\Support\Str; use Illuminate\Support\Traits\Conditionable; use Illuminate\Support\Traits\ForwardsCalls; use Illuminate\Support\Traits\Localizable; @@ -448,7 +448,7 @@ protected function buildSubject($message) if ($this->subject) { $message->subject($this->subject); } else { - $message->subject(Str::title(Str::snake(class_basename($this), ' '))); + $message->subject(Casing::title(Casing::snake(class_basename($this), ' '))); } return $this; @@ -1813,7 +1813,7 @@ public function __call($method, $parameters) } if (str_starts_with($method, 'with')) { - return $this->with(Str::camel(substr($method, 4)), $parameters[0]); + return $this->with(Casing::camel(substr($method, 4)), $parameters[0]); } static::throwBadMethodCallException($method); diff --git a/src/Illuminate/Mail/Message.php b/src/Illuminate/Mail/Message.php index 170b6bcd636e..11310f668e0b 100755 --- a/src/Illuminate/Mail/Message.php +++ b/src/Illuminate/Mail/Message.php @@ -3,6 +3,7 @@ namespace Illuminate\Mail; use Illuminate\Contracts\Mail\Attachable; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use Illuminate\Support\Traits\ForwardsCalls; use Symfony\Component\Mime\Address; @@ -344,7 +345,7 @@ public function embed($file) if ($file instanceof Attachment) { return $file->attachWith( function ($path) use ($file) { - $cid = $file->as ?? Str::random(); + $cid = $file->as ?? Generator::random(); $this->message->addPart( (new DataPart(new File($path), $cid, $file->mime))->asInline() @@ -362,7 +363,7 @@ function ($data) use ($file) { ); } - $cid = Str::random(10); + $cid = Generator::random(10); $this->message->addPart( (new DataPart(new File($file), $cid))->asInline() diff --git a/src/Illuminate/Notifications/Channels/MailChannel.php b/src/Illuminate/Notifications/Channels/MailChannel.php index 1b852e65c2d7..b095a7c697b1 100644 --- a/src/Illuminate/Notifications/Channels/MailChannel.php +++ b/src/Illuminate/Notifications/Channels/MailChannel.php @@ -10,7 +10,7 @@ use Illuminate\Mail\Markdown; use Illuminate\Notifications\Notification; use Illuminate\Support\Arr; -use Illuminate\Support\Str; +use Illuminate\Support\Casing; use Symfony\Component\Mailer\Header\MetadataHeader; use Symfony\Component\Mailer\Header\TagHeader; @@ -175,8 +175,8 @@ protected function buildMessage($mailMessage, $notifiable, $notification, $messa { $this->addressMessage($mailMessage, $notifiable, $notification, $message); - $mailMessage->subject($message->subject ?: Str::title( - Str::snake(class_basename($notification), ' ') + $mailMessage->subject($message->subject ?: Casing::title( + Casing::snake(class_basename($notification), ' ') )); $this->addAttachments($mailMessage, $message); diff --git a/src/Illuminate/Notifications/RoutesNotifications.php b/src/Illuminate/Notifications/RoutesNotifications.php index 2744f3161127..665a4313d540 100644 --- a/src/Illuminate/Notifications/RoutesNotifications.php +++ b/src/Illuminate/Notifications/RoutesNotifications.php @@ -3,6 +3,7 @@ namespace Illuminate\Notifications; use Illuminate\Contracts\Notifications\Dispatcher; +use Illuminate\Support\Casing; use Illuminate\Support\Str; trait RoutesNotifications @@ -39,7 +40,7 @@ public function notifyNow($instance, ?array $channels = null) */ public function routeNotificationFor($driver, $notification = null) { - if (method_exists($this, $method = 'routeNotificationFor'.Str::studly($driver))) { + if (method_exists($this, $method = 'routeNotificationFor'.Casing::studly($driver))) { return $this->{$method}($notification); } diff --git a/src/Illuminate/Process/PendingProcess.php b/src/Illuminate/Process/PendingProcess.php index 9c4dd7153fae..4a6f5cc30be5 100644 --- a/src/Illuminate/Process/PendingProcess.php +++ b/src/Illuminate/Process/PendingProcess.php @@ -4,6 +4,7 @@ use Closure; use Illuminate\Process\Exceptions\ProcessTimedOutException; +use Illuminate\Support\PatternMatcher; use Illuminate\Support\Str; use Illuminate\Support\Traits\Conditionable; use LogicException; @@ -350,7 +351,7 @@ public function withFakeHandlers(array $fakeHandlers) protected function fakeFor(string $command) { return collect($this->fakeHandlers) - ->first(fn ($handler, $pattern) => Str::is($pattern, $command)); + ->first(fn ($handler, $pattern) => PatternMatcher::is($pattern, $command)); } /** diff --git a/src/Illuminate/Queue/Console/ClearCommand.php b/src/Illuminate/Queue/Console/ClearCommand.php index 8f4187bcac77..6f0c93f853c4 100644 --- a/src/Illuminate/Queue/Console/ClearCommand.php +++ b/src/Illuminate/Queue/Console/ClearCommand.php @@ -6,6 +6,7 @@ use Illuminate\Console\ConfirmableTrait; use Illuminate\Contracts\Queue\ClearableQueue; use Illuminate\Support\Str; +use Illuminate\Support\StrGrammar; use ReflectionClass; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputArgument; @@ -54,7 +55,7 @@ public function handle() if ($queue instanceof ClearableQueue) { $count = $queue->clear($queueName); - $this->components->info('Cleared '.$count.' '.Str::plural('job', $count).' from the ['.$queueName.'] queue'); + $this->components->info('Cleared '.$count.' '.StrGrammar::plural('job', $count).' from the ['.$queueName.'] queue'); } else { $this->components->error('Clearing queues is not supported on ['.(new ReflectionClass($queue))->getShortName().']'); diff --git a/src/Illuminate/Queue/RedisQueue.php b/src/Illuminate/Queue/RedisQueue.php index 94602022e721..0f09ff8bb771 100644 --- a/src/Illuminate/Queue/RedisQueue.php +++ b/src/Illuminate/Queue/RedisQueue.php @@ -6,6 +6,7 @@ use Illuminate\Contracts\Queue\Queue as QueueContract; use Illuminate\Contracts\Redis\Factory as Redis; use Illuminate\Queue\Jobs\RedisJob; +use Illuminate\Support\Generator; use Illuminate\Support\Str; class RedisQueue extends Queue implements QueueContract, ClearableQueue @@ -345,7 +346,7 @@ public function clear($queue) */ protected function getRandomId() { - return Str::random(32); + return Generator::random(32); } /** diff --git a/src/Illuminate/Redis/Limiters/ConcurrencyLimiter.php b/src/Illuminate/Redis/Limiters/ConcurrencyLimiter.php index 62e50b01aad1..fb2221ac200d 100644 --- a/src/Illuminate/Redis/Limiters/ConcurrencyLimiter.php +++ b/src/Illuminate/Redis/Limiters/ConcurrencyLimiter.php @@ -3,6 +3,7 @@ namespace Illuminate\Redis\Limiters; use Illuminate\Contracts\Redis\LimiterTimeoutException; +use Illuminate\Support\Generator; use Illuminate\Support\Sleep; use Illuminate\Support\Str; use Throwable; @@ -69,7 +70,7 @@ public function block($timeout, $callback = null, $sleep = 250) { $starting = time(); - $id = Str::random(20); + $id = Generator::random(20); while (! $slot = $this->acquire($id)) { if (time() - $timeout >= $starting) { diff --git a/src/Illuminate/Routing/AbstractRouteCollection.php b/src/Illuminate/Routing/AbstractRouteCollection.php index d87441ea2f1b..41207709daec 100644 --- a/src/Illuminate/Routing/AbstractRouteCollection.php +++ b/src/Illuminate/Routing/AbstractRouteCollection.php @@ -6,6 +6,7 @@ use Countable; use Illuminate\Http\Request; use Illuminate\Http\Response; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use IteratorAggregate; use LogicException; @@ -259,7 +260,7 @@ protected function addToSymfonyRoutesCollection(SymfonyRouteCollection $symfonyR */ protected function generateRouteName() { - return 'generated::'.Str::random(); + return 'generated::'.Generator::random(); } /** diff --git a/src/Illuminate/Routing/Exceptions/UrlGenerationException.php b/src/Illuminate/Routing/Exceptions/UrlGenerationException.php index eadda8010c0f..bf53d455e14a 100644 --- a/src/Illuminate/Routing/Exceptions/UrlGenerationException.php +++ b/src/Illuminate/Routing/Exceptions/UrlGenerationException.php @@ -4,7 +4,7 @@ use Exception; use Illuminate\Routing\Route; -use Illuminate\Support\Str; +use Illuminate\Support\StrGrammar; class UrlGenerationException extends Exception { @@ -17,7 +17,7 @@ class UrlGenerationException extends Exception */ public static function forMissingParameters(Route $route, array $parameters = []) { - $parameterLabel = Str::plural('parameter', count($parameters)); + $parameterLabel = StrGrammar::plural('parameter', count($parameters)); $message = sprintf( 'Missing required %s for [Route: %s] [URI: %s]', diff --git a/src/Illuminate/Routing/ImplicitRouteBinding.php b/src/Illuminate/Routing/ImplicitRouteBinding.php index 7d92ec9757f9..13501a71f015 100644 --- a/src/Illuminate/Routing/ImplicitRouteBinding.php +++ b/src/Illuminate/Routing/ImplicitRouteBinding.php @@ -6,6 +6,7 @@ use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Routing\Exceptions\BackedEnumCaseNotFoundException; +use Illuminate\Support\Casing; use Illuminate\Support\Reflector; use Illuminate\Support\Str; @@ -117,7 +118,7 @@ protected static function getParameterName($name, $parameters) return $name; } - if (array_key_exists($snakedName = Str::snake($name), $parameters)) { + if (array_key_exists($snakedName = Casing::snake($name), $parameters)) { return $snakedName; } } diff --git a/src/Illuminate/Routing/ResourceRegistrar.php b/src/Illuminate/Routing/ResourceRegistrar.php index 781b4baddb87..fa2ea31d10fe 100644 --- a/src/Illuminate/Routing/ResourceRegistrar.php +++ b/src/Illuminate/Routing/ResourceRegistrar.php @@ -3,6 +3,7 @@ namespace Illuminate\Routing; use Illuminate\Support\Str; +use Illuminate\Support\StrGrammar; class ResourceRegistrar { @@ -594,7 +595,7 @@ public function getResourceWildcard($value) } elseif (isset(static::$parameterMap[$value])) { $value = static::$parameterMap[$value]; } elseif ($this->parameters === 'singular' || static::$singularParameters) { - $value = Str::singular($value); + $value = StrGrammar::singular($value); } return str_replace('-', '_', $value); diff --git a/src/Illuminate/Routing/Route.php b/src/Illuminate/Routing/Route.php index 2f44fa711396..47a50018a1a9 100755 --- a/src/Illuminate/Routing/Route.php +++ b/src/Illuminate/Routing/Route.php @@ -16,6 +16,7 @@ use Illuminate\Routing\Matching\SchemeValidator; use Illuminate\Routing\Matching\UriValidator; use Illuminate\Support\Arr; +use Illuminate\Support\PatternMatcher; use Illuminate\Support\Str; use Illuminate\Support\Traits\Macroable; use InvalidArgumentException; @@ -911,7 +912,7 @@ public function named(...$patterns) } foreach ($patterns as $pattern) { - if (Str::is($pattern, $routeName)) { + if (PatternMatcher::is($pattern, $routeName)) { return true; } } diff --git a/src/Illuminate/Routing/Router.php b/src/Illuminate/Routing/Router.php index 2be5d05e3a14..71f321f2967d 100644 --- a/src/Illuminate/Routing/Router.php +++ b/src/Illuminate/Routing/Router.php @@ -21,6 +21,7 @@ use Illuminate\Routing\Events\Routing; use Illuminate\Support\Arr; use Illuminate\Support\Collection; +use Illuminate\Support\PatternMatcher; use Illuminate\Support\Str; use Illuminate\Support\Stringable; use Illuminate\Support\Traits\Macroable; @@ -1350,7 +1351,7 @@ public function currentRouteAction() public function uses(...$patterns) { foreach ($patterns as $pattern) { - if (Str::is($pattern, $this->currentRouteAction())) { + if (PatternMatcher::is($pattern, $this->currentRouteAction())) { return true; } } diff --git a/src/Illuminate/Session/Store.php b/src/Illuminate/Session/Store.php index 986b00458c57..fdda3687d35c 100755 --- a/src/Illuminate/Session/Store.php +++ b/src/Illuminate/Session/Store.php @@ -5,8 +5,8 @@ use Closure; use Illuminate\Contracts\Session\Session; use Illuminate\Support\Arr; +use Illuminate\Support\Generator; use Illuminate\Support\MessageBag; -use Illuminate\Support\Str; use Illuminate\Support\Traits\Macroable; use Illuminate\Support\ViewErrorBag; use SessionHandlerInterface; @@ -692,7 +692,7 @@ public function isValidId($id) */ protected function generateSessionId() { - return Str::random(40); + return Generator::random(40); } /** @@ -725,7 +725,7 @@ public function token() */ public function regenerateToken() { - $this->put('_token', Str::random(40)); + $this->put('_token', Generator::random(40)); } /** diff --git a/src/Illuminate/Support/Manager.php b/src/Illuminate/Support/Manager.php index dac4731226b2..e8593a54bec9 100755 --- a/src/Illuminate/Support/Manager.php +++ b/src/Illuminate/Support/Manager.php @@ -100,7 +100,7 @@ protected function createDriver($driver) return $this->callCustomCreator($driver); } - $method = 'create'.Str::studly($driver).'Driver'; + $method = 'create'.Casing::studly($driver).'Driver'; if (method_exists($this, $method)) { return $this->$method(); diff --git a/src/Illuminate/Support/MessageBag.php b/src/Illuminate/Support/MessageBag.php index 8c8fb2ef916e..ffd7f652ff9c 100755 --- a/src/Illuminate/Support/MessageBag.php +++ b/src/Illuminate/Support/MessageBag.php @@ -225,7 +225,7 @@ protected function getMessagesForWildcardKey($key, $format) { return collect($this->messages) ->filter(function ($messages, $messageKey) use ($key) { - return Str::is($key, $messageKey); + return PatternMatcher::is($key, $messageKey); }) ->map(function ($messages, $messageKey) use ($format) { return $this->transform( diff --git a/src/Illuminate/Support/MultipleInstanceManager.php b/src/Illuminate/Support/MultipleInstanceManager.php index 05a8c23b4135..1b6df40d5b4f 100644 --- a/src/Illuminate/Support/MultipleInstanceManager.php +++ b/src/Illuminate/Support/MultipleInstanceManager.php @@ -134,7 +134,7 @@ protected function resolve($name) return $this->{$createMethod}($config); } - $createMethod = 'create'.Str::studly($driverName).ucfirst($this->driverKey); + $createMethod = 'create'.Casing::studly($driverName).ucfirst($this->driverKey); if (method_exists($this, $createMethod)) { return $this->{$createMethod}($config); diff --git a/src/Illuminate/Support/Testing/Fakes/EventFake.php b/src/Illuminate/Support/Testing/Fakes/EventFake.php index 06867c4f35bb..fd2935da61f3 100644 --- a/src/Illuminate/Support/Testing/Fakes/EventFake.php +++ b/src/Illuminate/Support/Testing/Fakes/EventFake.php @@ -8,6 +8,7 @@ use Illuminate\Contracts\Events\ShouldDispatchAfterCommit; use Illuminate\Support\Arr; use Illuminate\Support\Str; +use Illuminate\Support\StrGrammar; use Illuminate\Support\Traits\ForwardsCalls; use Illuminate\Support\Traits\ReflectsClosures; use PHPUnit\Framework\Assert as PHPUnit; @@ -197,7 +198,7 @@ public function assertNothingDispatched() '%s dispatched %s %s', $eventName, count($events), - Str::plural('time', count($events)), + StrGrammar::plural('time', count($events)), )) ->join("\n- "); diff --git a/src/Illuminate/Testing/ParallelTesting.php b/src/Illuminate/Testing/ParallelTesting.php index e633bc57192f..145bb679d44f 100644 --- a/src/Illuminate/Testing/ParallelTesting.php +++ b/src/Illuminate/Testing/ParallelTesting.php @@ -246,7 +246,7 @@ public function callTearDownTestCaseCallbacks($testCase) public function option($option) { $optionsResolver = $this->optionsResolver ?: function ($option) { - $option = 'LARAVEL_PARALLEL_TESTING_'.Str::upper($option); + $option = 'LARAVEL_PARALLEL_TESTING_'.Casing::upper($option); return $_SERVER[$option] ?? false; }; diff --git a/src/Illuminate/Translation/Translator.php b/src/Illuminate/Translation/Translator.php index 5f9b1e299896..39c7bae51fb5 100755 --- a/src/Illuminate/Translation/Translator.php +++ b/src/Illuminate/Translation/Translator.php @@ -6,6 +6,7 @@ use Illuminate\Contracts\Translation\Loader; use Illuminate\Contracts\Translation\Translator as TranslatorContract; use Illuminate\Support\Arr; +use Illuminate\Support\Casing; use Illuminate\Support\NamespacedItemResolver; use Illuminate\Support\Str; use Illuminate\Support\Traits\Macroable; @@ -288,8 +289,8 @@ protected function makeReplacements($line, array $replace) $value = call_user_func($this->stringableHandlers[get_class($value)], $value); } - $shouldReplace[':'.Str::ucfirst($key)] = Str::ucfirst($value ?? ''); - $shouldReplace[':'.Str::upper($key)] = Str::upper($value ?? ''); + $shouldReplace[':'.Casing::ucfirst($key)] = Casing::ucfirst($value ?? ''); + $shouldReplace[':'.Casing::upper($key)] = Casing::upper($value ?? ''); $shouldReplace[':'.$key] = $value; } diff --git a/src/Illuminate/Validation/Concerns/FormatsMessages.php b/src/Illuminate/Validation/Concerns/FormatsMessages.php index ad1352aa767b..95711852f964 100644 --- a/src/Illuminate/Validation/Concerns/FormatsMessages.php +++ b/src/Illuminate/Validation/Concerns/FormatsMessages.php @@ -4,6 +4,8 @@ use Closure; use Illuminate\Support\Arr; +use Illuminate\Support\Casing; +use Illuminate\Support\PatternMatcher; use Illuminate\Support\Str; use Symfony\Component\HttpFoundation\File\File; use Symfony\Component\HttpFoundation\File\UploadedFile; @@ -34,7 +36,7 @@ protected function getMessage($attribute, $rule) return $inlineMessage; } - $lowerRule = Str::snake($rule); + $lowerRule = Casing::snake($rule); $customKey = "validation.custom.{$attribute}.{$lowerRule}"; @@ -81,7 +83,7 @@ protected function getMessage($attribute, $rule) */ protected function getInlineMessage($attribute, $rule) { - $inlineEntry = $this->getFromLocalArray($attribute, Str::snake($rule)); + $inlineEntry = $this->getFromLocalArray($attribute, Casing::snake($rule)); return is_array($inlineEntry) && in_array($rule, $this->sizeRules) ? $inlineEntry[$this->getAttributeType($attribute)] @@ -123,7 +125,7 @@ protected function getFromLocalArray($attribute, $lowerRule, $source = null) continue; } - if (Str::is($sourceKey, $key)) { + if (PatternMatcher::is($sourceKey, $key)) { $message = $source[$sourceKey]; if ($sourceKey === $attribute && is_array($message)) { @@ -179,7 +181,7 @@ protected function getCustomMessageFromTranslator($keys) protected function getWildcardCustomMessages($messages, $search, $default) { foreach ($messages as $key => $message) { - if ($search === $key || (Str::contains($key, ['*']) && Str::is($key, $search))) { + if ($search === $key || (Str::contains($key, ['*']) && PatternMatcher::is($key, $search))) { return $message; } } @@ -196,7 +198,7 @@ protected function getWildcardCustomMessages($messages, $search, $default) */ protected function getSizeMessage($attribute, $rule) { - $lowerRule = Str::snake($rule); + $lowerRule = Casing::snake($rule); // There are three different types of size validations. The attribute may be // either a number, file, or string so we will check a few things to know @@ -247,8 +249,8 @@ public function makeReplacements($message, $attribute, $rule, $parameters) $message = $this->replaceIndexPlaceholder($message, $attribute); $message = $this->replacePositionPlaceholder($message, $attribute); - if (isset($this->replacers[Str::snake($rule)])) { - return $this->callReplacer($message, $attribute, Str::snake($rule), $parameters, $this); + if (isset($this->replacers[Casing::snake($rule)])) { + return $this->callReplacer($message, $attribute, Casing::snake($rule), $parameters, $this); } elseif (method_exists($this, $replacer = "replace{$rule}")) { return $this->$replacer($message, $attribute, $rule, $parameters); } @@ -294,7 +296,7 @@ public function getDisplayableAttribute($attribute) : $attribute; } - return str_replace('_', ' ', Str::snake($attribute)); + return str_replace('_', ' ', Casing::snake($attribute)); } /** @@ -349,7 +351,7 @@ protected function replaceAttributePlaceholder($message, $value) { return str_replace( [':attribute', ':ATTRIBUTE', ':Attribute'], - [$value, Str::upper($value), Str::ucfirst($value)], + [$value, Casing::upper($value), Casing::ucfirst($value)], $message ); } diff --git a/src/Illuminate/Validation/Concerns/ValidatesAttributes.php b/src/Illuminate/Validation/Concerns/ValidatesAttributes.php index 522d2e1da4ef..e4a519a8466a 100644 --- a/src/Illuminate/Validation/Concerns/ValidatesAttributes.php +++ b/src/Illuminate/Validation/Concerns/ValidatesAttributes.php @@ -21,6 +21,7 @@ use Illuminate\Support\Casing; use Illuminate\Support\Exceptions\MathException; use Illuminate\Support\Facades\Date; +use Illuminate\Support\PatternMatcher; use Illuminate\Support\Str; use Illuminate\Validation\Rules\Exists; use Illuminate\Validation\Rules\Unique; @@ -159,7 +160,7 @@ protected function getDnsRecords($hostname, $type) */ public function validateAscii($attribute, $value) { - return Str::isAscii($value); + return PatternMatcher::isAscii($value); } /** @@ -1434,7 +1435,7 @@ public function validateInArray($attribute, $value, $parameters) $attributeData = ValidationData::extractDataFromPath($explicitPath, $this->data); $otherValues = Arr::where(Arr::dot($attributeData), function ($value, $key) use ($parameters) { - return Str::is($parameters[0], $key); + return PatternMatcher::is($parameters[0], $key); }); return in_array($value, $otherValues); @@ -2516,8 +2517,8 @@ public function validateString($attribute, $value) public function validateTimezone($attribute, $value, $parameters = []) { return in_array($value, timezone_identifiers_list( - constant(DateTimeZone::class.'::'.Str::upper($parameters[0] ?? 'ALL')), - isset($parameters[1]) ? Str::upper($parameters[1]) : null, + constant(DateTimeZone::class.'::'.Casing::upper($parameters[0] ?? 'ALL')), + isset($parameters[1]) ? Casing::upper($parameters[1]) : null, ), true); } @@ -2531,7 +2532,7 @@ public function validateTimezone($attribute, $value, $parameters = []) */ public function validateUrl($attribute, $value, $parameters = []) { - return Str::isUrl($value, $parameters); + return PatternMatcher::isUrl($value, $parameters); } /** @@ -2555,7 +2556,7 @@ public function validateUlid($attribute, $value) */ public function validateUuid($attribute, $value) { - return Str::isUuid($value); + return PatternMatcher::isUuid($value); } /** diff --git a/src/Illuminate/Validation/Factory.php b/src/Illuminate/Validation/Factory.php index 6ebfcac50d2d..a165b85303c5 100755 --- a/src/Illuminate/Validation/Factory.php +++ b/src/Illuminate/Validation/Factory.php @@ -6,6 +6,7 @@ use Illuminate\Contracts\Container\Container; use Illuminate\Contracts\Translation\Translator; use Illuminate\Contracts\Validation\Factory as FactoryContract; +use Illuminate\Support\Casing; use Illuminate\Support\Str; class Factory implements FactoryContract @@ -198,7 +199,7 @@ public function extend($rule, $extension, $message = null) $this->extensions[$rule] = $extension; if ($message) { - $this->fallbackMessages[Str::snake($rule)] = $message; + $this->fallbackMessages[Casing::snake($rule)] = $message; } } @@ -215,7 +216,7 @@ public function extendImplicit($rule, $extension, $message = null) $this->implicitExtensions[$rule] = $extension; if ($message) { - $this->fallbackMessages[Str::snake($rule)] = $message; + $this->fallbackMessages[Casing::snake($rule)] = $message; } } @@ -232,7 +233,7 @@ public function extendDependent($rule, $extension, $message = null) $this->dependentExtensions[$rule] = $extension; if ($message) { - $this->fallbackMessages[Str::snake($rule)] = $message; + $this->fallbackMessages[Casing::snake($rule)] = $message; } } diff --git a/src/Illuminate/Validation/ValidationRuleParser.php b/src/Illuminate/Validation/ValidationRuleParser.php index f803540fa2a9..e95607721029 100644 --- a/src/Illuminate/Validation/ValidationRuleParser.php +++ b/src/Illuminate/Validation/ValidationRuleParser.php @@ -7,6 +7,7 @@ use Illuminate\Contracts\Validation\Rule as RuleContract; use Illuminate\Contracts\Validation\ValidationRule; use Illuminate\Support\Arr; +use Illuminate\Support\Casing; use Illuminate\Support\Str; use Illuminate\Validation\Rules\Exists; use Illuminate\Validation\Rules\Unique; @@ -248,7 +249,7 @@ public static function parse($rule) */ protected static function parseArrayRule(array $rule) { - return [Str::studly(trim(Arr::get($rule, 0, ''))), array_slice($rule, 1)]; + return [Casing::studly(trim(Arr::get($rule, 0, ''))), array_slice($rule, 1)]; } /** @@ -270,7 +271,7 @@ protected static function parseStringRule($rule) $parameters = static::parseParameters($rule, $parameter); } - return [Str::studly(trim($rule)), $parameters]; + return [Casing::studly(trim($rule)), $parameters]; } /** diff --git a/src/Illuminate/Validation/Validator.php b/src/Illuminate/Validation/Validator.php index 031dd67a4915..0818c71cc11a 100755 --- a/src/Illuminate/Validation/Validator.php +++ b/src/Illuminate/Validation/Validator.php @@ -11,8 +11,11 @@ use Illuminate\Contracts\Validation\Validator as ValidatorContract; use Illuminate\Contracts\Validation\ValidatorAwareRule; use Illuminate\Support\Arr; +use Illuminate\Support\Casing; use Illuminate\Support\Fluent; +use Illuminate\Support\Generator; use Illuminate\Support\MessageBag; +use Illuminate\Support\Replacer; use Illuminate\Support\Str; use Illuminate\Support\ValidatedInput; use InvalidArgumentException; @@ -337,7 +340,7 @@ class Validator implements ValidatorContract public function __construct(Translator $translator, array $data, array $rules, array $messages = [], array $attributes = []) { - $this->dotPlaceholder = Str::random(); + $this->dotPlaceholder = Generator::random(); $this->initialRules = $rules; $this->translator = $translator; @@ -1252,7 +1255,7 @@ private function dataForSometimesIteration(string $attribute, $removeLastSegment $lastSegmentOfAttribute = strrchr($attribute, '.'); $attribute = $lastSegmentOfAttribute && $removeLastSegmentOfAttribute - ? Str::replaceLast($lastSegmentOfAttribute, '', $attribute) + ? Replacer::replaceLast($lastSegmentOfAttribute, '', $attribute) : $attribute; return is_array($data = data_get($this->data, $attribute)) @@ -1301,7 +1304,7 @@ public function addImplicitExtensions(array $extensions) $this->addExtensions($extensions); foreach ($extensions as $rule => $extension) { - $this->implicitRules[] = Str::studly($rule); + $this->implicitRules[] = Casing::studly($rule); } } @@ -1316,7 +1319,7 @@ public function addDependentExtensions(array $extensions) $this->addExtensions($extensions); foreach ($extensions as $rule => $extension) { - $this->dependentRules[] = Str::studly($rule); + $this->dependentRules[] = Casing::studly($rule); } } @@ -1329,7 +1332,7 @@ public function addDependentExtensions(array $extensions) */ public function addExtension($rule, $extension) { - $this->extensions[Str::snake($rule)] = $extension; + $this->extensions[Casing::snake($rule)] = $extension; } /** @@ -1343,7 +1346,7 @@ public function addImplicitExtension($rule, $extension) { $this->addExtension($rule, $extension); - $this->implicitRules[] = Str::studly($rule); + $this->implicitRules[] = Casing::studly($rule); } /** @@ -1357,7 +1360,7 @@ public function addDependentExtension($rule, $extension) { $this->addExtension($rule, $extension); - $this->dependentRules[] = Str::studly($rule); + $this->dependentRules[] = Casing::studly($rule); } /** @@ -1386,7 +1389,7 @@ public function addReplacers(array $replacers) */ public function addReplacer($rule, $replacer) { - $this->replacers[Str::snake($rule)] = $replacer; + $this->replacers[Casing::snake($rule)] = $replacer; } /** @@ -1629,7 +1632,7 @@ protected function callClassBasedExtension($callback, $parameters) */ public function __call($method, $parameters) { - $rule = Str::snake(substr($method, 8)); + $rule = Casing::snake(substr($method, 8)); if (isset($this->extensions[$rule])) { return $this->callExtension($rule, $parameters); diff --git a/src/Illuminate/View/Compilers/BladeCompiler.php b/src/Illuminate/View/Compilers/BladeCompiler.php index 1107249f88b0..8aa2bd76c7e8 100644 --- a/src/Illuminate/View/Compilers/BladeCompiler.php +++ b/src/Illuminate/View/Compilers/BladeCompiler.php @@ -7,6 +7,7 @@ use Illuminate\Contracts\View\Factory as ViewFactory; use Illuminate\Contracts\View\View; use Illuminate\Support\Arr; +use Illuminate\Support\Casing; use Illuminate\Support\Str; use Illuminate\Support\Traits\ReflectsClosures; use Illuminate\View\Component; @@ -761,9 +762,9 @@ public function component($class, $alias = null, $prefix = '') if (is_null($alias)) { $alias = str_contains($class, '\\View\\Components\\') ? collect(explode('\\', Str::after($class, '\\View\\Components\\')))->map(function ($segment) { - return Str::kebab($segment); + return Casing::kebab($segment); })->implode(':') - : Str::kebab(class_basename($class)); + : Casing::kebab(class_basename($class)); } if (! empty($prefix)) { diff --git a/src/Illuminate/View/Compilers/ComponentTagCompiler.php b/src/Illuminate/View/Compilers/ComponentTagCompiler.php index 9c3d6adbec99..b163399d67a2 100644 --- a/src/Illuminate/View/Compilers/ComponentTagCompiler.php +++ b/src/Illuminate/View/Compilers/ComponentTagCompiler.php @@ -6,6 +6,8 @@ use Illuminate\Contracts\Foundation\Application; use Illuminate\Contracts\View\Factory; use Illuminate\Filesystem\Filesystem; +use Illuminate\Support\Casing; +use Illuminate\Support\Replacer; use Illuminate\Support\Str; use Illuminate\View\AnonymousComponent; use Illuminate\View\DynamicComponent; @@ -237,7 +239,7 @@ protected function componentString(string $component, array $attributes) [$data, $attributes] = $this->partitionDataAndAttributes($class, $attributes); $data = $data->mapWithKeys(function ($value, $key) { - return [Str::camel($key) => $value]; + return [Casing::camel($key) => $value]; }); // If the component doesn't exist as a class, we'll assume it's a class-less @@ -426,7 +428,7 @@ public function guessClassName(string $component) public function formatClassName(string $component) { $componentPieces = array_map(function ($componentPiece) { - return ucfirst(Str::camel($componentPiece)); + return ucfirst(Casing::camel($componentPiece)); }, explode('.', $component)); return implode('\\', $componentPieces); @@ -448,7 +450,7 @@ public function guessViewName($name, $prefix = 'components.') $delimiter = ViewFinderInterface::HINT_PATH_DELIMITER; if (str_contains($name, $delimiter)) { - return Str::replaceFirst($delimiter, $delimiter.$prefix, $name); + return Replacer::replaceFirst($delimiter, $delimiter.$prefix, $name); } return $prefix.$name; @@ -477,7 +479,7 @@ public function partitionDataAndAttributes($class, array $attributes) : []; return collect($attributes)->partition(function ($value, $key) use ($parameterNames) { - return in_array(Str::camel($key), $parameterNames); + return in_array(Casing::camel($key), $parameterNames); })->all(); } @@ -548,7 +550,7 @@ public function compileSlots(string $value) $name = $this->stripQuotes($matches['inlineName'] ?: $matches['name'] ?: $matches['boundName']); if (Str::contains($name, '-') && ! empty($matches['inlineName'])) { - $name = Str::camel($name); + $name = Casing::camel($name); } // If the name was given as a simple string, we will wrap it in quotes as if it was bound for convenience... diff --git a/src/Illuminate/View/ComponentAttributeBag.php b/src/Illuminate/View/ComponentAttributeBag.php index 868a97f5aac3..39ad02bf9e96 100644 --- a/src/Illuminate/View/ComponentAttributeBag.php +++ b/src/Illuminate/View/ComponentAttributeBag.php @@ -6,6 +6,7 @@ use ArrayIterator; use Illuminate\Contracts\Support\Htmlable; use Illuminate\Support\Arr; +use Illuminate\Support\Casing; use Illuminate\Support\HtmlString; use Illuminate\Support\Str; use Illuminate\Support\Traits\Conditionable; @@ -405,7 +406,7 @@ public static function extractPropNames(array $keys) $key = is_numeric($key) ? $default : $key; $props[] = $key; - $props[] = Str::kebab($key); + $props[] = Casing::kebab($key); } return $props; diff --git a/src/Illuminate/View/Concerns/ManagesLayouts.php b/src/Illuminate/View/Concerns/ManagesLayouts.php index 38cc56c7d5ac..772171beeac1 100644 --- a/src/Illuminate/View/Concerns/ManagesLayouts.php +++ b/src/Illuminate/View/Concerns/ManagesLayouts.php @@ -3,6 +3,7 @@ namespace Illuminate\View\Concerns; use Illuminate\Contracts\View\View; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use InvalidArgumentException; @@ -192,7 +193,7 @@ public static function parentPlaceholder($section = '') protected static function parentPlaceholderSalt() { if (! static::$parentPlaceholderSalt) { - return static::$parentPlaceholderSalt = Str::random(40); + return static::$parentPlaceholderSalt = Generator::random(40); } return static::$parentPlaceholderSalt; diff --git a/src/Illuminate/View/DynamicComponent.php b/src/Illuminate/View/DynamicComponent.php index cea66e77b304..a83be85efb68 100644 --- a/src/Illuminate/View/DynamicComponent.php +++ b/src/Illuminate/View/DynamicComponent.php @@ -3,6 +3,7 @@ namespace Illuminate\View; use Illuminate\Container\Container; +use Illuminate\Support\Casing; use Illuminate\Support\Str; use Illuminate\View\Compilers\ComponentTagCompiler; @@ -48,7 +49,7 @@ public function __construct(string $component) public function render() { $template = <<<'EOF' -getAttributes())->mapWithKeys(function ($value, $key) { return [Illuminate\Support\Str::camel(str_replace([':', '.'], ' ', $key)) => $value]; })->all(), EXTR_SKIP); ?> +getAttributes())->mapWithKeys(function ($value, $key) { return [Illuminate\Support\Casing::camel(str_replace([':', '.'], ' ', $key)) => $value]; })->all(), EXTR_SKIP); ?> {{ props }} {{ slots }} @@ -94,7 +95,7 @@ protected function compileProps(array $bindings) } return '@props('.'[\''.implode('\',\'', collect($bindings)->map(function ($dataKey) { - return Str::camel($dataKey); + return Casing::camel($dataKey); })->all()).'\']'.')'; } @@ -107,7 +108,7 @@ protected function compileProps(array $bindings) protected function compileBindings(array $bindings) { return collect($bindings)->map(function ($key) { - return ':'.$key.'="$'.Str::camel(str_replace([':', '.'], ' ', $key)).'"'; + return ':'.$key.'="$'.Casing::camel(str_replace([':', '.'], ' ', $key)).'"'; })->implode(' '); } diff --git a/src/Illuminate/View/View.php b/src/Illuminate/View/View.php index 0751a8dff5ba..94cc8a3ad4c5 100755 --- a/src/Illuminate/View/View.php +++ b/src/Illuminate/View/View.php @@ -10,6 +10,7 @@ use Illuminate\Contracts\Support\Renderable; use Illuminate\Contracts\View\Engine; use Illuminate\Contracts\View\View as ViewContract; +use Illuminate\Support\Casing; use Illuminate\Support\MessageBag; use Illuminate\Support\Str; use Illuminate\Support\Traits\Macroable; @@ -480,7 +481,7 @@ public function __call($method, $parameters) )); } - return $this->with(Str::camel(substr($method, 4)), $parameters[0]); + return $this->with(Casing::camel(substr($method, 4)), $parameters[0]); } /** diff --git a/tests/Foundation/FoundationViteTest.php b/tests/Foundation/FoundationViteTest.php index eecae811997b..8936c24cba7e 100644 --- a/tests/Foundation/FoundationViteTest.php +++ b/tests/Foundation/FoundationViteTest.php @@ -6,6 +6,7 @@ use Illuminate\Foundation\ViteException; use Illuminate\Foundation\ViteManifestNotFoundException; use Illuminate\Support\Facades\Vite as ViteFacade; +use Illuminate\Support\Generator; use Illuminate\Support\Js; use Illuminate\Support\Str; use Orchestra\Testbench\TestCase; @@ -104,7 +105,7 @@ public function testViteHotModuleReplacementWithJsAndCss() public function testItCanGenerateCspNonceWithHotFile() { - Str::createRandomStringsUsing(fn ($length) => "random-string-with-length:{$length}"); + Generator::createRandomStringsUsing(fn ($length) => "random-string-with-length:{$length}"); $this->makeViteHotFile(); $nonce = ViteFacade::useCspNonce(); @@ -119,12 +120,12 @@ public function testItCanGenerateCspNonceWithHotFile() $result->toHtml() ); - Str::createRandomStringsNormally(); + Generator::createRandomStringsNormally(); } public function testItCanGenerateCspNonceWithManifest() { - Str::createRandomStringsUsing(fn ($length) => "random-string-with-length:{$length}"); + Generator::createRandomStringsUsing(fn ($length) => "random-string-with-length:{$length}"); $this->makeViteManifest(); $nonce = ViteFacade::useCspNonce(); @@ -138,7 +139,7 @@ public function testItCanGenerateCspNonceWithManifest() $result->toHtml() ); - Str::createRandomStringsNormally(); + Generator::createRandomStringsNormally(); } public function testItCanSpecifyCspNonceWithHotFile() @@ -195,7 +196,7 @@ public function testReactRefreshNonce() public function testItCanInjectIntegrityWhenPresentInManifest() { - $buildDir = Str::random(); + $buildDir = Generator::random(); $this->makeViteManifest([ 'resources/js/app.js' => [ 'src' => 'resources/js/app.js', @@ -222,7 +223,7 @@ public function testItCanInjectIntegrityWhenPresentInManifest() public function testItCanInjectIntegrityWhenPresentInManifestForCss() { - $buildDir = Str::random(); + $buildDir = Generator::random(); $this->makeViteManifest([ 'resources/js/app.js' => [ 'src' => 'resources/js/app.js', @@ -258,7 +259,7 @@ public function testItCanInjectIntegrityWhenPresentInManifestForCss() public function testItCanInjectIntegrityWhenPresentInManifestForImportedCss() { - $buildDir = Str::random(); + $buildDir = Generator::random(); $this->makeViteManifest([ 'resources/js/app.js' => [ 'src' => 'resources/js/app.js', @@ -294,7 +295,7 @@ public function testItCanInjectIntegrityWhenPresentInManifestForImportedCss() public function testItCanSpecifyIntegrityKey() { - $buildDir = Str::random(); + $buildDir = Generator::random(); $this->makeViteManifest([ 'resources/js/app.js' => [ 'src' => 'resources/js/app.js', @@ -676,7 +677,7 @@ public function testViteCanAssetPath() 'src' => 'resources/images/profile.png', 'file' => 'assets/profile.versioned.png', ], - ], $buildDir = Str::random()); + ], $buildDir = Generator::random()); $vite = app(Vite::class)->useBuildDirectory($buildDir); $this->app['config']->set('app.asset_url', 'https://cdn.app.com'); @@ -703,7 +704,7 @@ public function testViteIsMacroable() 'src' => 'resources/images/profile.png', 'file' => 'assets/profile.versioned.png', ], - ], $buildDir = Str::random()); + ], $buildDir = Generator::random()); Vite::macro('image', function ($asset, $buildDir = null) { return $this->asset("resources/images/{$asset}", $buildDir); }); @@ -718,7 +719,7 @@ public function testViteIsMacroable() public function testItGeneratesPreloadDirectivesForJsAndCssImports() { $manifest = json_decode(file_get_contents(__DIR__.'/fixtures/jetstream-manifest.json')); - $buildDir = Str::random(); + $buildDir = Generator::random(); $this->makeViteManifest($manifest, $buildDir); $result = app(Vite::class)(['resources/js/Pages/Auth/Login.vue'], $buildDir); @@ -776,7 +777,7 @@ public function testItGeneratesPreloadDirectivesForJsAndCssImports() public function testItCanSpecifyAttributesForPreloadedAssets() { - $buildDir = Str::random(); + $buildDir = Generator::random(); $this->makeViteManifest([ 'resources/js/app.js' => [ 'src' => 'resources/js/app.js', @@ -906,7 +907,7 @@ public function testItCanSpecifyAttributesForPreloadedAssets() public function testItCanSuppressPreloadTagGeneration() { - $buildDir = Str::random(); + $buildDir = Generator::random(); $this->makeViteManifest([ 'resources/js/app.js' => [ 'src' => 'resources/js/app.js', @@ -1057,7 +1058,7 @@ public function testItCanSuppressPreloadTagGeneration() public function testPreloadAssetsGetAssetNonce() { - $buildDir = Str::random(); + $buildDir = Generator::random(); $this->makeViteManifest([ 'resources/js/app.js' => [ 'src' => 'resources/js/app.js', @@ -1099,7 +1100,7 @@ public function testPreloadAssetsGetAssetNonce() public function testCrossoriginAttributeIsInheritedByPreloadTags() { - $buildDir = Str::random(); + $buildDir = Generator::random(); $this->makeViteManifest([ 'resources/js/app.js' => [ 'src' => 'resources/js/app.js', @@ -1146,7 +1147,7 @@ public function testCrossoriginAttributeIsInheritedByPreloadTags() public function testItCanConfigureTheManifestFilename() { - $buildDir = Str::random(); + $buildDir = Generator::random(); app()->usePublicPath(__DIR__); if (! file_exists(public_path($buildDir))) { mkdir(public_path($buildDir)); @@ -1174,7 +1175,7 @@ public function testItCanConfigureTheManifestFilename() public function testItOnlyOutputsUniquePreloadTags() { - $buildDir = Str::random(); + $buildDir = Generator::random(); $this->makeViteManifest([ 'resources/js/app.css' => [ 'file' => 'assets/app-versioned.css', @@ -1301,7 +1302,7 @@ protected function makeViteManifest($contents = null, $path = 'build') public function testItCanPrefetchEntrypoint() { $manifest = json_decode(file_get_contents(__DIR__.'/fixtures/prefetching-manifest.json')); - $buildDir = Str::random(); + $buildDir = Generator::random(); $this->makeViteManifest($manifest, $buildDir); app()->usePublicPath(__DIR__); @@ -1377,7 +1378,7 @@ public function testItCanPrefetchEntrypoint() public function testItHandlesSpecifyingPageWithAppJs() { $manifest = json_decode(file_get_contents(__DIR__.'/fixtures/prefetching-manifest.json')); - $buildDir = Str::random(); + $buildDir = Generator::random(); $this->makeViteManifest($manifest, $buildDir); app()->usePublicPath(__DIR__); @@ -1407,7 +1408,7 @@ public function testItHandlesSpecifyingPageWithAppJs() public function testItCanSpecifyWaterfallChunks() { $manifest = json_decode(file_get_contents(__DIR__.'/fixtures/prefetching-manifest.json')); - $buildDir = Str::random(); + $buildDir = Generator::random(); $this->makeViteManifest($manifest, $buildDir); app()->usePublicPath(__DIR__); @@ -1443,7 +1444,7 @@ public function testItCanSpecifyWaterfallChunks() public function testItCanPrefetchAggressively() { $manifest = json_decode(file_get_contents(__DIR__.'/fixtures/prefetching-manifest.json')); - $buildDir = Str::random(); + $buildDir = Generator::random(); $this->makeViteManifest($manifest, $buildDir); app()->usePublicPath(__DIR__); @@ -1497,7 +1498,7 @@ public function testItCanPrefetchAggressively() public function testAddsAttributesToPrefetchTags() { $manifest = json_decode(file_get_contents(__DIR__.'/fixtures/prefetching-manifest.json')); - $buildDir = Str::random(); + $buildDir = Generator::random(); $this->makeViteManifest($manifest, $buildDir); app()->usePublicPath(__DIR__); @@ -1533,7 +1534,7 @@ public function testAddsAttributesToPrefetchTags() public function testItNormalisesAttributes() { $manifest = json_decode(file_get_contents(__DIR__.'/fixtures/prefetching-manifest.json')); - $buildDir = Str::random(); + $buildDir = Generator::random(); $this->makeViteManifest($manifest, $buildDir); app()->usePublicPath(__DIR__); @@ -1576,7 +1577,7 @@ public function testItNormalisesAttributes() public function testItPrefetchesCss() { $manifest = json_decode(file_get_contents(__DIR__.'/fixtures/prefetching-manifest.json')); - $buildDir = Str::random(); + $buildDir = Generator::random(); $this->makeViteManifest($manifest, $buildDir); app()->usePublicPath(__DIR__); @@ -1655,7 +1656,7 @@ public function testItPrefetchesCss() public function testSupportCspNonceInPrefetchScript() { $manifest = json_decode(file_get_contents(__DIR__.'/fixtures/prefetching-manifest.json')); - $buildDir = Str::random(); + $buildDir = Generator::random(); $this->makeViteManifest($manifest, $buildDir); app()->usePublicPath(__DIR__); @@ -1679,7 +1680,7 @@ public function testSupportCspNonceInPrefetchScript() public function testItCanConfigureThePrefetchTriggerEvent() { $manifest = json_decode(file_get_contents(__DIR__.'/fixtures/prefetching-manifest.json')); - $buildDir = Str::random(); + $buildDir = Generator::random(); $this->makeViteManifest($manifest, $buildDir); app()->usePublicPath(__DIR__); diff --git a/tests/Integration/Auth/AuthenticationTest.php b/tests/Integration/Auth/AuthenticationTest.php index cd65dd793145..858317426544 100644 --- a/tests/Integration/Auth/AuthenticationTest.php +++ b/tests/Integration/Auth/AuthenticationTest.php @@ -17,6 +17,7 @@ use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Schema; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use Illuminate\Support\Testing\Fakes\EventFake; use Illuminate\Tests\Integration\Auth\Fixtures\AuthenticationTestUser; @@ -276,7 +277,7 @@ public function testAuthViaAttemptRemembering() 'username' => 'username2', 'email' => 'email2', 'password' => bcrypt('password'), - 'remember_token' => $token = Str::random(), + 'remember_token' => $token = Generator::random(), 'is_active' => false, ]); diff --git a/tests/Integration/Auth/ForgotPasswordTest.php b/tests/Integration/Auth/ForgotPasswordTest.php index 3d38f74179ea..ed0e91df0753 100644 --- a/tests/Integration/Auth/ForgotPasswordTest.php +++ b/tests/Integration/Auth/ForgotPasswordTest.php @@ -9,6 +9,7 @@ use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Notification; use Illuminate\Support\Facades\Password; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use Illuminate\Tests\Integration\Auth\Fixtures\AuthenticationTestUser; use Orchestra\Testbench\Attributes\WithMigration; @@ -30,7 +31,7 @@ protected function tearDown(): void protected function defineEnvironment($app) { - $app['config']->set('app.key', Str::random(32)); + $app['config']->set('app.key', Generator::random(32)); $app['config']->set('auth.providers.users.model', AuthenticationTestUser::class); } diff --git a/tests/Integration/Auth/ForgotPasswordWithoutDefaultRoutesTest.php b/tests/Integration/Auth/ForgotPasswordWithoutDefaultRoutesTest.php index f5f680beb1bc..7172583420e0 100644 --- a/tests/Integration/Auth/ForgotPasswordWithoutDefaultRoutesTest.php +++ b/tests/Integration/Auth/ForgotPasswordWithoutDefaultRoutesTest.php @@ -7,6 +7,7 @@ use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Support\Facades\Notification; use Illuminate\Support\Facades\Password; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use Illuminate\Tests\Integration\Auth\Fixtures\AuthenticationTestUser; use Orchestra\Testbench\Attributes\WithMigration; @@ -28,7 +29,7 @@ protected function tearDown(): void protected function defineEnvironment($app) { - $app['config']->set('app.key', Str::random(32)); + $app['config']->set('app.key', Generator::random(32)); $app['config']->set('auth.providers.users.model', AuthenticationTestUser::class); } diff --git a/tests/Integration/Auth/Middleware/RedirectIfAuthenticatedTest.php b/tests/Integration/Auth/Middleware/RedirectIfAuthenticatedTest.php index c0db2c4eb1ca..bd535ad3483c 100644 --- a/tests/Integration/Auth/Middleware/RedirectIfAuthenticatedTest.php +++ b/tests/Integration/Auth/Middleware/RedirectIfAuthenticatedTest.php @@ -4,6 +4,7 @@ use Illuminate\Auth\Middleware\RedirectIfAuthenticated; use Illuminate\Contracts\Routing\Registrar; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use Illuminate\Tests\Integration\Auth\Fixtures\AuthenticationTestUser; use Orchestra\Testbench\Factories\UserFactory; @@ -38,7 +39,7 @@ protected function setUp(): void protected function defineEnvironment($app) { - $app['config']->set('app.key', Str::random(32)); + $app['config']->set('app.key', Generator::random(32)); $app['config']->set('auth.providers.users.model', AuthenticationTestUser::class); } diff --git a/tests/Integration/Cache/DynamoDbStoreTest.php b/tests/Integration/Cache/DynamoDbStoreTest.php index b465cc61ea0e..0f84df9e871d 100644 --- a/tests/Integration/Cache/DynamoDbStoreTest.php +++ b/tests/Integration/Cache/DynamoDbStoreTest.php @@ -6,6 +6,7 @@ use Aws\Exception\AwsException; use Illuminate\Contracts\Cache\Repository; use Illuminate\Support\Facades\Cache; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use Orchestra\Testbench\Attributes\RequiresEnv; use Orchestra\Testbench\TestCase; @@ -34,7 +35,7 @@ public function testItemsCanBeStoredAndRetrieved() public function testItemsCanBeAtomicallyAdded() { - $key = Str::random(6); + $key = Generator::random(6); $this->assertTrue(Cache::driver('dynamodb')->add($key, 'Taylor', 10)); $this->assertFalse(Cache::driver('dynamodb')->add($key, 'Taylor', 10)); diff --git a/tests/Integration/Console/CommandEventsTest.php b/tests/Integration/Console/CommandEventsTest.php index cc63e22dc4fc..9e8fb047988e 100644 --- a/tests/Integration/Console/CommandEventsTest.php +++ b/tests/Integration/Console/CommandEventsTest.php @@ -9,6 +9,7 @@ use Illuminate\Filesystem\Filesystem; use Illuminate\Foundation\Testing\WithConsoleEvents; use Illuminate\Support\Facades\Event; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use Orchestra\Testbench\Foundation\Application as Testbench; use Orchestra\Testbench\TestCase; @@ -36,7 +37,7 @@ protected function setUp(): void { $this->afterApplicationCreated(function () { $this->files = new Filesystem; - $this->logfile = storage_path(sprintf('logs/command_events_test_%s.log', (string) Str::random())); + $this->logfile = storage_path(sprintf('logs/command_events_test_%s.log', (string) Generator::random())); }); $this->beforeApplicationDestroyed(function () { diff --git a/tests/Integration/Console/CommandSchedulingTest.php b/tests/Integration/Console/CommandSchedulingTest.php index 1a4c918aa5e0..71cb46e51495 100644 --- a/tests/Integration/Console/CommandSchedulingTest.php +++ b/tests/Integration/Console/CommandSchedulingTest.php @@ -4,6 +4,7 @@ use Illuminate\Console\Scheduling\Schedule; use Illuminate\Filesystem\Filesystem; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use Orchestra\Testbench\TestCase; use PHPUnit\Framework\Attributes\DataProvider; @@ -45,7 +46,7 @@ protected function setUp(): void $this->fs = new Filesystem; - $this->id = Str::random(); + $this->id = Generator::random(); $this->logfile = storage_path("logs/command_scheduling_test_{$this->id}.log"); $this->writeArtisanScript(); diff --git a/tests/Integration/Cookie/CookieTest.php b/tests/Integration/Cookie/CookieTest.php index bc5252630376..27856a2b6cfe 100644 --- a/tests/Integration/Cookie/CookieTest.php +++ b/tests/Integration/Cookie/CookieTest.php @@ -8,6 +8,7 @@ use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Session; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use Mockery as m; use Orchestra\Testbench\TestCase; @@ -51,7 +52,7 @@ protected function getEnvironmentSetUp($app) $handler->shouldReceive('render')->andReturn(new Response); - $app['config']->set('app.key', Str::random(32)); + $app['config']->set('app.key', Generator::random(32)); $app['config']->set('session.driver', 'fake-null'); Session::extend('fake-null', function () { diff --git a/tests/Integration/Database/DatabaseEloquentModelAttributeCastingTest.php b/tests/Integration/Database/DatabaseEloquentModelAttributeCastingTest.php index 060031684a0b..82ac519c00b8 100644 --- a/tests/Integration/Database/DatabaseEloquentModelAttributeCastingTest.php +++ b/tests/Integration/Database/DatabaseEloquentModelAttributeCastingTest.php @@ -8,6 +8,7 @@ use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\Schema; +use Illuminate\Support\Generator; use Illuminate\Support\Str; class DatabaseEloquentModelAttributeCastingTest extends DatabaseTestCase @@ -425,7 +426,7 @@ public function virtualString(): Attribute { return new Attribute( function () { - return Str::random(10); + return Generator::random(10); } ); } @@ -433,7 +434,7 @@ function () { public function virtualStringCached(): Attribute { return Attribute::get(function () { - return Str::random(10); + return Generator::random(10); })->shouldCache(); } @@ -466,7 +467,7 @@ public function virtualObject(): Attribute { return new Attribute( function () { - return new AttributeCastAddress(Str::random(10), Str::random(10)); + return new AttributeCastAddress(Generator::random(10), Generator::random(10)); } ); } @@ -484,7 +485,7 @@ public function virtualObjectWithoutCachingFluent(): Attribute { return (new Attribute( function () { - return new AttributeCastAddress(Str::random(10), Str::random(10)); + return new AttributeCastAddress(Generator::random(10), Generator::random(10)); } ))->withoutObjectCaching(); } @@ -501,7 +502,7 @@ function () { public function virtualObjectWithoutCaching(): Attribute { return Attribute::get(function () { - return new AttributeCastAddress(Str::random(10), Str::random(10)); + return new AttributeCastAddress(Generator::random(10), Generator::random(10)); })->withoutObjectCaching(); } diff --git a/tests/Integration/Database/EloquentBelongsToManyTest.php b/tests/Integration/Database/EloquentBelongsToManyTest.php index 68087659bb6c..2b0d93b1d41a 100644 --- a/tests/Integration/Database/EloquentBelongsToManyTest.php +++ b/tests/Integration/Database/EloquentBelongsToManyTest.php @@ -10,6 +10,7 @@ use Illuminate\Support\Carbon; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use Illuminate\Tests\Integration\Database\DatabaseTestCase; @@ -82,11 +83,11 @@ public function testBasicCreateAndRetrieve() { Carbon::setTestNow('2017-10-10 10:10:10'); - $post = Post::create(['title' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); - $tag = Tag::create(['name' => Str::random()]); - $tag2 = Tag::create(['name' => Str::random()]); - $tag3 = Tag::create(['name' => Str::random()]); + $tag = Tag::create(['name' => Generator::random()]); + $tag2 = Tag::create(['name' => Generator::random()]); + $tag3 = Tag::create(['name' => Generator::random()]); $post->tags()->sync([ $tag->id => ['flag' => 'taylor'], @@ -117,8 +118,8 @@ public function testBasicCreateAndRetrieve() public function testRefreshOnOtherModelWorks() { - $post = Post::create(['title' => Str::random()]); - $tag = Tag::create(['name' => $tagName = Str::random()]); + $post = Post::create(['title' => Generator::random()]); + $tag = Tag::create(['name' => $tagName = Generator::random()]); $post->tags()->sync([ $tag->id, @@ -147,9 +148,9 @@ public function testCustomPivotClass() { Carbon::setTestNow('2017-10-10 10:10:10'); - $post = Post::create(['title' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); - $tag = TagWithCustomPivot::create(['name' => Str::random()]); + $tag = TagWithCustomPivot::create(['name' => Generator::random()]); $post->tagsWithCustomPivot()->attach($tag->id); @@ -177,9 +178,9 @@ public function testCustomPivotClassUsingSync() { Carbon::setTestNow('2017-10-10 10:10:10'); - $post = Post::create(['title' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); - $tag = TagWithCustomPivot::create(['name' => Str::random()]); + $tag = TagWithCustomPivot::create(['name' => Generator::random()]); $results = $post->tagsWithCustomPivot()->sync([ $tag->id => ['flag' => 1], @@ -202,8 +203,8 @@ public function testCustomPivotClassUsingUpdateExistingPivot() { Carbon::setTestNow('2017-10-10 10:10:10'); - $post = Post::create(['title' => Str::random()]); - $tag = TagWithCustomPivot::create(['name' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); + $tag = TagWithCustomPivot::create(['name' => Generator::random()]); DB::table('posts_tags')->insert([ ['post_id' => $post->id, 'tag_id' => $tag->id, 'flag' => 'empty'], @@ -229,8 +230,8 @@ public function testCustomPivotClassUpdatesTimestamps() { Carbon::setTestNow('2017-10-10 10:10:10'); - $post = Post::create(['title' => Str::random()]); - $tag = TagWithCustomPivot::create(['name' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); + $tag = TagWithCustomPivot::create(['name' => Generator::random()]); DB::table('posts_tags')->insert([ [ @@ -261,16 +262,16 @@ public function testCustomPivotClassUpdatesTimestamps() public function testAttachMethod() { - $post = Post::create(['title' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); - $tag = Tag::create(['name' => Str::random()]); - $tag2 = Tag::create(['name' => Str::random()]); - $tag3 = Tag::create(['name' => Str::random()]); - $tag4 = Tag::create(['name' => Str::random()]); - $tag5 = Tag::create(['name' => Str::random()]); - $tag6 = Tag::create(['name' => Str::random()]); - $tag7 = Tag::create(['name' => Str::random()]); - $tag8 = Tag::create(['name' => Str::random()]); + $tag = Tag::create(['name' => Generator::random()]); + $tag2 = Tag::create(['name' => Generator::random()]); + $tag3 = Tag::create(['name' => Generator::random()]); + $tag4 = Tag::create(['name' => Generator::random()]); + $tag5 = Tag::create(['name' => Generator::random()]); + $tag6 = Tag::create(['name' => Generator::random()]); + $tag7 = Tag::create(['name' => Generator::random()]); + $tag8 = Tag::create(['name' => Generator::random()]); $post->tags()->attach($tag->id); $this->assertEquals($tag->name, $post->tags[0]->name); @@ -301,15 +302,15 @@ public function testAttachMethod() public function testDetachMethod() { - $post = Post::create(['title' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); - $tag = Tag::create(['name' => Str::random()]); - $tag2 = Tag::create(['name' => Str::random()]); - $tag3 = Tag::create(['name' => Str::random()]); - $tag4 = Tag::create(['name' => Str::random()]); - $tag5 = Tag::create(['name' => Str::random()]); - Tag::create(['name' => Str::random()]); - Tag::create(['name' => Str::random()]); + $tag = Tag::create(['name' => Generator::random()]); + $tag2 = Tag::create(['name' => Generator::random()]); + $tag3 = Tag::create(['name' => Generator::random()]); + $tag4 = Tag::create(['name' => Generator::random()]); + $tag5 = Tag::create(['name' => Generator::random()]); + Tag::create(['name' => Generator::random()]); + Tag::create(['name' => Generator::random()]); $post->tags()->attach(Tag::all()); @@ -344,9 +345,9 @@ public function testDetachMethod() public function testFirstMethod() { - $post = Post::create(['title' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); - $tag = Tag::create(['name' => Str::random()]); + $tag = Tag::create(['name' => Generator::random()]); $post->tags()->attach(Tag::all()); @@ -357,17 +358,17 @@ public function testFirstOrFailMethod() { $this->expectException(ModelNotFoundException::class); - $post = Post::create(['title' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); $post->tags()->firstOrFail(['id']); } public function testFindMethod() { - $post = Post::create(['title' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); - $tag = Tag::create(['name' => Str::random()]); - $tag2 = Tag::create(['name' => Str::random()]); + $tag = Tag::create(['name' => Generator::random()]); + $tag2 = Tag::create(['name' => Generator::random()]); $post->tags()->attach(Tag::all()); @@ -398,17 +399,17 @@ public function testFindMethodStringyKey() $post = PostStringPrimaryKey::query()->create([ 'id' => 'a', - 'title' => Str::random(10), + 'title' => Generator::random(10), ]); $tag = TagStringPrimaryKey::query()->create([ 'id' => 'b', - 'title' => Str::random(10), + 'title' => Generator::random(10), ]); $tag2 = TagStringPrimaryKey::query()->create([ 'id' => 'c', - 'title' => Str::random(10), + 'title' => Generator::random(10), ]); $post->tags()->attach(TagStringPrimaryKey::all()); @@ -425,9 +426,9 @@ public function testFindOrFailMethod() $this->expectException(ModelNotFoundException::class); $this->expectExceptionMessage('No query results for model [Illuminate\Tests\Integration\Database\EloquentBelongsToManyTest\Tag] 10'); - $post = Post::create(['title' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); - Tag::create(['name' => Str::random()]); + Tag::create(['name' => Generator::random()]); $post->tags()->attach(Tag::all()); @@ -439,9 +440,9 @@ public function testFindOrFailMethodWithMany() $this->expectException(ModelNotFoundException::class); $this->expectExceptionMessage('No query results for model [Illuminate\Tests\Integration\Database\EloquentBelongsToManyTest\Tag] 10, 11'); - $post = Post::create(['title' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); - Tag::create(['name' => Str::random()]); + Tag::create(['name' => Generator::random()]); $post->tags()->attach(Tag::all()); @@ -453,9 +454,9 @@ public function testFindOrFailMethodWithManyUsingCollection() $this->expectException(ModelNotFoundException::class); $this->expectExceptionMessage('No query results for model [Illuminate\Tests\Integration\Database\EloquentBelongsToManyTest\Tag] 10, 11'); - $post = Post::create(['title' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); - Tag::create(['name' => Str::random()]); + Tag::create(['name' => Generator::random()]); $post->tags()->attach(Tag::all()); @@ -464,9 +465,9 @@ public function testFindOrFailMethodWithManyUsingCollection() public function testFindOrNewMethod() { - $post = Post::create(['title' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); - $tag = Tag::create(['name' => Str::random()]); + $tag = Tag::create(['name' => Generator::random()]); $post->tags()->attach(Tag::all()); @@ -478,8 +479,8 @@ public function testFindOrNewMethod() public function testFindOrMethod() { - $post = Post::create(['title' => Str::random()]); - $post->tags()->create(['name' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); + $post->tags()->create(['name' => Generator::random()]); $result = $post->tags()->findOr(1, fn () => 'callback result'); $this->assertInstanceOf(Tag::class, $result); @@ -497,10 +498,10 @@ public function testFindOrMethod() public function testFindOrMethodWithMany() { - $post = Post::create(['title' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); $post->tags()->createMany([ - ['name' => Str::random()], - ['name' => Str::random()], + ['name' => Generator::random()], + ['name' => Generator::random()], ]); $result = $post->tags()->findOr([1, 2], fn () => 'callback result'); @@ -523,10 +524,10 @@ public function testFindOrMethodWithMany() public function testFindOrMethodWithManyUsingCollection() { - $post = Post::create(['title' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); $post->tags()->createMany([ - ['name' => Str::random()], - ['name' => Str::random()], + ['name' => Generator::random()], + ['name' => Generator::random()], ]); $result = $post->tags()->findOr(new Collection([1, 2]), fn () => 'callback result'); @@ -549,9 +550,9 @@ public function testFindOrMethodWithManyUsingCollection() public function testFirstOrNewMethod() { - $post = Post::create(['title' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); - $tag = Tag::create(['name' => Str::random()]); + $tag = Tag::create(['name' => Generator::random()]); $post->tags()->attach(Tag::all()); @@ -563,9 +564,9 @@ public function testFirstOrNewMethod() // public function testFirstOrNewUnrelatedExisting() // { - // $post = Post::create(['title' => Str::random()]); + // $post = Post::create(['title' => Generator::random()]); - // $name = Str::random(); + // $name = Generator::random(); // $tag = Tag::create(['name' => $name]); // $postTag = $post->tags()->firstOrNew(['name' => $name]); @@ -576,9 +577,9 @@ public function testFirstOrNewMethod() public function testFirstOrCreateMethod() { - $post = Post::create(['title' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); - $tag = Tag::create(['name' => Str::random()]); + $tag = Tag::create(['name' => Generator::random()]); $post->tags()->attach(Tag::all()); @@ -591,9 +592,9 @@ public function testFirstOrCreateMethod() public function testFirstOrCreateUnrelatedExisting() { - $post = Post::create(['title' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); - $name = Str::random(); + $name = Generator::random(); $tag = Tag::create(['name' => $name]); $postTag = $post->tags()->firstOrCreate(['name' => $name]); @@ -604,9 +605,9 @@ public function testFirstOrCreateUnrelatedExisting() public function testCreateOrFirst() { - $post = Post::create(['title' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); - $tag = UniqueTag::create(['name' => Str::random()]); + $tag = UniqueTag::create(['name' => Generator::random()]); $post->tagsUnique()->attach(UniqueTag::all()); @@ -619,9 +620,9 @@ public function testCreateOrFirst() public function testCreateOrFirstUnrelatedExisting() { - $post = Post::create(['title' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); - $name = Str::random(); + $name = Generator::random(); $tag = UniqueTag::create(['name' => $name]); $postTag = $post->tagsUnique()->createOrFirst(['name' => $name]); @@ -632,9 +633,9 @@ public function testCreateOrFirstUnrelatedExisting() public function testCreateOrFirstWithinTransaction() { - $post = Post::create(['title' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); - $tag = UniqueTag::create(['name' => Str::random()]); + $tag = UniqueTag::create(['name' => Generator::random()]); $post->tagsUnique()->attach(UniqueTag::all()); @@ -645,8 +646,8 @@ public function testCreateOrFirstWithinTransaction() public function testFirstOrNewMethodWithValues() { - $post = Post::create(['title' => Str::random()]); - $tag = Tag::create(['name' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); + $tag = Tag::create(['name' => Generator::random()]); $post->tags()->attach(Tag::all()); $existing = $post->tags()->firstOrNew( @@ -675,8 +676,8 @@ public function testFirstOrNewMethodWithValues() public function testFirstOrCreateMethodWithValues() { - $post = Post::create(['title' => Str::random()]); - $tag = Tag::create(['name' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); + $tag = Tag::create(['name' => Generator::random()]); $post->tags()->attach(Tag::all()); $existing = $post->tags()->firstOrCreate( @@ -707,9 +708,9 @@ public function testFirstOrCreateMethodWithValues() public function testUpdateOrCreateMethod() { - $post = Post::create(['title' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); - $tag = Tag::create(['name' => Str::random()]); + $tag = Tag::create(['name' => Generator::random()]); $post->tags()->attach(Tag::all()); @@ -722,7 +723,7 @@ public function testUpdateOrCreateMethod() public function testUpdateOrCreateUnrelatedExisting() { - $post = Post::create(['title' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); $tag = Tag::create(['name' => 'foo']); @@ -736,7 +737,7 @@ public function testUpdateOrCreateUnrelatedExisting() public function testUpdateOrCreateMethodCreate() { - $post = Post::create(['title' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); $post->tags()->updateOrCreate(['name' => 'wavez'], ['type' => 'featured']); @@ -748,12 +749,12 @@ public function testUpdateOrCreateMethodCreate() public function testSyncMethod() { - $post = Post::create(['title' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); - $tag = Tag::create(['name' => Str::random()]); - $tag2 = Tag::create(['name' => Str::random()]); - $tag3 = Tag::create(['name' => Str::random()]); - $tag4 = Tag::create(['name' => Str::random()]); + $tag = Tag::create(['name' => Generator::random()]); + $tag2 = Tag::create(['name' => Generator::random()]); + $tag3 = Tag::create(['name' => Generator::random()]); + $tag4 = Tag::create(['name' => Generator::random()]); $post->tags()->sync([$tag->id, $tag2->id]); @@ -791,10 +792,10 @@ public function testSyncMethod() public function testSyncWithoutDetachingMethod() { - $post = Post::create(['title' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); - $tag = Tag::create(['name' => Str::random()]); - $tag2 = Tag::create(['name' => Str::random()]); + $tag = Tag::create(['name' => Generator::random()]); + $tag2 = Tag::create(['name' => Generator::random()]); $post->tags()->sync([$tag->id]); @@ -813,10 +814,10 @@ public function testSyncWithoutDetachingMethod() public function testToggleMethod() { - $post = Post::create(['title' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); - $tag = Tag::create(['name' => Str::random()]); - $tag2 = Tag::create(['name' => Str::random()]); + $tag = Tag::create(['name' => Generator::random()]); + $tag2 = Tag::create(['name' => Generator::random()]); $post->tags()->toggle([$tag->id]); @@ -843,9 +844,9 @@ public function testToggleMethod() public function testTouchingParent() { - $post = Post::create(['title' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); - $tag = TouchingTag::create(['name' => Str::random()]); + $tag = TouchingTag::create(['name' => Generator::random()]); $post->touchingTags()->attach([$tag->id]); @@ -856,15 +857,15 @@ public function testTouchingParent() $tag->update(['name' => $tag->name]); $this->assertNotSame('2017-10-10 10:10:10', $post->fresh()->updated_at->toDateTimeString()); - $tag->update(['name' => Str::random()]); + $tag->update(['name' => Generator::random()]); $this->assertSame('2017-10-10 10:10:10', $post->fresh()->updated_at->toDateTimeString()); } public function testTouchingRelatedModelsOnSync() { - $tag = TouchingTag::create(['name' => Str::random()]); + $tag = TouchingTag::create(['name' => Generator::random()]); - $post = Post::create(['title' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); $this->assertNotSame('2017-10-10 10:10:10', $post->fresh()->updated_at->toDateTimeString()); $this->assertNotSame('2017-10-10 10:10:10', $tag->fresh()->updated_at->toDateTimeString()); @@ -879,9 +880,9 @@ public function testTouchingRelatedModelsOnSync() public function testNoTouchingHappensIfNotConfigured() { - $tag = Tag::create(['name' => Str::random()]); + $tag = Tag::create(['name' => Generator::random()]); - $post = Post::create(['title' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); $this->assertNotSame('2017-10-10 10:10:10', $post->fresh()->updated_at->toDateTimeString()); $this->assertNotSame('2017-10-10 10:10:10', $tag->fresh()->updated_at->toDateTimeString()); @@ -896,11 +897,11 @@ public function testNoTouchingHappensIfNotConfigured() public function testCanRetrieveRelatedIds() { - $post = Post::create(['title' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); DB::table('tags')->insert([ ['name' => 'excluded'], - ['name' => Str::random()], + ['name' => Generator::random()], ]); DB::table('posts_tags')->insert([ @@ -914,11 +915,11 @@ public function testCanRetrieveRelatedIds() public function testCanTouchRelatedModels() { - $post = Post::create(['title' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); DB::table('tags')->insert([ - ['name' => Str::random()], - ['name' => Str::random()], + ['name' => Generator::random()], + ['name' => Generator::random()], ]); DB::table('posts_tags')->insert([ @@ -940,8 +941,8 @@ public function testCanTouchRelatedModels() public function testWherePivotOnString() { - $tag = Tag::create(['name' => Str::random()])->fresh(); - $post = Post::create(['title' => Str::random()]); + $tag = Tag::create(['name' => Generator::random()])->fresh(); + $post = Post::create(['title' => Generator::random()]); DB::table('posts_tags')->insert([ ['post_id' => $post->id, 'tag_id' => $tag->id, 'flag' => 'foo'], @@ -957,7 +958,7 @@ public function testWherePivotOnString() public function testFirstWhere() { $tag = Tag::create(['name' => 'foo'])->fresh(); - $post = Post::create(['title' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); DB::table('posts_tags')->insert([ ['post_id' => $post->id, 'tag_id' => $tag->id, 'flag' => 'foo'], @@ -972,8 +973,8 @@ public function testFirstWhere() public function testWherePivotOnBoolean() { - $tag = Tag::create(['name' => Str::random()])->fresh(); - $post = Post::create(['title' => Str::random()]); + $tag = Tag::create(['name' => Generator::random()])->fresh(); + $post = Post::create(['title' => Generator::random()]); DB::table('posts_tags')->insert([ ['post_id' => $post->id, 'tag_id' => $tag->id, 'flag' => true], @@ -988,8 +989,8 @@ public function testWherePivotOnBoolean() public function testOrWherePivotOnBoolean() { - $tag = Tag::create(['name' => Str::random()])->fresh(); - $post = Post::create(['title' => Str::random()]); + $tag = Tag::create(['name' => Generator::random()])->fresh(); + $post = Post::create(['title' => Generator::random()]); DB::table('posts_tags')->insert([ ['post_id' => $post->id, 'tag_id' => $tag->id, 'flag' => true, 'isActive' => false], @@ -1001,8 +1002,8 @@ public function testOrWherePivotOnBoolean() public function testWherePivotNotBetween() { - $tag = Tag::create(['name' => Str::random()])->fresh(); - $post = Post::create(['title' => Str::random()]); + $tag = Tag::create(['name' => Generator::random()])->fresh(); + $post = Post::create(['title' => Generator::random()]); DB::table('posts_tags')->insert([ ['post_id' => $post->id, 'tag_id' => $tag->id, 'flag' => true, 'isActive' => false], @@ -1018,8 +1019,8 @@ public function testWherePivotNotBetween() public function testWherePivotInMethod() { - $tag = Tag::create(['name' => Str::random()])->fresh(); - $post = Post::create(['title' => Str::random()]); + $tag = Tag::create(['name' => Generator::random()])->fresh(); + $post = Post::create(['title' => Generator::random()]); DB::table('posts_tags')->insert([ ['post_id' => $post->id, 'tag_id' => $tag->id, 'flag' => 'foo'], @@ -1031,10 +1032,10 @@ public function testWherePivotInMethod() public function testOrWherePivotInMethod() { - $tag1 = Tag::create(['name' => Str::random()]); - $tag2 = Tag::create(['name' => Str::random()]); - $tag3 = Tag::create(['name' => Str::random()]); - $post = Post::create(['title' => Str::random()]); + $tag1 = Tag::create(['name' => Generator::random()]); + $tag2 = Tag::create(['name' => Generator::random()]); + $tag3 = Tag::create(['name' => Generator::random()]); + $post = Post::create(['title' => Generator::random()]); DB::table('posts_tags')->insert([ ['post_id' => $post->id, 'tag_id' => $tag1->id, 'flag' => 'foo'], @@ -1052,9 +1053,9 @@ public function testOrWherePivotInMethod() public function testWherePivotNotInMethod() { - $tag1 = Tag::create(['name' => Str::random()]); - $tag2 = Tag::create(['name' => Str::random()])->fresh(); - $post = Post::create(['title' => Str::random()]); + $tag1 = Tag::create(['name' => Generator::random()]); + $tag2 = Tag::create(['name' => Generator::random()])->fresh(); + $post = Post::create(['title' => Generator::random()]); DB::table('posts_tags')->insert([ ['post_id' => $post->id, 'tag_id' => $tag1->id, 'flag' => 'foo'], @@ -1069,10 +1070,10 @@ public function testWherePivotNotInMethod() public function testOrWherePivotNotInMethod() { - $tag1 = Tag::create(['name' => Str::random()]); - $tag2 = Tag::create(['name' => Str::random()]); - $tag3 = Tag::create(['name' => Str::random()]); - $post = Post::create(['title' => Str::random()]); + $tag1 = Tag::create(['name' => Generator::random()]); + $tag2 = Tag::create(['name' => Generator::random()]); + $tag3 = Tag::create(['name' => Generator::random()]); + $post = Post::create(['title' => Generator::random()]); DB::table('posts_tags')->insert([ ['post_id' => $post->id, 'tag_id' => $tag1->id, 'flag' => 'foo'], @@ -1090,9 +1091,9 @@ public function testOrWherePivotNotInMethod() public function testWherePivotNullMethod() { - $tag1 = Tag::create(['name' => Str::random()]); - $tag2 = Tag::create(['name' => Str::random()])->fresh(); - $post = Post::create(['title' => Str::random()]); + $tag1 = Tag::create(['name' => Generator::random()]); + $tag2 = Tag::create(['name' => Generator::random()])->fresh(); + $post = Post::create(['title' => Generator::random()]); DB::table('posts_tags')->insert([ ['post_id' => $post->id, 'tag_id' => $tag1->id, 'flag' => 'foo'], @@ -1107,9 +1108,9 @@ public function testWherePivotNullMethod() public function testWherePivotNotNullMethod() { - $tag1 = Tag::create(['name' => Str::random()])->fresh(); - $tag2 = Tag::create(['name' => Str::random()]); - $post = Post::create(['title' => Str::random()]); + $tag1 = Tag::create(['name' => Generator::random()])->fresh(); + $tag2 = Tag::create(['name' => Generator::random()]); + $post = Post::create(['title' => Generator::random()]); DB::table('posts_tags')->insert([ ['post_id' => $post->id, 'tag_id' => $tag1->id, 'flag' => 'foo', 'isActive' => true], @@ -1124,8 +1125,8 @@ public function testWherePivotNotNullMethod() public function testCanUpdateExistingPivot() { - $tag = Tag::create(['name' => Str::random()]); - $post = Post::create(['title' => Str::random()]); + $tag = Tag::create(['name' => Generator::random()]); + $post = Post::create(['title' => Generator::random()]); DB::table('posts_tags')->insert([ ['post_id' => $post->id, 'tag_id' => $tag->id, 'flag' => 'empty'], @@ -1141,10 +1142,10 @@ public function testCanUpdateExistingPivot() public function testCanUpdateExistingPivotUsingArrayableOfIds() { $tags = new Collection([ - $tag1 = Tag::create(['name' => Str::random()]), - $tag2 = Tag::create(['name' => Str::random()]), + $tag1 = Tag::create(['name' => Generator::random()]), + $tag2 = Tag::create(['name' => Generator::random()]), ]); - $post = Post::create(['title' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); DB::table('posts_tags')->insert([ ['post_id' => $post->id, 'tag_id' => $tag1->id, 'flag' => 'empty'], @@ -1160,8 +1161,8 @@ public function testCanUpdateExistingPivotUsingArrayableOfIds() public function testCanUpdateExistingPivotUsingModel() { - $tag = Tag::create(['name' => Str::random()]); - $post = Post::create(['title' => Str::random()]); + $tag = Tag::create(['name' => Generator::random()]); + $post = Post::create(['title' => Generator::random()]); DB::table('posts_tags')->insert([ ['post_id' => $post->id, 'tag_id' => $tag->id, 'flag' => 'empty'], @@ -1176,9 +1177,9 @@ public function testCanUpdateExistingPivotUsingModel() public function testCustomRelatedKey() { - $post = Post::create(['title' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); - $tag = $post->tagsWithCustomRelatedKey()->create(['name' => Str::random()]); + $tag = $post->tagsWithCustomRelatedKey()->create(['name' => Generator::random()]); $this->assertEquals($tag->name, $post->tagsWithCustomRelatedKey()->first()->pivot->tag_name); $post->tagsWithCustomRelatedKey()->detach($tag); @@ -1197,8 +1198,8 @@ public function testCustomRelatedKey() public function testGlobalScopeColumns() { - $tag = Tag::create(['name' => Str::random()]); - $post = Post::create(['title' => Str::random()]); + $tag = Tag::create(['name' => Generator::random()]); + $post = Post::create(['title' => Generator::random()]); DB::table('posts_tags')->insert([ ['post_id' => $post->id, 'tag_id' => $tag->id, 'flag' => 'empty'], @@ -1211,9 +1212,9 @@ public function testGlobalScopeColumns() public function testPivotDoesntHavePrimaryKey() { - $user = User::create(['name' => Str::random()]); - $post1 = Post::create(['title' => Str::random()]); - $post2 = Post::create(['title' => Str::random()]); + $user = User::create(['name' => Generator::random()]); + $post1 = Post::create(['title' => Generator::random()]); + $post2 = Post::create(['title' => Generator::random()]); $user->postsWithCustomPivot()->sync([$post1->uuid]); $this->assertEquals($user->uuid, $user->postsWithCustomPivot()->first()->pivot->user_uuid); @@ -1231,11 +1232,11 @@ public function testPivotDoesntHavePrimaryKey() public function testOrderByPivotMethod() { - $tag1 = Tag::create(['name' => Str::random()]); - $tag2 = Tag::create(['name' => Str::random()])->fresh(); - $tag3 = Tag::create(['name' => Str::random()])->fresh(); - $tag4 = Tag::create(['name' => Str::random()]); - $post = Post::create(['title' => Str::random()]); + $tag1 = Tag::create(['name' => Generator::random()]); + $tag2 = Tag::create(['name' => Generator::random()])->fresh(); + $tag3 = Tag::create(['name' => Generator::random()])->fresh(); + $tag4 = Tag::create(['name' => Generator::random()]); + $post = Post::create(['title' => Generator::random()]); DB::table('posts_tags')->insert([ ['post_id' => $post->id, 'tag_id' => $tag1->id, 'flag' => 'foo3'], @@ -1253,12 +1254,12 @@ public function testOrderByPivotMethod() public function testFirstOrMethod() { - $user1 = User::create(['name' => Str::random()]); - $user2 = User::create(['name' => Str::random()]); - $user3 = User::create(['name' => Str::random()]); - $post1 = Post::create(['title' => Str::random()]); - $post2 = Post::create(['title' => Str::random()]); - $post3 = Post::create(['title' => Str::random()]); + $user1 = User::create(['name' => Generator::random()]); + $user2 = User::create(['name' => Generator::random()]); + $user3 = User::create(['name' => Generator::random()]); + $post1 = Post::create(['title' => Generator::random()]); + $post2 = Post::create(['title' => Generator::random()]); + $post3 = Post::create(['title' => Generator::random()]); $user1->posts()->sync([$post1->uuid, $post2->uuid]); $user2->posts()->sync([$post1->uuid, $post2->uuid]); @@ -1266,7 +1267,7 @@ public function testFirstOrMethod() $this->assertEquals( $post1->id, $user2->posts()->firstOr(function () { - return Post::create(['title' => Str::random()]); + return Post::create(['title' => Generator::random()]); })->id ); @@ -1280,14 +1281,14 @@ public function testFirstOrMethod() public function testUpdateOrCreateQueryBuilderIsolation() { - $user = User::create(['name' => Str::random()]); - $post = Post::create(['title' => Str::random()]); + $user = User::create(['name' => Generator::random()]); + $post = Post::create(['title' => Generator::random()]); $user->postsWithCustomPivot()->attach($post); $instance = $user->postsWithCustomPivot()->updateOrCreate( ['uuid' => $post->uuid], - ['title' => Str::random()], + ['title' => Generator::random()], ); $this->assertArrayNotHasKey( @@ -1298,14 +1299,14 @@ public function testUpdateOrCreateQueryBuilderIsolation() public function testFirstOrCreateQueryBuilderIsolation() { - $user = User::create(['name' => Str::random()]); - $post = Post::create(['title' => Str::random()]); + $user = User::create(['name' => Generator::random()]); + $post = Post::create(['title' => Generator::random()]); $user->postsWithCustomPivot()->attach($post); $instance = $user->postsWithCustomPivot()->firstOrCreate( ['uuid' => $post->uuid], - ['title' => Str::random()], + ['title' => Generator::random()], ); $this->assertArrayNotHasKey( @@ -1326,7 +1327,7 @@ protected static function boot() parent::boot(); static::creating(function ($model) { - $model->setAttribute('uuid', Str::random()); + $model->setAttribute('uuid', Generator::random()); }); } @@ -1394,7 +1395,7 @@ protected static function boot() parent::boot(); static::creating(function ($model) { - $model->setAttribute('uuid', Str::random()); + $model->setAttribute('uuid', Generator::random()); }); } diff --git a/tests/Integration/Database/EloquentBelongsToTest.php b/tests/Integration/Database/EloquentBelongsToTest.php index 13492efefb6c..964b1a6056e2 100644 --- a/tests/Integration/Database/EloquentBelongsToTest.php +++ b/tests/Integration/Database/EloquentBelongsToTest.php @@ -5,6 +5,7 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use Illuminate\Tests\Integration\Database\DatabaseTestCase; @@ -19,7 +20,7 @@ protected function afterRefreshingDatabase() $table->string('parent_slug')->nullable(); }); - $user = User::create(['slug' => Str::random()]); + $user = User::create(['slug' => Generator::random()]); User::create(['parent_id' => $user->id, 'parent_slug' => $user->slug]); } diff --git a/tests/Integration/Database/EloquentHasManyTest.php b/tests/Integration/Database/EloquentHasManyTest.php index b8add9b8a72e..2aee426bf393 100644 --- a/tests/Integration/Database/EloquentHasManyTest.php +++ b/tests/Integration/Database/EloquentHasManyTest.php @@ -7,6 +7,7 @@ use Illuminate\Database\Eloquent\Relations\HasOne; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; +use Illuminate\Support\Generator; use Illuminate\Support\Str; class EloquentHasManyTest extends DatabaseTestCase @@ -65,7 +66,7 @@ public function testFirstOrCreate() { $user = EloquentHasManyTestUser::create(); - $post1 = $user->posts()->create(['title' => Str::random()]); + $post1 = $user->posts()->create(['title' => Generator::random()]); $post2 = $user->posts()->firstOrCreate(['title' => $post1->title]); $this->assertTrue($post1->is($post2)); @@ -76,7 +77,7 @@ public function testFirstOrCreateWithinTransaction() { $user = EloquentHasManyTestUser::create(); - $post1 = $user->posts()->create(['title' => Str::random()]); + $post1 = $user->posts()->create(['title' => Generator::random()]); DB::transaction(function () use ($user, $post1) { $post2 = $user->posts()->firstOrCreate(['title' => $post1->title]); @@ -91,7 +92,7 @@ public function testCreateOrFirst() { $user = EloquentHasManyTestUser::create(); - $post1 = $user->posts()->createOrFirst(['title' => Str::random()]); + $post1 = $user->posts()->createOrFirst(['title' => Generator::random()]); $post2 = $user->posts()->createOrFirst(['title' => $post1->title]); $this->assertTrue($post1->is($post2)); @@ -102,7 +103,7 @@ public function testCreateOrFirstWithinTransaction() { $user = EloquentHasManyTestUser::create(); - $post1 = $user->posts()->create(['title' => Str::random()]); + $post1 = $user->posts()->create(['title' => Generator::random()]); DB::transaction(function () use ($user, $post1) { $post2 = $user->posts()->createOrFirst(['title' => $post1->title]); diff --git a/tests/Integration/Database/EloquentHasManyThroughTest.php b/tests/Integration/Database/EloquentHasManyThroughTest.php index 68e8363182b4..4a0b01169cc3 100644 --- a/tests/Integration/Database/EloquentHasManyThroughTest.php +++ b/tests/Integration/Database/EloquentHasManyThroughTest.php @@ -7,6 +7,7 @@ use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use Illuminate\Tests\Integration\Database\DatabaseTestCase; @@ -48,7 +49,7 @@ protected function afterRefreshingDatabase() public function testBasicCreateAndRetrieve() { - $user = User::create(['name' => Str::random()]); + $user = User::create(['name' => Generator::random()]); $team1 = Team::create(['owner_id' => $user->id]); $team2 = Team::create(['owner_id' => $user->id]); @@ -56,7 +57,7 @@ public function testBasicCreateAndRetrieve() $mate1 = User::create(['name' => 'John', 'team_id' => $team1->id]); $mate2 = User::create(['name' => 'Jack', 'team_id' => $team2->id, 'slug' => null]); - User::create(['name' => Str::random()]); + User::create(['name' => Generator::random()]); $this->assertEquals([$mate1->id, $mate2->id], $user->teamMates->pluck('id')->toArray()); $this->assertEquals([$mate1->id, $mate2->id], $user->teamMatesWithPendingRelation->pluck('id')->toArray()); @@ -90,11 +91,11 @@ public function testBasicCreateAndRetrieve() public function testGlobalScopeColumns() { - $user = User::create(['name' => Str::random()]); + $user = User::create(['name' => Generator::random()]); $team1 = Team::create(['owner_id' => $user->id]); - User::create(['name' => Str::random(), 'team_id' => $team1->id]); + User::create(['name' => Generator::random(), 'team_id' => $team1->id]); $teamMates = $user->teamMatesWithGlobalScope; $this->assertEquals(['id' => 2, 'laravel_through_key' => 1], $teamMates[0]->getAttributes()); @@ -105,11 +106,11 @@ public function testGlobalScopeColumns() public function testHasSelf() { - $user = User::create(['name' => Str::random()]); + $user = User::create(['name' => Generator::random()]); $team = Team::create(['owner_id' => $user->id]); - User::create(['name' => Str::random(), 'team_id' => $team->id]); + User::create(['name' => Generator::random(), 'team_id' => $team->id]); $users = User::has('teamMates')->get(); $this->assertCount(1, $users); @@ -120,11 +121,11 @@ public function testHasSelf() public function testHasSelfCustomOwnerKey() { - $user = User::create(['slug' => Str::random(), 'name' => Str::random()]); + $user = User::create(['slug' => Generator::random(), 'name' => Generator::random()]); $team = Team::create(['owner_slug' => $user->slug]); - User::create(['name' => Str::random(), 'team_id' => $team->id]); + User::create(['name' => Generator::random(), 'team_id' => $team->id]); $users = User::has('teamMatesBySlug')->get(); $this->assertCount(1, $users); diff --git a/tests/Integration/Database/EloquentModelTest.php b/tests/Integration/Database/EloquentModelTest.php index d4ad6c207437..9f23e44da27c 100644 --- a/tests/Integration/Database/EloquentModelTest.php +++ b/tests/Integration/Database/EloquentModelTest.php @@ -6,6 +6,7 @@ use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Schema; +use Illuminate\Support\Generator; use Illuminate\Support\Str; class EloquentModelTest extends DatabaseTestCase @@ -42,7 +43,7 @@ public function testUserCanUpdateNullableDate() public function testAttributeChanges() { $user = TestModel2::create([ - 'name' => Str::random(), 'title' => Str::random(), + 'name' => Generator::random(), 'title' => Generator::random(), ]); $this->assertEmpty($user->getDirty()); @@ -50,7 +51,7 @@ public function testAttributeChanges() $this->assertFalse($user->isDirty()); $this->assertFalse($user->wasChanged()); - $user->name = $name = Str::random(); + $user->name = $name = Generator::random(); $this->assertEquals(['name' => $name], $user->getDirty()); $this->assertEmpty($user->getChanges()); @@ -68,7 +69,7 @@ public function testAttributeChanges() public function testDiscardChanges() { $user = TestModel2::create([ - 'name' => $originalName = Str::random(), 'title' => Str::random(), + 'name' => $originalName = Generator::random(), 'title' => Generator::random(), ]); $this->assertEmpty($user->getDirty()); @@ -76,7 +77,7 @@ public function testDiscardChanges() $this->assertFalse($user->isDirty()); $this->assertFalse($user->wasChanged()); - $user->name = $overrideName = Str::random(); + $user->name = $overrideName = Generator::random(); $this->assertEquals(['name' => $overrideName], $user->getDirty()); $this->assertEmpty($user->getChanges()); diff --git a/tests/Integration/Database/EloquentMorphManyTest.php b/tests/Integration/Database/EloquentMorphManyTest.php index b2dff448bba2..37f169ee7195 100644 --- a/tests/Integration/Database/EloquentMorphManyTest.php +++ b/tests/Integration/Database/EloquentMorphManyTest.php @@ -7,6 +7,7 @@ use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Schema; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use Illuminate\Tests\Integration\Database\DatabaseTestCase; @@ -31,7 +32,7 @@ protected function afterRefreshingDatabase() public function testUpdateModelWithDefaultWithCount() { - $post = Post::create(['title' => Str::random()]); + $post = Post::create(['title' => Generator::random()]); $post->update(['title' => 'new name']); diff --git a/tests/Integration/Database/EloquentTouchParentWithGlobalScopeTest.php b/tests/Integration/Database/EloquentTouchParentWithGlobalScopeTest.php index e29cabb591ee..38ae67f4d485 100644 --- a/tests/Integration/Database/EloquentTouchParentWithGlobalScopeTest.php +++ b/tests/Integration/Database/EloquentTouchParentWithGlobalScopeTest.php @@ -5,6 +5,7 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use Illuminate\Tests\Integration\Database\DatabaseTestCase; @@ -28,11 +29,11 @@ protected function afterRefreshingDatabase() public function testBasicCreateAndRetrieve() { - $post = Post::create(['title' => Str::random(), 'updated_at' => '2016-10-10 10:10:10']); + $post = Post::create(['title' => Generator::random(), 'updated_at' => '2016-10-10 10:10:10']); $this->assertSame('2016-10-10', $post->fresh()->updated_at->toDateString()); - $post->comments()->create(['title' => Str::random()]); + $post->comments()->create(['title' => Generator::random()]); $this->assertNotSame('2016-10-10', $post->fresh()->updated_at->toDateString()); } diff --git a/tests/Integration/Database/EloquentUniqueStringPrimaryKeysTest.php b/tests/Integration/Database/EloquentUniqueStringPrimaryKeysTest.php index 83724b65267d..d19135651e58 100644 --- a/tests/Integration/Database/EloquentUniqueStringPrimaryKeysTest.php +++ b/tests/Integration/Database/EloquentUniqueStringPrimaryKeysTest.php @@ -7,6 +7,7 @@ use Illuminate\Database\Eloquent\Model as Eloquent; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; +use Illuminate\Support\PatternMatcher; use Illuminate\Support\Str; class EloquentUniqueStringPrimaryKeysTest extends DatabaseTestCase @@ -51,9 +52,9 @@ public function testModelWithUuidPrimaryKeyCanBeCreated() { $user = ModelWithUuidPrimaryKey::create(); - $this->assertTrue(Str::isUuid($user->id)); - $this->assertTrue(Str::isUuid($user->foo)); - $this->assertTrue(Str::isUuid($user->bar)); + $this->assertTrue(PatternMatcher::isUuid($user->id)); + $this->assertTrue(PatternMatcher::isUuid($user->foo)); + $this->assertTrue(PatternMatcher::isUuid($user->bar)); } public function testModelWithUlidPrimaryKeyCanBeCreated() @@ -70,15 +71,15 @@ public function testModelWithoutUuidPrimaryKeyCanBeCreated() $user = ModelWithoutUuidPrimaryKey::create(); $this->assertTrue(is_int($user->id)); - $this->assertTrue(Str::isUuid($user->foo)); - $this->assertTrue(Str::isUuid($user->bar)); + $this->assertTrue(PatternMatcher::isUuid($user->foo)); + $this->assertTrue(PatternMatcher::isUuid($user->bar)); } public function testModelWithCustomUuidPrimaryKeyNameCanBeCreated() { $user = ModelWithCustomUuidPrimaryKeyName::create(); - $this->assertTrue(Str::isUuid($user->uuid)); + $this->assertTrue(PatternMatcher::isUuid($user->uuid)); } public function testModelWithUuidPrimaryKeyCanBeCreatedQuietly() @@ -87,9 +88,9 @@ public function testModelWithUuidPrimaryKeyCanBeCreatedQuietly() $user->saveQuietly(); - $this->assertTrue(Str::isUuid($user->id)); - $this->assertTrue(Str::isUuid($user->foo)); - $this->assertTrue(Str::isUuid($user->bar)); + $this->assertTrue(PatternMatcher::isUuid($user->id)); + $this->assertTrue(PatternMatcher::isUuid($user->foo)); + $this->assertTrue(PatternMatcher::isUuid($user->bar)); } public function testModelWithUlidPrimaryKeyCanBeCreatedQuietly() @@ -110,8 +111,8 @@ public function testModelWithoutUuidPrimaryKeyCanBeCreatedQuietly() $user->saveQuietly(); $this->assertTrue(is_int($user->id)); - $this->assertTrue(Str::isUuid($user->foo)); - $this->assertTrue(Str::isUuid($user->bar)); + $this->assertTrue(PatternMatcher::isUuid($user->foo)); + $this->assertTrue(PatternMatcher::isUuid($user->bar)); } public function testModelWithCustomUuidPrimaryKeyNameCanBeCreatedQuietly() @@ -120,7 +121,7 @@ public function testModelWithCustomUuidPrimaryKeyNameCanBeCreatedQuietly() $user->saveQuietly(); - $this->assertTrue(Str::isUuid($user->uuid)); + $this->assertTrue(PatternMatcher::isUuid($user->uuid)); } public function testUpsertWithUuidPrimaryKey() diff --git a/tests/Integration/Database/EloquentUpdateTest.php b/tests/Integration/Database/EloquentUpdateTest.php index 68fdc26993a2..1df27dd39261 100644 --- a/tests/Integration/Database/EloquentUpdateTest.php +++ b/tests/Integration/Database/EloquentUpdateTest.php @@ -6,6 +6,7 @@ use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; +use Illuminate\Support\Generator; use Illuminate\Support\Str; class EloquentUpdateTest extends DatabaseTestCase @@ -37,7 +38,7 @@ protected function afterRefreshingDatabase() public function testBasicUpdate() { TestUpdateModel1::create([ - 'name' => Str::random(), + 'name' => Generator::random(), 'title' => 'Ms.', ]); @@ -70,7 +71,7 @@ public function testUpdatedAtWithJoins() ]); TestUpdateModel2::create([ - 'name' => Str::random(), + 'name' => Generator::random(), ]); TestUpdateModel2::join('test_model1', function ($join) { @@ -86,12 +87,12 @@ public function testUpdatedAtWithJoins() public function testSoftDeleteWithJoins() { TestUpdateModel1::create([ - 'name' => Str::random(), + 'name' => Generator::random(), 'title' => 'Mr.', ]); TestUpdateModel2::create([ - 'name' => Str::random(), + 'name' => Generator::random(), ]); TestUpdateModel2::join('test_model1', function ($join) { diff --git a/tests/Integration/Database/MySql/JoinLateralTest.php b/tests/Integration/Database/MySql/JoinLateralTest.php index 29770adf97ba..c5303e83855c 100644 --- a/tests/Integration/Database/MySql/JoinLateralTest.php +++ b/tests/Integration/Database/MySql/JoinLateralTest.php @@ -5,6 +5,7 @@ use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use PHPUnit\Framework\Attributes\RequiresOperatingSystemFamily; use PHPUnit\Framework\Attributes\RequiresPhpExtension; @@ -41,14 +42,14 @@ protected function setUp(): void $this->checkMySqlVersion(); DB::table('users')->insert([ - ['name' => Str::random()], - ['name' => Str::random()], + ['name' => Generator::random()], + ['name' => Generator::random()], ]); DB::table('posts')->insert([ - ['title' => Str::random(), 'rating' => 1, 'user_id' => 1], - ['title' => Str::random(), 'rating' => 3, 'user_id' => 1], - ['title' => Str::random(), 'rating' => 7, 'user_id' => 1], + ['title' => Generator::random(), 'rating' => 1, 'user_id' => 1], + ['title' => Generator::random(), 'rating' => 3, 'user_id' => 1], + ['title' => Generator::random(), 'rating' => 7, 'user_id' => 1], ]); } diff --git a/tests/Integration/Database/Postgres/JoinLateralTest.php b/tests/Integration/Database/Postgres/JoinLateralTest.php index acab3781316b..edff78e73fe7 100644 --- a/tests/Integration/Database/Postgres/JoinLateralTest.php +++ b/tests/Integration/Database/Postgres/JoinLateralTest.php @@ -5,6 +5,7 @@ use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use PHPUnit\Framework\Attributes\RequiresOperatingSystemFamily; use PHPUnit\Framework\Attributes\RequiresPhpExtension; @@ -39,14 +40,14 @@ protected function setUp(): void parent::setUp(); DB::table('users')->insert([ - ['name' => Str::random()], - ['name' => Str::random()], + ['name' => Generator::random()], + ['name' => Generator::random()], ]); DB::table('posts')->insert([ - ['title' => Str::random(), 'rating' => 1, 'user_id' => 1], - ['title' => Str::random(), 'rating' => 3, 'user_id' => 1], - ['title' => Str::random(), 'rating' => 7, 'user_id' => 1], + ['title' => Generator::random(), 'rating' => 1, 'user_id' => 1], + ['title' => Generator::random(), 'rating' => 3, 'user_id' => 1], + ['title' => Generator::random(), 'rating' => 7, 'user_id' => 1], ]); } diff --git a/tests/Integration/Database/SqlServer/JoinLateralTest.php b/tests/Integration/Database/SqlServer/JoinLateralTest.php index df11c5517585..e0ea8feceb70 100644 --- a/tests/Integration/Database/SqlServer/JoinLateralTest.php +++ b/tests/Integration/Database/SqlServer/JoinLateralTest.php @@ -5,6 +5,7 @@ use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; +use Illuminate\Support\Generator; use Illuminate\Support\Str; class JoinLateralTest extends SqlServerTestCase @@ -35,14 +36,14 @@ protected function setUp(): void parent::setUp(); DB::table('users')->insert([ - ['name' => Str::random()], - ['name' => Str::random()], + ['name' => Generator::random()], + ['name' => Generator::random()], ]); DB::table('posts')->insert([ - ['title' => Str::random(), 'rating' => 1, 'user_id' => 1], - ['title' => Str::random(), 'rating' => 3, 'user_id' => 1], - ['title' => Str::random(), 'rating' => 7, 'user_id' => 1], + ['title' => Generator::random(), 'rating' => 1, 'user_id' => 1], + ['title' => Generator::random(), 'rating' => 3, 'user_id' => 1], + ['title' => Generator::random(), 'rating' => 7, 'user_id' => 1], ]); } diff --git a/tests/Integration/Database/Sqlite/EloquentModelConnectionsTest.php b/tests/Integration/Database/Sqlite/EloquentModelConnectionsTest.php index 83be9c20df25..54ac479a8327 100644 --- a/tests/Integration/Database/Sqlite/EloquentModelConnectionsTest.php +++ b/tests/Integration/Database/Sqlite/EloquentModelConnectionsTest.php @@ -5,6 +5,7 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use Orchestra\Testbench\Attributes\RequiresDatabase; use Orchestra\Testbench\TestCase; @@ -56,14 +57,14 @@ protected function defineDatabaseMigrations() public function testChildObeysParentConnection() { - $parent1 = ParentModel::create(['name' => Str::random()]); + $parent1 = ParentModel::create(['name' => Generator::random()]); $parent1->children()->create(['name' => 'childOnConn1']); $parents1 = ParentModel::with('children')->get(); $this->assertSame('childOnConn1', ChildModel::on('conn1')->first()->name); $this->assertSame('childOnConn1', $parent1->children()->first()->name); $this->assertSame('childOnConn1', $parents1[0]->children[0]->name); - $parent2 = ParentModel::on('conn2')->create(['name' => Str::random()]); + $parent2 = ParentModel::on('conn2')->create(['name' => Generator::random()]); $parent2->children()->create(['name' => 'childOnConn2']); $parents2 = ParentModel::on('conn2')->with('children')->get(); $this->assertSame('childOnConn2', ChildModel::on('conn2')->first()->name); @@ -73,7 +74,7 @@ public function testChildObeysParentConnection() public function testChildUsesItsOwnConnectionIfSet() { - $parent1 = ParentModel::create(['name' => Str::random()]); + $parent1 = ParentModel::create(['name' => Generator::random()]); $parent1->childrenDefaultConn2()->create(['name' => 'childAlwaysOnConn2']); $parents1 = ParentModel::with('childrenDefaultConn2')->get(); $this->assertSame('childAlwaysOnConn2', ChildModelDefaultConn2::first()->name); @@ -84,7 +85,7 @@ public function testChildUsesItsOwnConnectionIfSet() public function testChildUsesItsOwnConnectionIfSetEvenIfParentExplicitConnection() { - $parent1 = ParentModel::on('conn1')->create(['name' => Str::random()]); + $parent1 = ParentModel::on('conn1')->create(['name' => Generator::random()]); $parent1->childrenDefaultConn2()->create(['name' => 'childAlwaysOnConn2']); $parents1 = ParentModel::on('conn1')->with('childrenDefaultConn2')->get(); $this->assertSame('childAlwaysOnConn2', ChildModelDefaultConn2::first()->name); diff --git a/tests/Integration/Foundation/Support/Providers/RouteServiceProviderHealthTest.php b/tests/Integration/Foundation/Support/Providers/RouteServiceProviderHealthTest.php index 1a341eb33a10..18ac414b9954 100644 --- a/tests/Integration/Foundation/Support/Providers/RouteServiceProviderHealthTest.php +++ b/tests/Integration/Foundation/Support/Providers/RouteServiceProviderHealthTest.php @@ -3,6 +3,7 @@ namespace Illuminate\Tests\Integration\Foundation\Support\Providers; use Illuminate\Foundation\Application; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use Orchestra\Testbench\TestCase; @@ -24,7 +25,7 @@ protected function resolveApplication() protected function defineEnvironment($app) { - $app['config']->set('app.key', Str::random(32)); + $app['config']->set('app.key', Generator::random(32)); } public function test_it_can_load_health_page() diff --git a/tests/Integration/Queue/JobEncryptionTest.php b/tests/Integration/Queue/JobEncryptionTest.php index 704c08001074..2c2faea5060c 100644 --- a/tests/Integration/Queue/JobEncryptionTest.php +++ b/tests/Integration/Queue/JobEncryptionTest.php @@ -11,6 +11,7 @@ use Illuminate\Support\Facades\Bus; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Queue; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use Illuminate\Tests\Integration\Database\DatabaseTestCase; use Orchestra\Testbench\Attributes\WithMigration; @@ -25,7 +26,7 @@ protected function getEnvironmentSetUp($app) { parent::getEnvironmentSetUp($app); - $app['config']->set('app.key', Str::random(32)); + $app['config']->set('app.key', Generator::random(32)); $app['config']->set('queue.default', 'database'); } diff --git a/tests/Integration/Queue/RateLimitedWithRedisTest.php b/tests/Integration/Queue/RateLimitedWithRedisTest.php index 1306c7d232c4..e34c7280bfa3 100644 --- a/tests/Integration/Queue/RateLimitedWithRedisTest.php +++ b/tests/Integration/Queue/RateLimitedWithRedisTest.php @@ -12,6 +12,7 @@ use Illuminate\Queue\CallQueuedHandler; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\Middleware\RateLimitedWithRedis; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use Mockery as m; use Orchestra\Testbench\TestCase; @@ -194,7 +195,7 @@ class RedisRateLimitedTestJob public function __construct() { - $this->key = Str::random(10); + $this->key = Generator::random(10); } public function handle() diff --git a/tests/Integration/Queue/ThrottlesExceptionsWithRedisTest.php b/tests/Integration/Queue/ThrottlesExceptionsWithRedisTest.php index 59cc8f77b412..e83ce73ea4bb 100644 --- a/tests/Integration/Queue/ThrottlesExceptionsWithRedisTest.php +++ b/tests/Integration/Queue/ThrottlesExceptionsWithRedisTest.php @@ -12,6 +12,7 @@ use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\Middleware\ThrottlesExceptionsWithRedis; use Illuminate\Support\Carbon; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use Mockery as m; use Orchestra\Testbench\TestCase; @@ -41,21 +42,21 @@ protected function tearDown(): void public function testCircuitIsOpenedForJobErrors() { - $this->assertJobWasReleasedImmediately(CircuitBreakerWithRedisTestJob::class, $key = Str::random()); + $this->assertJobWasReleasedImmediately(CircuitBreakerWithRedisTestJob::class, $key = Generator::random()); $this->assertJobWasReleasedImmediately(CircuitBreakerWithRedisTestJob::class, $key); $this->assertJobWasReleasedWithDelay(CircuitBreakerWithRedisTestJob::class, $key); } public function testCircuitStaysClosedForSuccessfulJobs() { - $this->assertJobRanSuccessfully(CircuitBreakerWithRedisSuccessfulJob::class, $key = Str::random()); + $this->assertJobRanSuccessfully(CircuitBreakerWithRedisSuccessfulJob::class, $key = Generator::random()); $this->assertJobRanSuccessfully(CircuitBreakerWithRedisSuccessfulJob::class, $key); $this->assertJobRanSuccessfully(CircuitBreakerWithRedisSuccessfulJob::class, $key); } public function testCircuitResetsAfterSuccess() { - $this->assertJobWasReleasedImmediately(CircuitBreakerWithRedisTestJob::class, $key = Str::random()); + $this->assertJobWasReleasedImmediately(CircuitBreakerWithRedisTestJob::class, $key = Generator::random()); $this->assertJobRanSuccessfully(CircuitBreakerWithRedisSuccessfulJob::class, $key); $this->assertJobWasReleasedImmediately(CircuitBreakerWithRedisTestJob::class, $key); $this->assertJobWasReleasedImmediately(CircuitBreakerWithRedisTestJob::class, $key); diff --git a/tests/Integration/Session/CookieSessionHandlerTest.php b/tests/Integration/Session/CookieSessionHandlerTest.php index a392ebaefb1f..10286126f3df 100644 --- a/tests/Integration/Session/CookieSessionHandlerTest.php +++ b/tests/Integration/Session/CookieSessionHandlerTest.php @@ -3,6 +3,7 @@ namespace Illuminate\Tests\Integration\Session; use Illuminate\Support\Facades\Route; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use Orchestra\Testbench\TestCase; @@ -41,7 +42,7 @@ public function testCookieSessionInheritsRequestSecureState() protected function defineEnvironment($app) { - $app['config']->set('app.key', Str::random(32)); + $app['config']->set('app.key', Generator::random(32)); $app['config']->set('session.driver', 'cookie'); $app['config']->set('session.expire_on_close', true); } diff --git a/tests/Integration/Session/SessionPersistenceTest.php b/tests/Integration/Session/SessionPersistenceTest.php index 6253b79eb766..a0bb24d942d1 100644 --- a/tests/Integration/Session/SessionPersistenceTest.php +++ b/tests/Integration/Session/SessionPersistenceTest.php @@ -8,6 +8,7 @@ use Illuminate\Session\TokenMismatchException; use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Session; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use Mockery as m; use Orchestra\Testbench\TestCase; @@ -40,7 +41,7 @@ protected function defineEnvironment($app) $handler->shouldReceive('render')->andReturn(new Response); - $app['config']->set('app.key', Str::random(32)); + $app['config']->set('app.key', Generator::random(32)); $app['config']->set('session.driver', 'fake-null'); $app['config']->set('session.expire_on_close', true); } diff --git a/tests/Integration/Support/PluralizerPortugueseTest.php b/tests/Integration/Support/PluralizerPortugueseTest.php index d788c98629d3..70486d1640ae 100644 --- a/tests/Integration/Support/PluralizerPortugueseTest.php +++ b/tests/Integration/Support/PluralizerPortugueseTest.php @@ -3,7 +3,7 @@ namespace Illuminate\Tests\Integration\Support; use Illuminate\Support\Pluralizer; -use Illuminate\Support\Str; +use Illuminate\Support\StrGrammar; use Orchestra\Testbench\TestCase; class PluralizerPortugueseTest extends TestCase @@ -24,64 +24,64 @@ protected function tearDown(): void public function testBasicSingular() { - $this->assertSame('herói', Str::singular('heróis')); - $this->assertSame('irmão', Str::singular('irmãos')); - $this->assertSame('chafariz', Str::singular('chafarizes')); - $this->assertSame('colher', Str::singular('colheres')); - $this->assertSame('modelo', Str::singular('modelos')); - $this->assertSame('venda', Str::singular('vendas')); - $this->assertSame('usuário', Str::singular('usuários')); - $this->assertSame('comissão', Str::singular('comissões')); + $this->assertSame('herói', StrGrammar::singular('heróis')); + $this->assertSame('irmão', StrGrammar::singular('irmãos')); + $this->assertSame('chafariz', StrGrammar::singular('chafarizes')); + $this->assertSame('colher', StrGrammar::singular('colheres')); + $this->assertSame('modelo', StrGrammar::singular('modelos')); + $this->assertSame('venda', StrGrammar::singular('vendas')); + $this->assertSame('usuário', StrGrammar::singular('usuários')); + $this->assertSame('comissão', StrGrammar::singular('comissões')); } public function testIrregulars() { - $this->assertSame('males', Str::plural('mal')); - $this->assertSame('lápis', Str::singular('lápis')); + $this->assertSame('males', StrGrammar::plural('mal')); + $this->assertSame('lápis', StrGrammar::singular('lápis')); } public function testBasicPlural() { - $this->assertSame('fênix', Str::plural('fênix')); - $this->assertSame('palavras', Str::plural('palavra')); - $this->assertSame('modelos', Str::plural('modelo')); - $this->assertSame('vendas', Str::plural('venda')); - $this->assertSame('usuários', Str::plural('usuário')); - $this->assertSame('comissões', Str::plural('comissão')); + $this->assertSame('fênix', StrGrammar::plural('fênix')); + $this->assertSame('palavras', StrGrammar::plural('palavra')); + $this->assertSame('modelos', StrGrammar::plural('modelo')); + $this->assertSame('vendas', StrGrammar::plural('venda')); + $this->assertSame('usuários', StrGrammar::plural('usuário')); + $this->assertSame('comissões', StrGrammar::plural('comissão')); } public function testCaseSensitiveSingularUsage() { - $this->assertSame('Criança', Str::singular('Crianças')); - $this->assertSame('CIDADÃO', Str::singular('CIDADÃOS')); + $this->assertSame('Criança', StrGrammar::singular('Crianças')); + $this->assertSame('CIDADÃO', StrGrammar::singular('CIDADÃOS')); } public function testCaseSensitiveSingularPlural() { - $this->assertSame('Crianças', Str::plural('Criança')); - $this->assertSame('CIDADÃOS', Str::plural('CIDADÃO')); - $this->assertSame('Testes', Str::plural('Teste')); + $this->assertSame('Crianças', StrGrammar::plural('Criança')); + $this->assertSame('CIDADÃOS', StrGrammar::plural('CIDADÃO')); + $this->assertSame('Testes', StrGrammar::plural('Teste')); } public function testPluralAppliedForStringEndingWithNumericCharacter() { - $this->assertSame('Usuário1s', Str::plural('Usuário1')); - $this->assertSame('Usuário2s', Str::plural('Usuário2')); - $this->assertSame('Usuário3s', Str::plural('Usuário3')); + $this->assertSame('Usuário1s', StrGrammar::plural('Usuário1')); + $this->assertSame('Usuário2s', StrGrammar::plural('Usuário2')); + $this->assertSame('Usuário3s', StrGrammar::plural('Usuário3')); } public function testPluralSupportsArrays() { - $this->assertSame('usuários', Str::plural('usuário', [])); - $this->assertSame('usuário', Str::plural('usuário', ['um'])); - $this->assertSame('usuários', Str::plural('usuário', ['um', 'dois'])); + $this->assertSame('usuários', StrGrammar::plural('usuário', [])); + $this->assertSame('usuário', StrGrammar::plural('usuário', ['um'])); + $this->assertSame('usuários', StrGrammar::plural('usuário', ['um', 'dois'])); } public function testPluralSupportsCollections() { - $this->assertSame('usuários', Str::plural('usuário', collect())); - $this->assertSame('usuário', Str::plural('usuário', collect(['um']))); - $this->assertSame('usuários', Str::plural('usuário', collect(['um', 'dois']))); + $this->assertSame('usuários', StrGrammar::plural('usuário', collect())); + $this->assertSame('usuário', StrGrammar::plural('usuário', collect(['um']))); + $this->assertSame('usuários', StrGrammar::plural('usuário', collect(['um', 'dois']))); } public function testPluralStudlySupportsArrays() @@ -100,6 +100,6 @@ public function testPluralStudlySupportsCollections() private function assertPluralStudly($expected, $value, $count = 2) { - $this->assertSame($expected, Str::pluralStudly($value, $count)); + $this->assertSame($expected, StrGrammar::pluralStudly($value, $count)); } } diff --git a/tests/Routing/RoutingRouteTest.php b/tests/Routing/RoutingRouteTest.php index bb7964a7b07b..14eed794b48f 100644 --- a/tests/Routing/RoutingRouteTest.php +++ b/tests/Routing/RoutingRouteTest.php @@ -37,6 +37,7 @@ use Illuminate\Routing\RouteGroup; use Illuminate\Routing\Router; use Illuminate\Routing\UrlGenerator; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use LogicException; use PHPUnit\Framework\TestCase; @@ -682,37 +683,37 @@ public function testControllerCallActionMethodParameters() // Has one argument but receives two unset($_SERVER['__test.controller_callAction_parameters']); - $router->get(($str = Str::random()).'/{one}/{two}', RouteTestAnotherControllerWithParameterStub::class.'@oneArgument'); + $router->get(($str = Generator::random()).'/{one}/{two}', RouteTestAnotherControllerWithParameterStub::class.'@oneArgument'); $router->dispatch(Request::create($str.'/one/two', 'GET')); $this->assertEquals(['one' => 'one', 'two' => 'two'], $_SERVER['__test.controller_callAction_parameters']); // Has two arguments and receives two unset($_SERVER['__test.controller_callAction_parameters']); - $router->get(($str = Str::random()).'/{one}/{two}', RouteTestAnotherControllerWithParameterStub::class.'@twoArguments'); + $router->get(($str = Generator::random()).'/{one}/{two}', RouteTestAnotherControllerWithParameterStub::class.'@twoArguments'); $router->dispatch(Request::create($str.'/one/two', 'GET')); $this->assertEquals(['one' => 'one', 'two' => 'two'], $_SERVER['__test.controller_callAction_parameters']); // Has two arguments but with different names from the ones passed from the route unset($_SERVER['__test.controller_callAction_parameters']); - $router->get(($str = Str::random()).'/{one}/{two}', RouteTestAnotherControllerWithParameterStub::class.'@differentArgumentNames'); + $router->get(($str = Generator::random()).'/{one}/{two}', RouteTestAnotherControllerWithParameterStub::class.'@differentArgumentNames'); $router->dispatch(Request::create($str.'/one/two', 'GET')); $this->assertEquals(['one' => 'one', 'two' => 'two'], $_SERVER['__test.controller_callAction_parameters']); // Has two arguments with same name but argument order is reversed unset($_SERVER['__test.controller_callAction_parameters']); - $router->get(($str = Str::random()).'/{one}/{two}', RouteTestAnotherControllerWithParameterStub::class.'@reversedArguments'); + $router->get(($str = Generator::random()).'/{one}/{two}', RouteTestAnotherControllerWithParameterStub::class.'@reversedArguments'); $router->dispatch(Request::create($str.'/one/two', 'GET')); $this->assertEquals(['one' => 'one', 'two' => 'two'], $_SERVER['__test.controller_callAction_parameters']); // No route parameters while method has parameters unset($_SERVER['__test.controller_callAction_parameters']); - $router->get(($str = Str::random()).'', RouteTestAnotherControllerWithParameterStub::class.'@oneArgument'); + $router->get(($str = Generator::random()).'', RouteTestAnotherControllerWithParameterStub::class.'@oneArgument'); $router->dispatch(Request::create($str, 'GET')); $this->assertEquals([], $_SERVER['__test.controller_callAction_parameters']); // With model bindings unset($_SERVER['__test.controller_callAction_parameters']); - $router->get(($str = Str::random()).'/{user}/{defaultNull?}/{team?}', [ + $router->get(($str = Generator::random()).'/{user}/{defaultNull?}/{team?}', [ 'middleware' => SubstituteBindings::class, 'uses' => RouteTestAnotherControllerWithParameterStub::class.'@withModels', ]); diff --git a/tests/Session/SessionStoreTest.php b/tests/Session/SessionStoreTest.php index f4f4fb8e5fbb..8f12ae6b8e27 100644 --- a/tests/Session/SessionStoreTest.php +++ b/tests/Session/SessionStoreTest.php @@ -5,6 +5,7 @@ use Illuminate\Cookie\CookieJar; use Illuminate\Session\CookieSessionHandler; use Illuminate\Session\Store; +use Illuminate\Support\Generator; use Illuminate\Support\MessageBag; use Illuminate\Support\Str; use Illuminate\Support\ViewErrorBag; @@ -127,7 +128,7 @@ public function testSessionIsProperlyUpdated() { $session = $this->getSession(); $session->getHandler()->shouldReceive('read')->once()->andReturn(serialize([ - '_token' => Str::random(40), + '_token' => Generator::random(40), 'foo' => 'bar', 'baz' => 'boom', '_flash' => [ @@ -158,7 +159,7 @@ public function testSessionIsReSavedWhenNothingHasChanged() { $session = $this->getSession(); $session->getHandler()->shouldReceive('read')->once()->andReturn(serialize([ - '_token' => Str::random(40), + '_token' => Generator::random(40), 'foo' => 'bar', 'baz' => 'boom', '_flash' => [ @@ -190,7 +191,7 @@ public function testSessionIsReSavedWhenNothingHasChangedExceptSessionId() { $session = $this->getSession(); $oldId = $session->getId(); - $token = Str::random(40); + $token = Generator::random(40); $session->getHandler()->shouldReceive('read')->once()->with($oldId)->andReturn(serialize([ '_token' => $token, 'foo' => 'bar', From ebe7b85bea2c16de370c7234ffb4cd4c74ae4878 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20H=C3=A4drich?= Date: Mon, 30 Sep 2024 18:01:18 +0200 Subject: [PATCH 07/14] refactor: :recycle: Next batch of class adjustments --- src/Illuminate/Bus/Batchable.php | 3 +- .../Bus/DatabaseBatchRepository.php | 3 +- src/Illuminate/Bus/DynamoBatchRepository.php | 3 +- .../Database/Eloquent/Concerns/HasUlids.php | 3 +- .../Eloquent/Concerns/HasVersion4Uuids.php | 3 +- .../Notifications/NotificationSender.php | 5 +-- src/Illuminate/Queue/Jobs/FakeJob.php | 3 +- src/Illuminate/Queue/Queue.php | 5 +-- src/Illuminate/Support/Casing.php | 10 +++--- .../Support/Defer/DeferredCallback.php | 3 +- src/Illuminate/Support/Generator.php | 12 +++---- src/Illuminate/Support/Replacer.php | 6 ++-- .../Testing/Fakes/BatchRepositoryFake.php | 3 +- .../Testing/Fakes/NotificationFake.php | 3 +- src/Illuminate/Support/composer.json | 4 +-- .../Concerns/CompilesConditionals.php | 3 +- .../Compilers/Concerns/CompilesStacks.php | 5 +-- .../SendingMailNotificationsTest.php | 17 +++++----- tests/Integration/Queue/DynamoBatchTest.php | 7 ++-- tests/Integration/Queue/RedisQueueTest.php | 3 +- .../Integration/Validation/ValidatorTest.php | 5 +-- tests/Log/ContextTest.php | 25 +++++++------- tests/Queue/DatabaseFailedJobProviderTest.php | 33 ++++++++++--------- .../DatabaseUuidFailedJobProviderTest.php | 31 ++++++++--------- tests/Queue/DynamoDbFailedJobProviderTest.php | 5 +-- tests/Queue/FileFailedJobProviderTest.php | 5 +-- tests/Queue/QueueBeanstalkdQueueTest.php | 11 ++++--- .../QueueDatabaseQueueIntegrationTest.php | 3 +- tests/Queue/QueueDatabaseQueueUnitTest.php | 13 ++++---- tests/Queue/QueueRedisQueueTest.php | 23 ++++++------- 30 files changed, 142 insertions(+), 116 deletions(-) diff --git a/src/Illuminate/Bus/Batchable.php b/src/Illuminate/Bus/Batchable.php index 5cf5706070e9..c817ee170416 100644 --- a/src/Illuminate/Bus/Batchable.php +++ b/src/Illuminate/Bus/Batchable.php @@ -3,6 +3,7 @@ namespace Illuminate\Bus; use Carbon\CarbonImmutable; +use Generator; use Illuminate\Container\Container; use Illuminate\Support\Str; use Illuminate\Support\Testing\Fakes\BatchFake; @@ -91,7 +92,7 @@ public function withFakeBatch(string $id = '', ?CarbonImmutable $finishedAt = null) { $this->fakeBatch = new BatchFake( - empty($id) ? (string) Str::uuid() : $id, + empty($id) ? (string) Generator::uuid() : $id, $name, $totalJobs, $pendingJobs, diff --git a/src/Illuminate/Bus/DatabaseBatchRepository.php b/src/Illuminate/Bus/DatabaseBatchRepository.php index d6130ede6c63..395d1f2847e2 100644 --- a/src/Illuminate/Bus/DatabaseBatchRepository.php +++ b/src/Illuminate/Bus/DatabaseBatchRepository.php @@ -8,6 +8,7 @@ use Illuminate\Database\Connection; use Illuminate\Database\PostgresConnection; use Illuminate\Database\Query\Expression; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use Throwable; @@ -94,7 +95,7 @@ public function find(string $batchId) */ public function store(PendingBatch $batch) { - $id = (string) Str::orderedUuid(); + $id = (string) Generator::orderedUuid(); $this->connection->table($this->table)->insert([ 'id' => $id, diff --git a/src/Illuminate/Bus/DynamoBatchRepository.php b/src/Illuminate/Bus/DynamoBatchRepository.php index c93d7ae7881a..1215196e1d11 100644 --- a/src/Illuminate/Bus/DynamoBatchRepository.php +++ b/src/Illuminate/Bus/DynamoBatchRepository.php @@ -6,6 +6,7 @@ use Aws\DynamoDb\Marshaler; use Carbon\CarbonImmutable; use Closure; +use Illuminate\Support\Generator; use Illuminate\Support\Str; class DynamoBatchRepository implements BatchRepository @@ -162,7 +163,7 @@ public function find(string $batchId) */ public function store(PendingBatch $batch) { - $id = (string) Str::orderedUuid(); + $id = (string) Generator::orderedUuid(); $batch = [ 'id' => $id, diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasUlids.php b/src/Illuminate/Database/Eloquent/Concerns/HasUlids.php index 85a810db5ee1..b7d4f4f8836e 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasUlids.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasUlids.php @@ -3,6 +3,7 @@ namespace Illuminate\Database\Eloquent\Concerns; use Illuminate\Database\Eloquent\ModelNotFoundException; +use Illuminate\Support\Generator; use Illuminate\Support\Str; trait HasUlids @@ -34,7 +35,7 @@ public function uniqueIds() */ public function newUniqueId() { - return strtolower((string) Str::ulid()); + return strtolower((string) Generator::ulid()); } /** diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasVersion4Uuids.php b/src/Illuminate/Database/Eloquent/Concerns/HasVersion4Uuids.php index eac53c67ba8d..0f182ec9b6a9 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasVersion4Uuids.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasVersion4Uuids.php @@ -2,6 +2,7 @@ namespace Illuminate\Database\Eloquent\Concerns; +use Illuminate\Support\Generator; use Illuminate\Support\Str; trait HasVersion4Uuids @@ -15,6 +16,6 @@ trait HasVersion4Uuids */ public function newUniqueId() { - return (string) Str::orderedUuid(); + return (string) Generator::orderedUuid(); } } diff --git a/src/Illuminate/Notifications/NotificationSender.php b/src/Illuminate/Notifications/NotificationSender.php index f82f02279372..3cb30f54a818 100644 --- a/src/Illuminate/Notifications/NotificationSender.php +++ b/src/Illuminate/Notifications/NotificationSender.php @@ -9,6 +9,7 @@ use Illuminate\Notifications\Events\NotificationSending; use Illuminate\Notifications\Events\NotificationSent; use Illuminate\Support\Collection; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use Illuminate\Support\Traits\Localizable; @@ -99,7 +100,7 @@ public function sendNow($notifiables, $notification, ?array $channels = null) } $this->withLocale($this->preferredLocale($notifiable, $notification), function () use ($viaChannels, $notifiable, $original) { - $notificationId = Str::uuid()->toString(); + $notificationId = Generator::uuid()->toString(); foreach ((array) $viaChannels as $channel) { if (! ($notifiable instanceof AnonymousNotifiable && $channel === 'database')) { @@ -186,7 +187,7 @@ protected function queueNotification($notifiables, $notification) $original = clone $notification; foreach ($notifiables as $notifiable) { - $notificationId = Str::uuid()->toString(); + $notificationId = Generator::uuid()->toString(); foreach ((array) $original->via($notifiable) as $channel) { $notification = clone $original; diff --git a/src/Illuminate/Queue/Jobs/FakeJob.php b/src/Illuminate/Queue/Jobs/FakeJob.php index ef1d4e8bc04a..fdadeff0221b 100644 --- a/src/Illuminate/Queue/Jobs/FakeJob.php +++ b/src/Illuminate/Queue/Jobs/FakeJob.php @@ -2,6 +2,7 @@ namespace Illuminate\Queue\Jobs; +use Illuminate\Support\Generator; use Illuminate\Support\Str; class FakeJob extends Job @@ -34,7 +35,7 @@ class FakeJob extends Job */ public function getJobId() { - return once(fn () => (string) Str::uuid()); + return once(fn () => (string) Generator::uuid()); } /** diff --git a/src/Illuminate/Queue/Queue.php b/src/Illuminate/Queue/Queue.php index 7b08da689dae..acd76f69268d 100755 --- a/src/Illuminate/Queue/Queue.php +++ b/src/Illuminate/Queue/Queue.php @@ -11,6 +11,7 @@ use Illuminate\Queue\Events\JobQueued; use Illuminate\Queue\Events\JobQueueing; use Illuminate\Support\Arr; +use Illuminate\Support\Generator; use Illuminate\Support\InteractsWithTime; use Illuminate\Support\Str; @@ -140,7 +141,7 @@ protected function createPayloadArray($job, $queue, $data = '') protected function createObjectPayload($job, $queue) { $payload = $this->withCreatePayloadHooks($queue, [ - 'uuid' => (string) Str::uuid(), + 'uuid' => (string) Generator::uuid(), 'displayName' => $this->getDisplayName($job), 'job' => 'Illuminate\Queue\CallQueuedHandler@call', 'maxTries' => $this->getJobTries($job) ?? null, @@ -267,7 +268,7 @@ protected function jobShouldBeEncrypted($job) protected function createStringPayload($job, $queue, $data) { return $this->withCreatePayloadHooks($queue, [ - 'uuid' => (string) Str::uuid(), + 'uuid' => (string) Generator::uuid(), 'displayName' => is_string($job) ? explode('@', $job)[0] : null, 'job' => $job, 'maxTries' => null, diff --git a/src/Illuminate/Support/Casing.php b/src/Illuminate/Support/Casing.php index 059f158dba96..3abca6e4960a 100644 --- a/src/Illuminate/Support/Casing.php +++ b/src/Illuminate/Support/Casing.php @@ -114,9 +114,9 @@ public static function headline($value) $parts = count($parts) > 1 ? array_map([static::class, 'title'], $parts) - : array_map([static::class, 'title'], static::ucsplit(implode('_', $parts))); + : array_map([static::class, 'title'], Str::ucsplit(implode('_', $parts))); - $collapsed = static::replace(['-', '_', ' '], '_', implode('_', $parts)); + $collapsed = Str::replace(['-', '_', ' '], '_', implode('_', $parts)); return implode(' ', array_filter(explode('_', $collapsed))); } @@ -129,7 +129,7 @@ public static function headline($value) */ public static function lcfirst($string) { - return static::lower(static::substr($string, 0, 1)).static::substr($string, 1); + return static::lower(Str::substr($string, 0, 1)).Str::substr($string, 1); } /** @@ -140,7 +140,7 @@ public static function lcfirst($string) */ public static function ucfirst($string) { - return static::upper(static::substr($string, 0, 1)).static::substr($string, 1); + return static::upper(Str::substr($string, 0, 1)).Str::substr($string, 1); } /** @@ -181,7 +181,7 @@ public static function studly($value) return static::$studlyCache[$key]; } - $words = explode(' ', static::replace(['-', '_'], ' ', $value)); + $words = explode(' ', Str::replace(['-', '_'], ' ', $value)); $studlyWords = array_map(fn ($word) => static::ucfirst($word), $words); diff --git a/src/Illuminate/Support/Defer/DeferredCallback.php b/src/Illuminate/Support/Defer/DeferredCallback.php index 2bf6ad4cbd1c..b7032b3631af 100644 --- a/src/Illuminate/Support/Defer/DeferredCallback.php +++ b/src/Illuminate/Support/Defer/DeferredCallback.php @@ -2,6 +2,7 @@ namespace Illuminate\Support\Defer; +use Illuminate\Support\Generator; use Illuminate\Support\Str; class DeferredCallback @@ -14,7 +15,7 @@ class DeferredCallback */ public function __construct(public $callback, public ?string $name = null, public bool $always = false) { - $this->name = $name ?? (string) Str::uuid(); + $this->name = $name ?? (string) Generator::uuid(); } /** diff --git a/src/Illuminate/Support/Generator.php b/src/Illuminate/Support/Generator.php index 527c411eb3be..b51abe4b1a70 100644 --- a/src/Illuminate/Support/Generator.php +++ b/src/Illuminate/Support/Generator.php @@ -218,15 +218,15 @@ public static function createUuidsUsingSequence(array $sequence, $whenMissing = */ public static function freezeUuids(?Closure $callback = null) { - $uuid = Str::uuid(); + $uuid = self::uuid(); - Str::createUuidsUsing(fn () => $uuid); + self::createUuidsUsing(fn () => $uuid); if ($callback !== null) { try { $callback($uuid); } finally { - Str::createUuidsNormally(); + self::createUuidsNormally(); } } @@ -325,15 +325,15 @@ public static function createUlidsUsingSequence(array $sequence, $whenMissing = */ public static function freezeUlids(?Closure $callback = null) { - $ulid = Str::ulid(); + $ulid = self::ulid(); - Str::createUlidsUsing(fn () => $ulid); + self::createUlidsUsing(fn () => $ulid); if ($callback !== null) { try { $callback($ulid); } finally { - Str::createUlidsNormally(); + self::createUlidsNormally(); } } diff --git a/src/Illuminate/Support/Replacer.php b/src/Illuminate/Support/Replacer.php index fa4c256029b1..b8ecafe091ff 100644 --- a/src/Illuminate/Support/Replacer.php +++ b/src/Illuminate/Support/Replacer.php @@ -40,7 +40,7 @@ public static function replaceArray($search, $replace, $subject) $result = array_shift($segments); foreach ($segments as $segment) { - $result .= self::toStringOr(array_shift($replace) ?? $search, $search).$segment; + $result .= Str::toStringOr(array_shift($replace) ?? $search, $search).$segment; } return $result; @@ -115,7 +115,7 @@ public static function replaceStart($search, $replace, $subject) return $subject; } - if (static::startsWith($subject, $search)) { + if (Str::startsWith($subject, $search)) { return static::replaceFirst($search, $replace, $subject); } @@ -163,7 +163,7 @@ public static function replaceEnd($search, $replace, $subject) return $subject; } - if (static::endsWith($subject, $search)) { + if (Str::endsWith($subject, $search)) { return static::replaceLast($search, $replace, $subject); } diff --git a/src/Illuminate/Support/Testing/Fakes/BatchRepositoryFake.php b/src/Illuminate/Support/Testing/Fakes/BatchRepositoryFake.php index 2afa4ab94e2c..44ebf84a0a98 100644 --- a/src/Illuminate/Support/Testing/Fakes/BatchRepositoryFake.php +++ b/src/Illuminate/Support/Testing/Fakes/BatchRepositoryFake.php @@ -7,6 +7,7 @@ use Illuminate\Bus\BatchRepository; use Illuminate\Bus\PendingBatch; use Illuminate\Bus\UpdatedBatchJobCounts; +use Illuminate\Support\Generator; use Illuminate\Support\Str; class BatchRepositoryFake implements BatchRepository @@ -49,7 +50,7 @@ public function find(string $batchId) */ public function store(PendingBatch $batch) { - $id = (string) Str::orderedUuid(); + $id = (string) Generator::orderedUuid(); $this->batches[$id] = new BatchFake( $id, diff --git a/src/Illuminate/Support/Testing/Fakes/NotificationFake.php b/src/Illuminate/Support/Testing/Fakes/NotificationFake.php index fceb32d47b83..ae6ea3b55487 100644 --- a/src/Illuminate/Support/Testing/Fakes/NotificationFake.php +++ b/src/Illuminate/Support/Testing/Fakes/NotificationFake.php @@ -10,6 +10,7 @@ use Illuminate\Contracts\Translation\HasLocalePreference; use Illuminate\Notifications\AnonymousNotifiable; use Illuminate\Support\Collection; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use Illuminate\Support\Traits\Macroable; use Illuminate\Support\Traits\ReflectsClosures; @@ -310,7 +311,7 @@ public function sendNow($notifiables, $notification, ?array $channels = null) foreach ($notifiables as $notifiable) { if (! $notification->id) { - $notification->id = Str::uuid()->toString(); + $notification->id = Generator::uuid()->toString(); } $notifiableChannels = $channels ?: $notification->via($notifiable); diff --git a/src/Illuminate/Support/composer.json b/src/Illuminate/Support/composer.json index e3cbe196a03a..efd7de560cb5 100644 --- a/src/Illuminate/Support/composer.json +++ b/src/Illuminate/Support/composer.json @@ -50,9 +50,9 @@ "illuminate/filesystem": "Required to use the composer class (^12.0).", "laravel/serializable-closure": "Required to use the once function (^1.3).", "league/commonmark": "Required to use Str::markdown() and Stringable::markdown() (^2.0.2).", - "ramsey/uuid": "Required to use Str::uuid() (^4.7).", + "ramsey/uuid": "Required to use Generator::uuid() (^4.7).", "symfony/process": "Required to use the composer class (^7.0).", - "symfony/uid": "Required to use Str::ulid() (^7.0).", + "symfony/uid": "Required to use Generator::ulid() (^7.0).", "symfony/var-dumper": "Required to use the dd function (^7.0).", "vlucas/phpdotenv": "Required to use the Env class and env helper (^5.4.1)." }, diff --git a/src/Illuminate/View/Compilers/Concerns/CompilesConditionals.php b/src/Illuminate/View/Compilers/Concerns/CompilesConditionals.php index b26494e822b5..ab0de185175a 100644 --- a/src/Illuminate/View/Compilers/Concerns/CompilesConditionals.php +++ b/src/Illuminate/View/Compilers/Concerns/CompilesConditionals.php @@ -2,6 +2,7 @@ namespace Illuminate\View\Compilers\Concerns; +use Illuminate\Support\Generator; use Illuminate\Support\Str; trait CompilesConditionals @@ -290,7 +291,7 @@ protected function compileEndSwitch() */ protected function compileOnce($id = null) { - $id = $id ? $this->stripParentheses($id) : "'".(string) Str::uuid()."'"; + $id = $id ? $this->stripParentheses($id) : "'".(string) Generator::uuid()."'"; return 'hasRenderedOnce('.$id.')): $__env->markAsRenderedOnce('.$id.'); ?>'; } diff --git a/src/Illuminate/View/Compilers/Concerns/CompilesStacks.php b/src/Illuminate/View/Compilers/Concerns/CompilesStacks.php index 16ceef37ce3e..7b5d1893eced 100644 --- a/src/Illuminate/View/Compilers/Concerns/CompilesStacks.php +++ b/src/Illuminate/View/Compilers/Concerns/CompilesStacks.php @@ -2,6 +2,7 @@ namespace Illuminate\View\Compilers\Concerns; +use Illuminate\Support\Generator; use Illuminate\Support\Str; trait CompilesStacks @@ -40,7 +41,7 @@ protected function compilePushOnce($expression) [$stack, $id] = [$parts[0], $parts[1] ?? '']; - $id = trim($id) ?: "'".(string) Str::uuid()."'"; + $id = trim($id) ?: "'".(string) Generator::uuid()."'"; return 'hasRenderedOnce('.$id.')): $__env->markAsRenderedOnce('.$id.'); $__env->startPush('.$stack.'); ?>'; @@ -89,7 +90,7 @@ protected function compilePrependOnce($expression) [$stack, $id] = [$parts[0], $parts[1] ?? '']; - $id = trim($id) ?: "'".(string) Str::uuid()."'"; + $id = trim($id) ?: "'".(string) Generator::uuid()."'"; return 'hasRenderedOnce('.$id.')): $__env->markAsRenderedOnce('.$id.'); $__env->startPrepend('.$stack.'); ?>'; diff --git a/tests/Integration/Notifications/SendingMailNotificationsTest.php b/tests/Integration/Notifications/SendingMailNotificationsTest.php index 9b59f4c7c0da..3d62cb950246 100644 --- a/tests/Integration/Notifications/SendingMailNotificationsTest.php +++ b/tests/Integration/Notifications/SendingMailNotificationsTest.php @@ -14,6 +14,7 @@ use Illuminate\Notifications\Notifiable; use Illuminate\Notifications\Notification; use Illuminate\Support\Facades\Schema; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use Mockery as m; use Orchestra\Testbench\TestCase; @@ -60,7 +61,7 @@ protected function setUp(): void public function testMailIsSent() { $notification = new TestMailNotification; - $notification->id = Str::uuid()->toString(); + $notification->id = Generator::uuid()->toString(); $user = NotifiableUser::forceCreate([ 'email' => 'taylor@laravel.com', @@ -98,7 +99,7 @@ public function testMailIsSent() public function testMailIsSentWithCustomTheme() { $notification = new TestMailNotificationWithCustomTheme; - $notification->id = Str::uuid()->toString(); + $notification->id = Generator::uuid()->toString(); $user = NotifiableUser::forceCreate([ 'email' => 'taylor@laravel.com', @@ -171,7 +172,7 @@ private function setMailerSendAssertions( public function testMailIsSentToNamedAddress() { $notification = new TestMailNotification; - $notification->id = Str::uuid()->toString(); + $notification->id = Generator::uuid()->toString(); $user = NotifiableUserWithNamedAddress::forceCreate([ 'email' => 'taylor@laravel.com', @@ -210,7 +211,7 @@ public function testMailIsSentToNamedAddress() public function testMailIsSentWithSubject() { $notification = new TestMailNotificationWithSubject; - $notification->id = Str::uuid()->toString(); + $notification->id = Generator::uuid()->toString(); $user = NotifiableUser::forceCreate([ 'email' => 'taylor@laravel.com', @@ -238,7 +239,7 @@ public function testMailIsSentWithSubject() public function testMailIsSentToMultipleAddresses() { $notification = new TestMailNotificationWithSubject; - $notification->id = Str::uuid()->toString(); + $notification->id = Generator::uuid()->toString(); $user = NotifiableUserWithMultipleAddresses::forceCreate([ 'email' => 'taylor@laravel.com', @@ -277,7 +278,7 @@ public function testMailIsSentUsingMailable() public function testMailIsSentUsingMailMessageWithHtmlAndPlain() { $notification = new TestMailNotificationWithHtmlAndPlain; - $notification->id = Str::uuid()->toString(); + $notification->id = Generator::uuid()->toString(); $user = NotifiableUser::forceCreate([ 'email' => 'taylor@laravel.com', @@ -309,7 +310,7 @@ public function testMailIsSentUsingMailMessageWithHtmlAndPlain() public function testMailIsSentUsingMailMessageWithHtmlOnly() { $notification = new TestMailNotificationWithHtmlOnly; - $notification->id = Str::uuid()->toString(); + $notification->id = Generator::uuid()->toString(); $user = NotifiableUser::forceCreate([ 'email' => 'taylor@laravel.com', @@ -341,7 +342,7 @@ public function testMailIsSentUsingMailMessageWithHtmlOnly() public function testMailIsSentUsingMailMessageWithPlainOnly() { $notification = new TestMailNotificationWithPlainOnly; - $notification->id = Str::uuid()->toString(); + $notification->id = Generator::uuid()->toString(); $user = NotifiableUser::forceCreate([ 'email' => 'taylor@laravel.com', diff --git a/tests/Integration/Queue/DynamoBatchTest.php b/tests/Integration/Queue/DynamoBatchTest.php index a395fc414af0..917324056f02 100644 --- a/tests/Integration/Queue/DynamoBatchTest.php +++ b/tests/Integration/Queue/DynamoBatchTest.php @@ -10,6 +10,7 @@ use Illuminate\Queue\InteractsWithQueue; use Illuminate\Support\Env; use Illuminate\Support\Facades\Bus; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use Orchestra\Testbench\Attributes\RequiresEnv; use Orchestra\Testbench\TestCase; @@ -73,7 +74,7 @@ public function test_retrieve_non_existent_batch() { /** @var DynamoBatchRepository */ $repo = app(DynamoBatchRepository::class); - $retrieved = $repo->find(Str::orderedUuid()); + $retrieved = $repo->find(Generator::orderedUuid()); $this->assertNull($retrieved); } @@ -96,7 +97,7 @@ public function test_delete_non_existent_batch() { /** @var DynamoBatchRepository */ $repo = app(DynamoBatchRepository::class); - $repo->delete(Str::orderedUuid()); + $repo->delete(Generator::orderedUuid()); // Ensure we didn't throw an exception $this->assertTrue(true); } @@ -139,7 +140,7 @@ public function test_get_batches() $this->assertCount(6, $repo->get(100, $batches[6]->id)); $this->assertCount(0, $repo->get(100, $batches[0]->id)); $this->assertCount(9, $repo->get(100, $batches[9]->id)); - $this->assertCount(10, $repo->get(100, Str::orderedUuid())); + $this->assertCount(10, $repo->get(100, Generator::orderedUuid())); } } diff --git a/tests/Integration/Queue/RedisQueueTest.php b/tests/Integration/Queue/RedisQueueTest.php index f7120110568d..0d3783978a98 100644 --- a/tests/Integration/Queue/RedisQueueTest.php +++ b/tests/Integration/Queue/RedisQueueTest.php @@ -9,6 +9,7 @@ use Illuminate\Queue\Events\JobQueueing; use Illuminate\Queue\Jobs\RedisJob; use Illuminate\Queue\RedisQueue; +use Illuminate\Support\Generator; use Illuminate\Support\InteractsWithTime; use Illuminate\Support\Str; use Mockery as m; @@ -266,7 +267,7 @@ public function testBlockingPopProperlyPopsExpiredJobs($driver) $this->assertEquals(0, $this->redis[$driver]->connection()->zcard('queues:default:delayed')); $this->assertEquals(2, $this->redis[$driver]->connection()->zcard('queues:default:reserved')); - Str::createUuidsNormally(); + Generator::createUuidsNormally(); } /** diff --git a/tests/Integration/Validation/ValidatorTest.php b/tests/Integration/Validation/ValidatorTest.php index 3dd82a22b0aa..3320dd39182f 100644 --- a/tests/Integration/Validation/ValidatorTest.php +++ b/tests/Integration/Validation/ValidatorTest.php @@ -5,6 +5,7 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use Illuminate\Tests\Integration\Database\DatabaseTestCase; use Illuminate\Translation\ArrayLoader; @@ -24,8 +25,8 @@ protected function setUp(): void $table->string('first_name'); }); - User::create(['uuid' => (string) Str::uuid(), 'first_name' => 'John']); - User::create(['uuid' => (string) Str::uuid(), 'first_name' => 'Jim']); + User::create(['uuid' => (string) Generator::uuid(), 'first_name' => 'John']); + User::create(['uuid' => (string) Generator::uuid(), 'first_name' => 'Jim']); } public function testExists() diff --git a/tests/Log/ContextTest.php b/tests/Log/ContextTest.php index f0eb661e55b6..71e742397598 100644 --- a/tests/Log/ContextTest.php +++ b/tests/Log/ContextTest.php @@ -12,6 +12,7 @@ use Illuminate\Support\Facades\Context; use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Log; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use Orchestra\Testbench\TestCase; use RuntimeException; @@ -293,9 +294,9 @@ public function test_it_adds_context_to_logging() { $path = storage_path('logs/laravel.log'); file_put_contents($path, ''); - Str::createUuidsUsingSequence(['expected-trace-id']); + Generator::createUuidsUsingSequence(['expected-trace-id']); - Context::add('trace_id', Str::uuid()); + Context::add('trace_id', Generator::uuid()); Context::add('foo.bar', 123); Context::push('bar.baz', 456); Context::push('bar.baz', 789); @@ -309,14 +310,14 @@ public function test_it_adds_context_to_logging() $this->assertSame('testing.INFO: My name is Tim {"name":"Tim","framework":"Laravel"} {"trace_id":"expected-trace-id","foo.bar":123,"bar.baz":[456,789]}', trim($log)); file_put_contents($path, ''); - Str::createUuidsNormally(); + Generator::createUuidsNormally(); } public function test_it_doesnt_override_log_instance_context() { $path = storage_path('logs/laravel.log'); file_put_contents($path, ''); - Str::createUuidsUsingSequence(['expected-trace-id']); + Generator::createUuidsUsingSequence(['expected-trace-id']); Context::add('name', 'James'); @@ -328,14 +329,14 @@ public function test_it_doesnt_override_log_instance_context() $this->assertSame('testing.INFO: My name is Tim {"name":"Tim"} {"name":"James"}', trim($log)); file_put_contents($path, ''); - Str::createUuidsNormally(); + Generator::createUuidsNormally(); } public function test_it_doesnt_allow_context_to_be_used_as_parameters() { $path = storage_path('logs/laravel.log'); file_put_contents($path, ''); - Str::createUuidsUsingSequence(['expected-trace-id']); + Generator::createUuidsUsingSequence(['expected-trace-id']); Context::add('name', 'James'); @@ -345,14 +346,14 @@ public function test_it_doesnt_allow_context_to_be_used_as_parameters() $this->assertSame('testing.INFO: My name is {name} {"name":"James"}', trim($log)); file_put_contents($path, ''); - Str::createUuidsNormally(); + Generator::createUuidsNormally(); } public function test_does_not_add_hidden_context_to_logging() { $path = storage_path('logs/laravel.log'); file_put_contents($path, ''); - Str::createUuidsUsingSequence(['expected-trace-id']); + Generator::createUuidsUsingSequence(['expected-trace-id']); Context::addHidden('hidden_data', 'hidden_data'); @@ -365,7 +366,7 @@ public function test_does_not_add_hidden_context_to_logging() $this->assertStringNotContainsString('hidden_data', trim($log)); file_put_contents($path, ''); - Str::createUuidsNormally(); + Generator::createUuidsNormally(); } public function test_it_can_add_hidden() @@ -413,9 +414,9 @@ public function test_it_adds_context_to_logged_exceptions() { $path = storage_path('logs/laravel.log'); file_put_contents($path, ''); - Str::createUuidsUsingSequence(['expected-trace-id']); + Generator::createUuidsUsingSequence(['expected-trace-id']); - Context::add('trace_id', Str::uuid()); + Context::add('trace_id', Generator::uuid()); Context::add('foo.bar', 123); Context::push('bar.baz', 456); Context::push('bar.baz', 789); @@ -426,7 +427,7 @@ public function test_it_adds_context_to_logged_exceptions() $this->assertStringEndsWith(' {"trace_id":"expected-trace-id","foo.bar":123,"bar.baz":[456,789]}', trim($log)); file_put_contents($path, ''); - Str::createUuidsNormally(); + Generator::createUuidsNormally(); } } diff --git a/tests/Queue/DatabaseFailedJobProviderTest.php b/tests/Queue/DatabaseFailedJobProviderTest.php index a8e84a8950c1..235d673d404a 100644 --- a/tests/Queue/DatabaseFailedJobProviderTest.php +++ b/tests/Queue/DatabaseFailedJobProviderTest.php @@ -7,6 +7,7 @@ use Illuminate\Database\Schema\Blueprint; use Illuminate\Queue\Failed\DatabaseFailedJobProvider; use Illuminate\Support\Facades\Date; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use PHPUnit\Framework\TestCase; use RuntimeException; @@ -60,7 +61,7 @@ public function testCanProperlyLogFailedJob() $table->timestamp('failed_at')->useCurrent(); }); - $uuid = Str::uuid(); + $uuid = Generator::uuid(); $exception = new Exception(mb_convert_encoding('ÐÑÙ0E\xE2\x�98\xA0World��7B¹!þÿ', 'ISO-8859-1', 'UTF-8')); $provider = new DatabaseFailedJobProvider($db->getDatabaseManager(), 'default', 'failed_jobs'); @@ -92,11 +93,11 @@ public function testJobsCanBeCounted() $this->assertSame(0, $provider->count()); - $provider->log('database', 'default', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); + $provider->log('database', 'default', json_encode(['uuid' => (string) Generator::uuid()]), new RuntimeException()); $this->assertSame(1, $provider->count()); - $provider->log('database', 'default', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); - $provider->log('another-connection', 'another-queue', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); + $provider->log('database', 'default', json_encode(['uuid' => (string) Generator::uuid()]), new RuntimeException()); + $provider->log('another-connection', 'another-queue', json_encode(['uuid' => (string) Generator::uuid()]), new RuntimeException()); $this->assertSame(3, $provider->count()); } @@ -117,12 +118,12 @@ public function testJobsCanBeCountedByConnection() }); $provider = new DatabaseFailedJobProvider($db->getDatabaseManager(), 'default', 'failed_jobs'); - $provider->log('connection-1', 'default', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); - $provider->log('connection-2', 'default', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); + $provider->log('connection-1', 'default', json_encode(['uuid' => (string) Generator::uuid()]), new RuntimeException()); + $provider->log('connection-2', 'default', json_encode(['uuid' => (string) Generator::uuid()]), new RuntimeException()); $this->assertSame(1, $provider->count('connection-1')); $this->assertSame(1, $provider->count('connection-2')); - $provider->log('connection-1', 'default', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); + $provider->log('connection-1', 'default', json_encode(['uuid' => (string) Generator::uuid()]), new RuntimeException()); $this->assertSame(2, $provider->count('connection-1')); $this->assertSame(1, $provider->count('connection-2')); } @@ -144,12 +145,12 @@ public function testJobsCanBeCountedByQueue() }); $provider = new DatabaseFailedJobProvider($db->getDatabaseManager(), 'default', 'failed_jobs'); - $provider->log('database', 'queue-1', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); - $provider->log('database', 'queue-2', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); + $provider->log('database', 'queue-1', json_encode(['uuid' => (string) Generator::uuid()]), new RuntimeException()); + $provider->log('database', 'queue-2', json_encode(['uuid' => (string) Generator::uuid()]), new RuntimeException()); $this->assertSame(1, $provider->count(queue: 'queue-1')); $this->assertSame(1, $provider->count(queue: 'queue-2')); - $provider->log('database', 'queue-1', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); + $provider->log('database', 'queue-1', json_encode(['uuid' => (string) Generator::uuid()]), new RuntimeException()); $this->assertSame(2, $provider->count(queue: 'queue-1')); $this->assertSame(1, $provider->count(queue: 'queue-2')); } @@ -171,12 +172,12 @@ public function testJobsCanBeCountedByQueueAndConnection() }); $provider = new DatabaseFailedJobProvider($db->getDatabaseManager(), 'default', 'failed_jobs'); - $provider->log('connection-1', 'queue-99', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); - $provider->log('connection-1', 'queue-99', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); - $provider->log('connection-2', 'queue-99', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); - $provider->log('connection-1', 'queue-1', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); - $provider->log('connection-2', 'queue-1', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); - $provider->log('connection-2', 'queue-1', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); + $provider->log('connection-1', 'queue-99', json_encode(['uuid' => (string) Generator::uuid()]), new RuntimeException()); + $provider->log('connection-1', 'queue-99', json_encode(['uuid' => (string) Generator::uuid()]), new RuntimeException()); + $provider->log('connection-2', 'queue-99', json_encode(['uuid' => (string) Generator::uuid()]), new RuntimeException()); + $provider->log('connection-1', 'queue-1', json_encode(['uuid' => (string) Generator::uuid()]), new RuntimeException()); + $provider->log('connection-2', 'queue-1', json_encode(['uuid' => (string) Generator::uuid()]), new RuntimeException()); + $provider->log('connection-2', 'queue-1', json_encode(['uuid' => (string) Generator::uuid()]), new RuntimeException()); $this->assertSame(2, $provider->count('connection-1', 'queue-99')); $this->assertSame(1, $provider->count('connection-2', 'queue-99')); $this->assertSame(1, $provider->count('connection-1', 'queue-1')); diff --git a/tests/Queue/DatabaseUuidFailedJobProviderTest.php b/tests/Queue/DatabaseUuidFailedJobProviderTest.php index d99284a89986..362d9ba9a787 100644 --- a/tests/Queue/DatabaseUuidFailedJobProviderTest.php +++ b/tests/Queue/DatabaseUuidFailedJobProviderTest.php @@ -5,6 +5,7 @@ use Illuminate\Database\Capsule\Manager as DB; use Illuminate\Database\Schema\Blueprint; use Illuminate\Queue\Failed\DatabaseUuidFailedJobProvider; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use PHPUnit\Framework\TestCase; use RuntimeException; @@ -30,11 +31,11 @@ public function testJobsCanBeCounted() $this->assertSame(0, $provider->count()); - $provider->log('connection-1', 'queue-1', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); + $provider->log('connection-1', 'queue-1', json_encode(['uuid' => (string) Generator::uuid()]), new RuntimeException()); $this->assertSame(1, $provider->count()); - $provider->log('connection-1', 'queue-1', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); - $provider->log('connection-2', 'queue-2', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); + $provider->log('connection-1', 'queue-1', json_encode(['uuid' => (string) Generator::uuid()]), new RuntimeException()); + $provider->log('connection-2', 'queue-2', json_encode(['uuid' => (string) Generator::uuid()]), new RuntimeException()); $this->assertSame(3, $provider->count()); } @@ -55,12 +56,12 @@ public function testJobsCanBeCountedByConnection() }); $provider = new DatabaseUuidFailedJobProvider($db->getDatabaseManager(), 'default', 'failed_jobs'); - $provider->log('connection-1', 'default', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); - $provider->log('connection-2', 'default', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); + $provider->log('connection-1', 'default', json_encode(['uuid' => (string) Generator::uuid()]), new RuntimeException()); + $provider->log('connection-2', 'default', json_encode(['uuid' => (string) Generator::uuid()]), new RuntimeException()); $this->assertSame(1, $provider->count('connection-1')); $this->assertSame(1, $provider->count('connection-2')); - $provider->log('connection-1', 'default', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); + $provider->log('connection-1', 'default', json_encode(['uuid' => (string) Generator::uuid()]), new RuntimeException()); $this->assertSame(2, $provider->count('connection-1')); $this->assertSame(1, $provider->count('connection-2')); } @@ -82,12 +83,12 @@ public function testJobsCanBeCountedByQueue() }); $provider = new DatabaseUuidFailedJobProvider($db->getDatabaseManager(), 'default', 'failed_jobs'); - $provider->log('database', 'queue-1', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); - $provider->log('database', 'queue-2', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); + $provider->log('database', 'queue-1', json_encode(['uuid' => (string) Generator::uuid()]), new RuntimeException()); + $provider->log('database', 'queue-2', json_encode(['uuid' => (string) Generator::uuid()]), new RuntimeException()); $this->assertSame(1, $provider->count(queue: 'queue-1')); $this->assertSame(1, $provider->count(queue: 'queue-2')); - $provider->log('database', 'queue-1', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); + $provider->log('database', 'queue-1', json_encode(['uuid' => (string) Generator::uuid()]), new RuntimeException()); $this->assertSame(2, $provider->count(queue: 'queue-1')); $this->assertSame(1, $provider->count(queue: 'queue-2')); } @@ -109,12 +110,12 @@ public function testJobsCanBeCountedByQueueAndConnection() }); $provider = new DatabaseUuidFailedJobProvider($db->getDatabaseManager(), 'default', 'failed_jobs'); - $provider->log('connection-1', 'queue-99', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); - $provider->log('connection-1', 'queue-99', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); - $provider->log('connection-2', 'queue-99', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); - $provider->log('connection-1', 'queue-1', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); - $provider->log('connection-2', 'queue-1', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); - $provider->log('connection-2', 'queue-1', json_encode(['uuid' => (string) Str::uuid()]), new RuntimeException()); + $provider->log('connection-1', 'queue-99', json_encode(['uuid' => (string) Generator::uuid()]), new RuntimeException()); + $provider->log('connection-1', 'queue-99', json_encode(['uuid' => (string) Generator::uuid()]), new RuntimeException()); + $provider->log('connection-2', 'queue-99', json_encode(['uuid' => (string) Generator::uuid()]), new RuntimeException()); + $provider->log('connection-1', 'queue-1', json_encode(['uuid' => (string) Generator::uuid()]), new RuntimeException()); + $provider->log('connection-2', 'queue-1', json_encode(['uuid' => (string) Generator::uuid()]), new RuntimeException()); + $provider->log('connection-2', 'queue-1', json_encode(['uuid' => (string) Generator::uuid()]), new RuntimeException()); $this->assertSame(2, $provider->count('connection-1', 'queue-99')); $this->assertSame(1, $provider->count('connection-2', 'queue-99')); $this->assertSame(1, $provider->count('connection-1', 'queue-1')); diff --git a/tests/Queue/DynamoDbFailedJobProviderTest.php b/tests/Queue/DynamoDbFailedJobProviderTest.php index dcd0cfe5f9d1..665cdbf554b0 100644 --- a/tests/Queue/DynamoDbFailedJobProviderTest.php +++ b/tests/Queue/DynamoDbFailedJobProviderTest.php @@ -8,6 +8,7 @@ use Exception; use Illuminate\Queue\Failed\DynamoDbFailedJobProvider; use Illuminate\Support\Carbon; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use Mockery as m; use PHPUnit\Framework\TestCase; @@ -21,7 +22,7 @@ protected function tearDown(): void public function testCanProperlyLogFailedJob() { - $uuid = Str::orderedUuid(); + $uuid = Generator::orderedUuid(); Str::createUuidsUsing(function () use ($uuid) { return $uuid; @@ -51,7 +52,7 @@ public function testCanProperlyLogFailedJob() $provider->log('connection', 'queue', json_encode(['uuid' => (string) $uuid]), $exception); - Str::createUuidsNormally(); + Generator::createUuidsNormally(); } public function testCanRetrieveAllFailedJobs() diff --git a/tests/Queue/FileFailedJobProviderTest.php b/tests/Queue/FileFailedJobProviderTest.php index 3ecbfec8e4d5..19b36895e5eb 100644 --- a/tests/Queue/FileFailedJobProviderTest.php +++ b/tests/Queue/FileFailedJobProviderTest.php @@ -4,6 +4,7 @@ use Exception; use Illuminate\Queue\Failed\FileFailedJobProvider; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use PHPUnit\Framework\TestCase; @@ -86,7 +87,7 @@ public function testCanFindFailedJobs() public function testNullIsReturnedIfJobNotFound() { - $uuid = Str::uuid(); + $uuid = Generator::uuid(); $failedJob = $this->provider->find($uuid); @@ -192,7 +193,7 @@ public function testJobsCanBeCountedByQueueAndConnection() public function logFailedJob($connection = 'connection', $queue = 'queue') { - $uuid = Str::uuid(); + $uuid = Generator::uuid(); $exception = new Exception("Something went wrong at job [{$uuid}]."); diff --git a/tests/Queue/QueueBeanstalkdQueueTest.php b/tests/Queue/QueueBeanstalkdQueueTest.php index ba34a7069305..66d263292d82 100755 --- a/tests/Queue/QueueBeanstalkdQueueTest.php +++ b/tests/Queue/QueueBeanstalkdQueueTest.php @@ -5,6 +5,7 @@ use Illuminate\Container\Container; use Illuminate\Queue\BeanstalkdQueue; use Illuminate\Queue\Jobs\BeanstalkdJob; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use Mockery as m; use Pheanstalk\Contract\JobIdInterface; @@ -36,7 +37,7 @@ protected function tearDown(): void public function testPushProperlyPushesJobOntoBeanstalkd() { - $uuid = Str::uuid(); + $uuid = Generator::uuid(); Str::createUuidsUsing(function () use ($uuid) { return $uuid; @@ -53,14 +54,14 @@ public function testPushProperlyPushesJobOntoBeanstalkd() $this->container->shouldHaveReceived('bound')->with('events')->times(4); - Str::createUuidsNormally(); + Generator::createUuidsNormally(); } public function testDelayedPushProperlyPushesJobOntoBeanstalkd() { - $uuid = Str::uuid(); + $uuid = Generator::uuid(); - Str::createUuidsUsing(function () use ($uuid) { + Generator::createUuidsUsing(function () use ($uuid) { return $uuid; }); @@ -75,7 +76,7 @@ public function testDelayedPushProperlyPushesJobOntoBeanstalkd() $this->container->shouldHaveReceived('bound')->with('events')->times(4); - Str::createUuidsNormally(); + Generator::createUuidsNormally(); } public function testPopProperlyPopsJobOffOfBeanstalkd() diff --git a/tests/Queue/QueueDatabaseQueueIntegrationTest.php b/tests/Queue/QueueDatabaseQueueIntegrationTest.php index 4c4f7c91c5c1..c61e9b76ff6d 100644 --- a/tests/Queue/QueueDatabaseQueueIntegrationTest.php +++ b/tests/Queue/QueueDatabaseQueueIntegrationTest.php @@ -11,6 +11,7 @@ use Illuminate\Queue\Events\JobQueued; use Illuminate\Queue\Events\JobQueueing; use Illuminate\Support\Carbon; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use PHPUnit\Framework\TestCase; @@ -252,7 +253,7 @@ public function testJobPayloadIsAvailableOnEvents() { $jobQueueingEvent = null; $jobQueuedEvent = null; - Str::createUuidsUsingSequence([ + Generator::createUuidsUsingSequence([ 'expected-job-uuid', ]); $this->container['events']->listen(function (JobQueueing $e) use (&$jobQueueingEvent) { diff --git a/tests/Queue/QueueDatabaseQueueUnitTest.php b/tests/Queue/QueueDatabaseQueueUnitTest.php index 3714b99a80b5..207f22b24049 100644 --- a/tests/Queue/QueueDatabaseQueueUnitTest.php +++ b/tests/Queue/QueueDatabaseQueueUnitTest.php @@ -6,6 +6,7 @@ use Illuminate\Database\Connection; use Illuminate\Queue\DatabaseQueue; use Illuminate\Queue\Queue; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; @@ -47,12 +48,12 @@ public function testPushProperlyPushesJobOntoDatabase($uuid, $job, $displayNameS $container->shouldHaveReceived('bound')->with('events')->twice(); - Str::createUuidsNormally(); + Generator::createUuidsNormally(); } public static function pushJobsDataProvider() { - $uuid = Str::uuid()->toString(); + $uuid = Generator::uuid()->toString(); return [ [$uuid, new MyTestJob, 'MyTestJob', 'CallQueuedHandler'], @@ -63,7 +64,7 @@ public static function pushJobsDataProvider() public function testDelayedPushProperlyPushesJobOntoDatabase() { - $uuid = Str::uuid(); + $uuid = Generator::uuid(); Str::createUuidsUsing(function () use ($uuid) { return $uuid; @@ -88,7 +89,7 @@ public function testDelayedPushProperlyPushesJobOntoDatabase() $container->shouldHaveReceived('bound')->with('events')->twice(); - Str::createUuidsNormally(); + Generator::createUuidsNormally(); } public function testFailureToCreatePayloadFromObject() @@ -124,7 +125,7 @@ public function testFailureToCreatePayloadFromArray() public function testBulkBatchPushesOntoDatabase() { - $uuid = Str::uuid(); + $uuid = Generator::uuid(); Str::createUuidsUsing(function () use ($uuid) { return $uuid; @@ -155,7 +156,7 @@ public function testBulkBatchPushesOntoDatabase() $queue->bulk(['foo', 'bar'], ['data'], 'queue'); - Str::createUuidsNormally(); + Generator::createUuidsNormally(); } public function testBuildDatabaseRecordWithPayloadAtTheEnd() diff --git a/tests/Queue/QueueRedisQueueTest.php b/tests/Queue/QueueRedisQueueTest.php index 007f743653d8..f4b8607d26ba 100644 --- a/tests/Queue/QueueRedisQueueTest.php +++ b/tests/Queue/QueueRedisQueueTest.php @@ -8,6 +8,7 @@ use Illuminate\Queue\Queue; use Illuminate\Queue\RedisQueue; use Illuminate\Support\Carbon; +use Illuminate\Support\Generator; use Illuminate\Support\Str; use Mockery as m; use PHPUnit\Framework\TestCase; @@ -21,9 +22,9 @@ protected function tearDown(): void public function testPushProperlyPushesJobOntoRedis() { - $uuid = Str::uuid(); + $uuid = Generator::uuid(); - Str::createUuidsUsing(function () use ($uuid) { + Generator::createUuidsUsing(function () use ($uuid) { return $uuid; }); @@ -37,12 +38,12 @@ public function testPushProperlyPushesJobOntoRedis() $this->assertSame('foo', $id); $container->shouldHaveReceived('bound')->with('events')->twice(); - Str::createUuidsNormally(); + Generator::createUuidsNormally(); } public function testPushProperlyPushesJobOntoRedisWithCustomPayloadHook() { - $uuid = Str::uuid(); + $uuid = Generator::uuid(); Str::createUuidsUsing(function () use ($uuid) { return $uuid; @@ -64,12 +65,12 @@ public function testPushProperlyPushesJobOntoRedisWithCustomPayloadHook() Queue::createPayloadUsing(null); - Str::createUuidsNormally(); + Generator::createUuidsNormally(); } public function testPushProperlyPushesJobOntoRedisWithTwoCustomPayloadHook() { - $uuid = Str::uuid(); + $uuid = Generator::uuid(); Str::createUuidsUsing(function () use ($uuid) { return $uuid; @@ -95,12 +96,12 @@ public function testPushProperlyPushesJobOntoRedisWithTwoCustomPayloadHook() Queue::createPayloadUsing(null); - Str::createUuidsNormally(); + Generator::createUuidsNormally(); } public function testDelayedPushProperlyPushesJobOntoRedis() { - $uuid = Str::uuid(); + $uuid = Generator::uuid(); Str::createUuidsUsing(function () use ($uuid) { return $uuid; @@ -122,12 +123,12 @@ public function testDelayedPushProperlyPushesJobOntoRedis() $this->assertSame('foo', $id); $container->shouldHaveReceived('bound')->with('events')->twice(); - Str::createUuidsNormally(); + Generator::createUuidsNormally(); } public function testDelayedPushWithDateTimeProperlyPushesJobOntoRedis() { - $uuid = Str::uuid(); + $uuid = Generator::uuid(); Str::createUuidsUsing(function () use ($uuid) { return $uuid; @@ -149,6 +150,6 @@ public function testDelayedPushWithDateTimeProperlyPushesJobOntoRedis() $queue->later($date, 'foo', ['data']); $container->shouldHaveReceived('bound')->with('events')->twice(); - Str::createUuidsNormally(); + Generator::createUuidsNormally(); } } From be272c7d7e9f3108b1c5008904ea92fd59bce060 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20H=C3=A4drich?= Date: Mon, 30 Sep 2024 18:06:08 +0200 Subject: [PATCH 08/14] fix: :bug: Change call on static to Casing class uin Str class --- src/Illuminate/Support/Str.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Illuminate/Support/Str.php b/src/Illuminate/Support/Str.php index 968b526a6994..87ddb5b6d17e 100644 --- a/src/Illuminate/Support/Str.php +++ b/src/Illuminate/Support/Str.php @@ -787,7 +787,7 @@ public static function slug($title, $separator = '-', $language = 'en', $diction $title = str_replace(array_keys($dictionary), array_values($dictionary), $title); // Remove all characters that are not the separator, letters, numbers, or whitespace - $title = preg_replace('![^'.preg_quote($separator).'\pL\pN\s]+!u', '', static::lower($title)); + $title = preg_replace('![^'.preg_quote($separator).'\pL\pN\s]+!u', '', Casing::lower($title)); // Replace all separator characters and whitespace by a single separator $title = preg_replace('!['.preg_quote($separator).'\s]+!u', $separator, $title); From 6d98c05ec6466bb22933d62ab55c814cdb0ad135 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20H=C3=A4drich?= Date: Mon, 30 Sep 2024 18:26:52 +0200 Subject: [PATCH 09/14] style: :art: Address styleCI spacing and indent issue --- src/Illuminate/Support/Casing.php | 1 - src/Illuminate/Support/Str.php | 1 + tests/Support/SupportGeneratorTest.php | 3 +-- tests/Support/SupportPatternMatcherTest.php | 2 +- tests/Support/SupportReplacerTest.php | 2 +- tests/Support/SupportSanitizerTest.php | 2 +- 6 files changed, 5 insertions(+), 6 deletions(-) diff --git a/src/Illuminate/Support/Casing.php b/src/Illuminate/Support/Casing.php index 3abca6e4960a..4c4c6060ad20 100644 --- a/src/Illuminate/Support/Casing.php +++ b/src/Illuminate/Support/Casing.php @@ -53,7 +53,6 @@ public static function lower($value) return mb_strtolower($value, 'UTF-8'); } - /** * Convert a value to camel case. * diff --git a/src/Illuminate/Support/Str.php b/src/Illuminate/Support/Str.php index 87ddb5b6d17e..b30d78399af9 100644 --- a/src/Illuminate/Support/Str.php +++ b/src/Illuminate/Support/Str.php @@ -464,6 +464,7 @@ public static function limit($value, $limit = 100, $end = '...', $preserveWords return preg_replace("/(.*)\s.*/", '$1', $trimmed).$end; } + /** * Limit the number of words in a string. * diff --git a/tests/Support/SupportGeneratorTest.php b/tests/Support/SupportGeneratorTest.php index b9688fac243c..d18474bda0aa 100644 --- a/tests/Support/SupportGeneratorTest.php +++ b/tests/Support/SupportGeneratorTest.php @@ -10,7 +10,6 @@ class SupportGeneratorTest extends TestCase { - public function testRandom() { $this->assertEquals(16, strlen(Generator::random())); @@ -306,4 +305,4 @@ public function testPasswordCreation() Str::of(Generator::password())->contains(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']) ); } -} \ No newline at end of file +} diff --git a/tests/Support/SupportPatternMatcherTest.php b/tests/Support/SupportPatternMatcherTest.php index b5137d524c8a..07de3a14fa55 100644 --- a/tests/Support/SupportPatternMatcherTest.php +++ b/tests/Support/SupportPatternMatcherTest.php @@ -177,4 +177,4 @@ public function testIsMatch() $this->assertTrue(PatternMatcher::isMatch(['/laravel/i', '/laravel!(.*)/'], 'Hello, Laravel!')); $this->assertTrue(PatternMatcher::isMatch(['/^[a-zA-Z,!]+$/', '/^(.*(.*(.*)))/'], 'Hello, Laravel!')); } -} \ No newline at end of file +} diff --git a/tests/Support/SupportReplacerTest.php b/tests/Support/SupportReplacerTest.php index a4f6cacc0dcf..c0fc2378b8ef 100644 --- a/tests/Support/SupportReplacerTest.php +++ b/tests/Support/SupportReplacerTest.php @@ -102,4 +102,4 @@ public function testSubstrReplace() $this->assertSame('The Laravel Framework', Replacer::substrReplace('The Framework', 'Laravel ', 4, 0)); $this->assertSame('Laravel – The PHP Framework for Web Artisans', Replacer::substrReplace('Laravel Framework', '– The PHP Framework for Web Artisans', 8)); } -} \ No newline at end of file +} diff --git a/tests/Support/SupportSanitizerTest.php b/tests/Support/SupportSanitizerTest.php index 0c1c1853a307..bc7ebb0e475f 100644 --- a/tests/Support/SupportSanitizerTest.php +++ b/tests/Support/SupportSanitizerTest.php @@ -146,4 +146,4 @@ public function testSquish() $this->assertSame('laravel php framework', Sanitizer::squish('laravelㅤㅤㅤphpㅤframework')); $this->assertSame('laravel php framework', Sanitizer::squish('laravelᅠᅠᅠᅠᅠᅠᅠᅠᅠᅠphpᅠᅠframework')); } -} \ No newline at end of file +} From 55da1f836901fe4301a7ca3e2afa1b335a7ad9e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20H=C3=A4drich?= Date: Mon, 30 Sep 2024 18:27:18 +0200 Subject: [PATCH 10/14] refactor: :recycle: StyleCI: Remove unused imports --- src/Illuminate/Auth/Passwords/DatabaseTokenRepository.php | 1 - src/Illuminate/Auth/SessionGuard.php | 1 - src/Illuminate/Bus/Batchable.php | 1 - src/Illuminate/Bus/DynamoBatchRepository.php | 1 - src/Illuminate/Cache/DynamoDbStore.php | 1 - src/Illuminate/Cache/Lock.php | 1 - src/Illuminate/Cache/RedisStore.php | 1 - .../Database/Console/Migrations/MigrateMakeCommand.php | 1 - src/Illuminate/Database/Console/Seeds/SeederMakeCommand.php | 1 - src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php | 1 - src/Illuminate/Database/Eloquent/Concerns/HasVersion4Uuids.php | 1 - src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php | 1 - .../Database/Eloquent/Relations/Concerns/AsPivot.php | 1 - src/Illuminate/Database/Migrations/MigrationCreator.php | 1 - src/Illuminate/Database/Migrations/Migrator.php | 1 - src/Illuminate/Database/Query/Builder.php | 1 - src/Illuminate/Database/Query/Grammars/MySqlGrammar.php | 1 - src/Illuminate/Database/QueryException.php | 1 - src/Illuminate/Foundation/Auth/Access/AuthorizesRequests.php | 1 - src/Illuminate/Foundation/Console/ComponentMakeCommand.php | 1 - src/Illuminate/Foundation/Console/DownCommand.php | 1 - src/Illuminate/Foundation/Console/MailMakeCommand.php | 1 - src/Illuminate/Foundation/Console/ModelMakeCommand.php | 1 - src/Illuminate/Foundation/Console/NotificationMakeCommand.php | 1 - src/Illuminate/Foundation/Console/PolicyMakeCommand.php | 1 - src/Illuminate/Foundation/Console/TestMakeCommand.php | 1 - src/Illuminate/Foundation/Events/DiscoverEvents.php | 1 - src/Illuminate/Foundation/Http/Middleware/TrimStrings.php | 1 - src/Illuminate/Http/FileHelpers.php | 1 - src/Illuminate/Http/Request.php | 1 - src/Illuminate/Http/Resources/CollectsResources.php | 1 - src/Illuminate/Log/LogManager.php | 1 - src/Illuminate/Mail/MailManager.php | 1 - src/Illuminate/Mail/Message.php | 1 - src/Illuminate/Notifications/NotificationSender.php | 1 - src/Illuminate/Notifications/RoutesNotifications.php | 1 - src/Illuminate/Process/PendingProcess.php | 1 - src/Illuminate/Queue/Console/ClearCommand.php | 1 - src/Illuminate/Queue/Jobs/FakeJob.php | 1 - src/Illuminate/Queue/Queue.php | 1 - src/Illuminate/Queue/RedisQueue.php | 1 - src/Illuminate/Redis/Limiters/ConcurrencyLimiter.php | 1 - src/Illuminate/Routing/AbstractRouteCollection.php | 1 - src/Illuminate/Routing/ImplicitRouteBinding.php | 1 - src/Illuminate/Routing/ResourceRegistrar.php | 1 - src/Illuminate/Support/Defer/DeferredCallback.php | 1 - src/Illuminate/Support/Testing/Fakes/BatchRepositoryFake.php | 1 - src/Illuminate/Support/Testing/Fakes/NotificationFake.php | 1 - src/Illuminate/Testing/ParallelTesting.php | 1 - src/Illuminate/Validation/Factory.php | 1 - .../View/Compilers/Concerns/CompilesConditionals.php | 1 - src/Illuminate/View/Compilers/Concerns/CompilesStacks.php | 1 - src/Illuminate/View/Concerns/ManagesLayouts.php | 1 - src/Illuminate/View/DynamicComponent.php | 1 - src/Illuminate/View/View.php | 1 - tests/Integration/Auth/AuthenticationTest.php | 1 - tests/Integration/Auth/ForgotPasswordTest.php | 1 - .../Auth/ForgotPasswordWithoutDefaultRoutesTest.php | 1 - .../Auth/Middleware/RedirectIfAuthenticatedTest.php | 1 - tests/Integration/Console/CommandEventsTest.php | 1 - tests/Integration/Cookie/CookieTest.php | 1 - .../Database/DatabaseEloquentModelAttributeCastingTest.php | 1 - tests/Integration/Database/EloquentBelongsToManyTest.php | 1 - tests/Integration/Database/EloquentBelongsToTest.php | 1 - tests/Integration/Database/EloquentHasManyTest.php | 1 - tests/Integration/Database/EloquentHasManyThroughTest.php | 1 - tests/Integration/Database/EloquentModelTest.php | 1 - tests/Integration/Database/EloquentMorphManyTest.php | 1 - .../Database/EloquentTouchParentWithGlobalScopeTest.php | 1 - tests/Integration/Database/EloquentUpdateTest.php | 1 - tests/Integration/Database/MySql/JoinLateralTest.php | 1 - tests/Integration/Database/Postgres/JoinLateralTest.php | 1 - tests/Integration/Database/SqlServer/JoinLateralTest.php | 1 - .../Database/Sqlite/EloquentModelConnectionsTest.php | 1 - .../Support/Providers/RouteServiceProviderHealthTest.php | 1 - .../Integration/Notifications/SendingMailNotificationsTest.php | 1 - tests/Integration/Queue/DynamoBatchTest.php | 1 - tests/Integration/Queue/JobEncryptionTest.php | 1 - tests/Integration/Queue/RateLimitedWithRedisTest.php | 1 - tests/Integration/Queue/ThrottlesExceptionsWithRedisTest.php | 1 - tests/Integration/Session/CookieSessionHandlerTest.php | 1 - tests/Integration/Session/SessionPersistenceTest.php | 1 - tests/Integration/Validation/ValidatorTest.php | 1 - tests/Queue/DatabaseFailedJobProviderTest.php | 1 - tests/Queue/DatabaseUuidFailedJobProviderTest.php | 1 - tests/Queue/FileFailedJobProviderTest.php | 1 - tests/Queue/QueueDatabaseQueueIntegrationTest.php | 1 - tests/Routing/RoutingRouteTest.php | 1 - tests/Session/SessionStoreTest.php | 1 - tests/Support/SupportStrTest.php | 3 --- 90 files changed, 92 deletions(-) diff --git a/src/Illuminate/Auth/Passwords/DatabaseTokenRepository.php b/src/Illuminate/Auth/Passwords/DatabaseTokenRepository.php index 7844592806a3..82b607d52052 100755 --- a/src/Illuminate/Auth/Passwords/DatabaseTokenRepository.php +++ b/src/Illuminate/Auth/Passwords/DatabaseTokenRepository.php @@ -7,7 +7,6 @@ use Illuminate\Database\ConnectionInterface; use Illuminate\Support\Carbon; use Illuminate\Support\Generator; -use Illuminate\Support\Str; class DatabaseTokenRepository implements TokenRepositoryInterface { diff --git a/src/Illuminate/Auth/SessionGuard.php b/src/Illuminate/Auth/SessionGuard.php index 47956a04dc46..139c98cdae93 100644 --- a/src/Illuminate/Auth/SessionGuard.php +++ b/src/Illuminate/Auth/SessionGuard.php @@ -20,7 +20,6 @@ use Illuminate\Support\Arr; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use Illuminate\Support\Timebox; use Illuminate\Support\Traits\Macroable; use InvalidArgumentException; diff --git a/src/Illuminate/Bus/Batchable.php b/src/Illuminate/Bus/Batchable.php index c817ee170416..fb49367f0f93 100644 --- a/src/Illuminate/Bus/Batchable.php +++ b/src/Illuminate/Bus/Batchable.php @@ -5,7 +5,6 @@ use Carbon\CarbonImmutable; use Generator; use Illuminate\Container\Container; -use Illuminate\Support\Str; use Illuminate\Support\Testing\Fakes\BatchFake; trait Batchable diff --git a/src/Illuminate/Bus/DynamoBatchRepository.php b/src/Illuminate/Bus/DynamoBatchRepository.php index 1215196e1d11..ab28bd1d383e 100644 --- a/src/Illuminate/Bus/DynamoBatchRepository.php +++ b/src/Illuminate/Bus/DynamoBatchRepository.php @@ -7,7 +7,6 @@ use Carbon\CarbonImmutable; use Closure; use Illuminate\Support\Generator; -use Illuminate\Support\Str; class DynamoBatchRepository implements BatchRepository { diff --git a/src/Illuminate/Cache/DynamoDbStore.php b/src/Illuminate/Cache/DynamoDbStore.php index 4371c3cef4c4..344cec9a159b 100644 --- a/src/Illuminate/Cache/DynamoDbStore.php +++ b/src/Illuminate/Cache/DynamoDbStore.php @@ -9,7 +9,6 @@ use Illuminate\Support\Carbon; use Illuminate\Support\InteractsWithTime; use Illuminate\Support\Replacer; -use Illuminate\Support\Str; use RuntimeException; class DynamoDbStore implements LockProvider, Store diff --git a/src/Illuminate/Cache/Lock.php b/src/Illuminate/Cache/Lock.php index af999c5c22b2..807839c0d777 100644 --- a/src/Illuminate/Cache/Lock.php +++ b/src/Illuminate/Cache/Lock.php @@ -7,7 +7,6 @@ use Illuminate\Support\Generator; use Illuminate\Support\InteractsWithTime; use Illuminate\Support\Sleep; -use Illuminate\Support\Str; abstract class Lock implements LockContract { diff --git a/src/Illuminate/Cache/RedisStore.php b/src/Illuminate/Cache/RedisStore.php index 7fb9fe1e3b63..f27ebc1223d0 100755 --- a/src/Illuminate/Cache/RedisStore.php +++ b/src/Illuminate/Cache/RedisStore.php @@ -8,7 +8,6 @@ use Illuminate\Redis\Connections\PredisConnection; use Illuminate\Support\LazyCollection; use Illuminate\Support\PatternMatcher; -use Illuminate\Support\Str; class RedisStore extends TaggableStore implements LockProvider { diff --git a/src/Illuminate/Database/Console/Migrations/MigrateMakeCommand.php b/src/Illuminate/Database/Console/Migrations/MigrateMakeCommand.php index 627c3386ec48..d0d0a0defbcb 100644 --- a/src/Illuminate/Database/Console/Migrations/MigrateMakeCommand.php +++ b/src/Illuminate/Database/Console/Migrations/MigrateMakeCommand.php @@ -6,7 +6,6 @@ use Illuminate\Database\Migrations\MigrationCreator; use Illuminate\Support\Casing; use Illuminate\Support\Composer; -use Illuminate\Support\Str; use Symfony\Component\Console\Attribute\AsCommand; #[AsCommand(name: 'make:migration')] diff --git a/src/Illuminate/Database/Console/Seeds/SeederMakeCommand.php b/src/Illuminate/Database/Console/Seeds/SeederMakeCommand.php index 804323f28768..19d74124bc9d 100644 --- a/src/Illuminate/Database/Console/Seeds/SeederMakeCommand.php +++ b/src/Illuminate/Database/Console/Seeds/SeederMakeCommand.php @@ -4,7 +4,6 @@ use Illuminate\Console\GeneratorCommand; use Illuminate\Support\Replacer; -use Illuminate\Support\Str; use Symfony\Component\Console\Attribute\AsCommand; #[AsCommand(name: 'make:seeder')] diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php index a1411fa1b16f..4a185ad18678 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php @@ -22,7 +22,6 @@ use Illuminate\Database\Eloquent\Relations\Relation; use Illuminate\Support\Arr; use Illuminate\Support\Casing; -use Illuminate\Support\Str; use Illuminate\Support\StrGrammar; trait HasRelationships diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasVersion4Uuids.php b/src/Illuminate/Database/Eloquent/Concerns/HasVersion4Uuids.php index 0f182ec9b6a9..b1cf107466a1 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasVersion4Uuids.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasVersion4Uuids.php @@ -3,7 +3,6 @@ namespace Illuminate\Database\Eloquent\Concerns; use Illuminate\Support\Generator; -use Illuminate\Support\Str; trait HasVersion4Uuids { diff --git a/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php b/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php index 14cd315bf91b..239c3d565e42 100755 --- a/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php +++ b/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php @@ -14,7 +14,6 @@ use Illuminate\Database\Query\Grammars\MySqlGrammar; use Illuminate\Database\UniqueConstraintViolationException; use Illuminate\Support\Casing; -use Illuminate\Support\Str; use Illuminate\Support\StrGrammar; use InvalidArgumentException; diff --git a/src/Illuminate/Database/Eloquent/Relations/Concerns/AsPivot.php b/src/Illuminate/Database/Eloquent/Relations/Concerns/AsPivot.php index 648b678d3ac0..2d940917652d 100644 --- a/src/Illuminate/Database/Eloquent/Relations/Concerns/AsPivot.php +++ b/src/Illuminate/Database/Eloquent/Relations/Concerns/AsPivot.php @@ -4,7 +4,6 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Casing; -use Illuminate\Support\Str; use Illuminate\Support\StrGrammar; trait AsPivot diff --git a/src/Illuminate/Database/Migrations/MigrationCreator.php b/src/Illuminate/Database/Migrations/MigrationCreator.php index 37fb43060da7..34017dbd6d4c 100755 --- a/src/Illuminate/Database/Migrations/MigrationCreator.php +++ b/src/Illuminate/Database/Migrations/MigrationCreator.php @@ -5,7 +5,6 @@ use Closure; use Illuminate\Filesystem\Filesystem; use Illuminate\Support\Casing; -use Illuminate\Support\Str; use InvalidArgumentException; class MigrationCreator diff --git a/src/Illuminate/Database/Migrations/Migrator.php b/src/Illuminate/Database/Migrations/Migrator.php index c80b37ef42e7..5a7a5b504dc3 100755 --- a/src/Illuminate/Database/Migrations/Migrator.php +++ b/src/Illuminate/Database/Migrations/Migrator.php @@ -17,7 +17,6 @@ use Illuminate\Support\Arr; use Illuminate\Support\Casing; use Illuminate\Support\Collection; -use Illuminate\Support\Str; use ReflectionClass; use Symfony\Component\Console\Output\OutputInterface; diff --git a/src/Illuminate/Database/Query/Builder.php b/src/Illuminate/Database/Query/Builder.php index 08095503df7b..93fe75d7063f 100755 --- a/src/Illuminate/Database/Query/Builder.php +++ b/src/Illuminate/Database/Query/Builder.php @@ -22,7 +22,6 @@ use Illuminate\Support\Casing; use Illuminate\Support\Collection; use Illuminate\Support\LazyCollection; -use Illuminate\Support\Str; use Illuminate\Support\Traits\ForwardsCalls; use Illuminate\Support\Traits\Macroable; use InvalidArgumentException; diff --git a/src/Illuminate/Database/Query/Grammars/MySqlGrammar.php b/src/Illuminate/Database/Query/Grammars/MySqlGrammar.php index 4384b6e1ba5f..b23819145f57 100755 --- a/src/Illuminate/Database/Query/Grammars/MySqlGrammar.php +++ b/src/Illuminate/Database/Query/Grammars/MySqlGrammar.php @@ -5,7 +5,6 @@ use Illuminate\Database\Query\Builder; use Illuminate\Database\Query\JoinLateralClause; use Illuminate\Support\Replacer; -use Illuminate\Support\Str; class MySqlGrammar extends Grammar { diff --git a/src/Illuminate/Database/QueryException.php b/src/Illuminate/Database/QueryException.php index 743d3122da10..0f68510ec1c7 100644 --- a/src/Illuminate/Database/QueryException.php +++ b/src/Illuminate/Database/QueryException.php @@ -3,7 +3,6 @@ namespace Illuminate\Database; use Illuminate\Support\Replacer; -use Illuminate\Support\Str; use PDOException; use Throwable; diff --git a/src/Illuminate/Foundation/Auth/Access/AuthorizesRequests.php b/src/Illuminate/Foundation/Auth/Access/AuthorizesRequests.php index f1b474774ab6..38b448a42d31 100644 --- a/src/Illuminate/Foundation/Auth/Access/AuthorizesRequests.php +++ b/src/Illuminate/Foundation/Auth/Access/AuthorizesRequests.php @@ -4,7 +4,6 @@ use Illuminate\Contracts\Auth\Access\Gate; use Illuminate\Support\Casing; -use Illuminate\Support\Str; trait AuthorizesRequests { diff --git a/src/Illuminate/Foundation/Console/ComponentMakeCommand.php b/src/Illuminate/Foundation/Console/ComponentMakeCommand.php index 5402aa827492..fa9d4a2908da 100644 --- a/src/Illuminate/Foundation/Console/ComponentMakeCommand.php +++ b/src/Illuminate/Foundation/Console/ComponentMakeCommand.php @@ -6,7 +6,6 @@ use Illuminate\Console\GeneratorCommand; use Illuminate\Foundation\Inspiring; use Illuminate\Support\Casing; -use Illuminate\Support\Str; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputOption; diff --git a/src/Illuminate/Foundation/Console/DownCommand.php b/src/Illuminate/Foundation/Console/DownCommand.php index b15bcc1d6c9c..d83415e67c63 100644 --- a/src/Illuminate/Foundation/Console/DownCommand.php +++ b/src/Illuminate/Foundation/Console/DownCommand.php @@ -8,7 +8,6 @@ use Illuminate\Foundation\Events\MaintenanceModeEnabled; use Illuminate\Foundation\Exceptions\RegisterErrorViewPaths; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use Symfony\Component\Console\Attribute\AsCommand; use Throwable; diff --git a/src/Illuminate/Foundation/Console/MailMakeCommand.php b/src/Illuminate/Foundation/Console/MailMakeCommand.php index efcc8381721d..37e5896bae94 100644 --- a/src/Illuminate/Foundation/Console/MailMakeCommand.php +++ b/src/Illuminate/Foundation/Console/MailMakeCommand.php @@ -6,7 +6,6 @@ use Illuminate\Console\GeneratorCommand; use Illuminate\Foundation\Inspiring; use Illuminate\Support\Casing; -use Illuminate\Support\Str; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; diff --git a/src/Illuminate/Foundation/Console/ModelMakeCommand.php b/src/Illuminate/Foundation/Console/ModelMakeCommand.php index 5ef1ccaea5a3..bb01b6b6e04f 100644 --- a/src/Illuminate/Foundation/Console/ModelMakeCommand.php +++ b/src/Illuminate/Foundation/Console/ModelMakeCommand.php @@ -5,7 +5,6 @@ use Illuminate\Console\Concerns\CreatesMatchingTest; use Illuminate\Console\GeneratorCommand; use Illuminate\Support\Casing; -use Illuminate\Support\Str; use Illuminate\Support\StrGrammar; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputInterface; diff --git a/src/Illuminate/Foundation/Console/NotificationMakeCommand.php b/src/Illuminate/Foundation/Console/NotificationMakeCommand.php index 7f93aee179c1..a9a7ede7824e 100644 --- a/src/Illuminate/Foundation/Console/NotificationMakeCommand.php +++ b/src/Illuminate/Foundation/Console/NotificationMakeCommand.php @@ -5,7 +5,6 @@ use Illuminate\Console\Concerns\CreatesMatchingTest; use Illuminate\Console\GeneratorCommand; use Illuminate\Support\Casing; -use Illuminate\Support\Str; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; diff --git a/src/Illuminate/Foundation/Console/PolicyMakeCommand.php b/src/Illuminate/Foundation/Console/PolicyMakeCommand.php index fb1b307458ee..0d072f4474c4 100644 --- a/src/Illuminate/Foundation/Console/PolicyMakeCommand.php +++ b/src/Illuminate/Foundation/Console/PolicyMakeCommand.php @@ -4,7 +4,6 @@ use Illuminate\Console\GeneratorCommand; use Illuminate\Support\Casing; -use Illuminate\Support\Str; use LogicException; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputInterface; diff --git a/src/Illuminate/Foundation/Console/TestMakeCommand.php b/src/Illuminate/Foundation/Console/TestMakeCommand.php index 6f5e8260ae8b..02893781641e 100644 --- a/src/Illuminate/Foundation/Console/TestMakeCommand.php +++ b/src/Illuminate/Foundation/Console/TestMakeCommand.php @@ -4,7 +4,6 @@ use Illuminate\Console\GeneratorCommand; use Illuminate\Support\Replacer; -use Illuminate\Support\Str; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; diff --git a/src/Illuminate/Foundation/Events/DiscoverEvents.php b/src/Illuminate/Foundation/Events/DiscoverEvents.php index fd6d7414e026..a0f34236dc4b 100644 --- a/src/Illuminate/Foundation/Events/DiscoverEvents.php +++ b/src/Illuminate/Foundation/Events/DiscoverEvents.php @@ -5,7 +5,6 @@ use Illuminate\Support\PatternMatcher; use Illuminate\Support\Reflector; use Illuminate\Support\Replacer; -use Illuminate\Support\Str; use ReflectionClass; use ReflectionException; use ReflectionMethod; diff --git a/src/Illuminate/Foundation/Http/Middleware/TrimStrings.php b/src/Illuminate/Foundation/Http/Middleware/TrimStrings.php index abe70921efc5..d3c2e6e0a14a 100644 --- a/src/Illuminate/Foundation/Http/Middleware/TrimStrings.php +++ b/src/Illuminate/Foundation/Http/Middleware/TrimStrings.php @@ -5,7 +5,6 @@ use Closure; use Illuminate\Support\Arr; use Illuminate\Support\Sanitizer; -use Illuminate\Support\Str; class TrimStrings extends TransformsRequest { diff --git a/src/Illuminate/Http/FileHelpers.php b/src/Illuminate/Http/FileHelpers.php index ede4b4a55c47..a5dfaac072de 100644 --- a/src/Illuminate/Http/FileHelpers.php +++ b/src/Illuminate/Http/FileHelpers.php @@ -3,7 +3,6 @@ namespace Illuminate\Http; use Illuminate\Support\Generator; -use Illuminate\Support\Str; trait FileHelpers { diff --git a/src/Illuminate/Http/Request.php b/src/Illuminate/Http/Request.php index 3aaa4fb4d877..78ac703ff830 100644 --- a/src/Illuminate/Http/Request.php +++ b/src/Illuminate/Http/Request.php @@ -8,7 +8,6 @@ use Illuminate\Session\SymfonySessionDecorator; use Illuminate\Support\Arr; use Illuminate\Support\PatternMatcher; -use Illuminate\Support\Str; use Illuminate\Support\Traits\Macroable; use RuntimeException; use Symfony\Component\HttpFoundation\Exception\SessionNotFoundException; diff --git a/src/Illuminate/Http/Resources/CollectsResources.php b/src/Illuminate/Http/Resources/CollectsResources.php index f53331c8edeb..cbcf2e3ed0d9 100644 --- a/src/Illuminate/Http/Resources/CollectsResources.php +++ b/src/Illuminate/Http/Resources/CollectsResources.php @@ -7,7 +7,6 @@ use Illuminate\Pagination\AbstractPaginator; use Illuminate\Support\Collection; use Illuminate\Support\Replacer; -use Illuminate\Support\Str; use LogicException; use ReflectionClass; use Traversable; diff --git a/src/Illuminate/Log/LogManager.php b/src/Illuminate/Log/LogManager.php index d4c386f6a33e..d16adc08000a 100644 --- a/src/Illuminate/Log/LogManager.php +++ b/src/Illuminate/Log/LogManager.php @@ -5,7 +5,6 @@ use Closure; use Illuminate\Log\Context\Repository as ContextRepository; use Illuminate\Support\Casing; -use Illuminate\Support\Str; use InvalidArgumentException; use Monolog\Formatter\LineFormatter; use Monolog\Handler\ErrorLogHandler; diff --git a/src/Illuminate/Mail/MailManager.php b/src/Illuminate/Mail/MailManager.php index d01469ad568a..2ecdc86e733d 100644 --- a/src/Illuminate/Mail/MailManager.php +++ b/src/Illuminate/Mail/MailManager.php @@ -15,7 +15,6 @@ use Illuminate\Support\Arr; use Illuminate\Support\Casing; use Illuminate\Support\ConfigurationUrlParser; -use Illuminate\Support\Str; use InvalidArgumentException; use Psr\Log\LoggerInterface; use Resend; diff --git a/src/Illuminate/Mail/Message.php b/src/Illuminate/Mail/Message.php index 11310f668e0b..c119e3bd5dfd 100755 --- a/src/Illuminate/Mail/Message.php +++ b/src/Illuminate/Mail/Message.php @@ -4,7 +4,6 @@ use Illuminate\Contracts\Mail\Attachable; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use Illuminate\Support\Traits\ForwardsCalls; use Symfony\Component\Mime\Address; use Symfony\Component\Mime\Email; diff --git a/src/Illuminate/Notifications/NotificationSender.php b/src/Illuminate/Notifications/NotificationSender.php index 3cb30f54a818..6b5c373bf56e 100644 --- a/src/Illuminate/Notifications/NotificationSender.php +++ b/src/Illuminate/Notifications/NotificationSender.php @@ -10,7 +10,6 @@ use Illuminate\Notifications\Events\NotificationSent; use Illuminate\Support\Collection; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use Illuminate\Support\Traits\Localizable; class NotificationSender diff --git a/src/Illuminate/Notifications/RoutesNotifications.php b/src/Illuminate/Notifications/RoutesNotifications.php index 665a4313d540..55b025b72488 100644 --- a/src/Illuminate/Notifications/RoutesNotifications.php +++ b/src/Illuminate/Notifications/RoutesNotifications.php @@ -4,7 +4,6 @@ use Illuminate\Contracts\Notifications\Dispatcher; use Illuminate\Support\Casing; -use Illuminate\Support\Str; trait RoutesNotifications { diff --git a/src/Illuminate/Process/PendingProcess.php b/src/Illuminate/Process/PendingProcess.php index 4a6f5cc30be5..96d57674750b 100644 --- a/src/Illuminate/Process/PendingProcess.php +++ b/src/Illuminate/Process/PendingProcess.php @@ -5,7 +5,6 @@ use Closure; use Illuminate\Process\Exceptions\ProcessTimedOutException; use Illuminate\Support\PatternMatcher; -use Illuminate\Support\Str; use Illuminate\Support\Traits\Conditionable; use LogicException; use RuntimeException; diff --git a/src/Illuminate/Queue/Console/ClearCommand.php b/src/Illuminate/Queue/Console/ClearCommand.php index 6f0c93f853c4..ae13dbda163c 100644 --- a/src/Illuminate/Queue/Console/ClearCommand.php +++ b/src/Illuminate/Queue/Console/ClearCommand.php @@ -5,7 +5,6 @@ use Illuminate\Console\Command; use Illuminate\Console\ConfirmableTrait; use Illuminate\Contracts\Queue\ClearableQueue; -use Illuminate\Support\Str; use Illuminate\Support\StrGrammar; use ReflectionClass; use Symfony\Component\Console\Attribute\AsCommand; diff --git a/src/Illuminate/Queue/Jobs/FakeJob.php b/src/Illuminate/Queue/Jobs/FakeJob.php index fdadeff0221b..8c627a9c4150 100644 --- a/src/Illuminate/Queue/Jobs/FakeJob.php +++ b/src/Illuminate/Queue/Jobs/FakeJob.php @@ -3,7 +3,6 @@ namespace Illuminate\Queue\Jobs; use Illuminate\Support\Generator; -use Illuminate\Support\Str; class FakeJob extends Job { diff --git a/src/Illuminate/Queue/Queue.php b/src/Illuminate/Queue/Queue.php index acd76f69268d..96512d5d66ab 100755 --- a/src/Illuminate/Queue/Queue.php +++ b/src/Illuminate/Queue/Queue.php @@ -13,7 +13,6 @@ use Illuminate\Support\Arr; use Illuminate\Support\Generator; use Illuminate\Support\InteractsWithTime; -use Illuminate\Support\Str; abstract class Queue { diff --git a/src/Illuminate/Queue/RedisQueue.php b/src/Illuminate/Queue/RedisQueue.php index 0f09ff8bb771..9b48946434f7 100644 --- a/src/Illuminate/Queue/RedisQueue.php +++ b/src/Illuminate/Queue/RedisQueue.php @@ -7,7 +7,6 @@ use Illuminate\Contracts\Redis\Factory as Redis; use Illuminate\Queue\Jobs\RedisJob; use Illuminate\Support\Generator; -use Illuminate\Support\Str; class RedisQueue extends Queue implements QueueContract, ClearableQueue { diff --git a/src/Illuminate/Redis/Limiters/ConcurrencyLimiter.php b/src/Illuminate/Redis/Limiters/ConcurrencyLimiter.php index fb2221ac200d..a3f49646f508 100644 --- a/src/Illuminate/Redis/Limiters/ConcurrencyLimiter.php +++ b/src/Illuminate/Redis/Limiters/ConcurrencyLimiter.php @@ -5,7 +5,6 @@ use Illuminate\Contracts\Redis\LimiterTimeoutException; use Illuminate\Support\Generator; use Illuminate\Support\Sleep; -use Illuminate\Support\Str; use Throwable; class ConcurrencyLimiter diff --git a/src/Illuminate/Routing/AbstractRouteCollection.php b/src/Illuminate/Routing/AbstractRouteCollection.php index 41207709daec..52900e44ad25 100644 --- a/src/Illuminate/Routing/AbstractRouteCollection.php +++ b/src/Illuminate/Routing/AbstractRouteCollection.php @@ -7,7 +7,6 @@ use Illuminate\Http\Request; use Illuminate\Http\Response; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use IteratorAggregate; use LogicException; use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException; diff --git a/src/Illuminate/Routing/ImplicitRouteBinding.php b/src/Illuminate/Routing/ImplicitRouteBinding.php index 13501a71f015..53fc0a328b64 100644 --- a/src/Illuminate/Routing/ImplicitRouteBinding.php +++ b/src/Illuminate/Routing/ImplicitRouteBinding.php @@ -8,7 +8,6 @@ use Illuminate\Routing\Exceptions\BackedEnumCaseNotFoundException; use Illuminate\Support\Casing; use Illuminate\Support\Reflector; -use Illuminate\Support\Str; class ImplicitRouteBinding { diff --git a/src/Illuminate/Routing/ResourceRegistrar.php b/src/Illuminate/Routing/ResourceRegistrar.php index fa2ea31d10fe..21aea1a24121 100644 --- a/src/Illuminate/Routing/ResourceRegistrar.php +++ b/src/Illuminate/Routing/ResourceRegistrar.php @@ -2,7 +2,6 @@ namespace Illuminate\Routing; -use Illuminate\Support\Str; use Illuminate\Support\StrGrammar; class ResourceRegistrar diff --git a/src/Illuminate/Support/Defer/DeferredCallback.php b/src/Illuminate/Support/Defer/DeferredCallback.php index b7032b3631af..94faa277611f 100644 --- a/src/Illuminate/Support/Defer/DeferredCallback.php +++ b/src/Illuminate/Support/Defer/DeferredCallback.php @@ -3,7 +3,6 @@ namespace Illuminate\Support\Defer; use Illuminate\Support\Generator; -use Illuminate\Support\Str; class DeferredCallback { diff --git a/src/Illuminate/Support/Testing/Fakes/BatchRepositoryFake.php b/src/Illuminate/Support/Testing/Fakes/BatchRepositoryFake.php index 44ebf84a0a98..0cb96c1443e9 100644 --- a/src/Illuminate/Support/Testing/Fakes/BatchRepositoryFake.php +++ b/src/Illuminate/Support/Testing/Fakes/BatchRepositoryFake.php @@ -8,7 +8,6 @@ use Illuminate\Bus\PendingBatch; use Illuminate\Bus\UpdatedBatchJobCounts; use Illuminate\Support\Generator; -use Illuminate\Support\Str; class BatchRepositoryFake implements BatchRepository { diff --git a/src/Illuminate/Support/Testing/Fakes/NotificationFake.php b/src/Illuminate/Support/Testing/Fakes/NotificationFake.php index ae6ea3b55487..3329b668d831 100644 --- a/src/Illuminate/Support/Testing/Fakes/NotificationFake.php +++ b/src/Illuminate/Support/Testing/Fakes/NotificationFake.php @@ -11,7 +11,6 @@ use Illuminate\Notifications\AnonymousNotifiable; use Illuminate\Support\Collection; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use Illuminate\Support\Traits\Macroable; use Illuminate\Support\Traits\ReflectsClosures; use PHPUnit\Framework\Assert as PHPUnit; diff --git a/src/Illuminate/Testing/ParallelTesting.php b/src/Illuminate/Testing/ParallelTesting.php index 145bb679d44f..321c8fd6db05 100644 --- a/src/Illuminate/Testing/ParallelTesting.php +++ b/src/Illuminate/Testing/ParallelTesting.php @@ -3,7 +3,6 @@ namespace Illuminate\Testing; use Illuminate\Contracts\Container\Container; -use Illuminate\Support\Str; class ParallelTesting { diff --git a/src/Illuminate/Validation/Factory.php b/src/Illuminate/Validation/Factory.php index a165b85303c5..2fbe633bc87c 100755 --- a/src/Illuminate/Validation/Factory.php +++ b/src/Illuminate/Validation/Factory.php @@ -7,7 +7,6 @@ use Illuminate\Contracts\Translation\Translator; use Illuminate\Contracts\Validation\Factory as FactoryContract; use Illuminate\Support\Casing; -use Illuminate\Support\Str; class Factory implements FactoryContract { diff --git a/src/Illuminate/View/Compilers/Concerns/CompilesConditionals.php b/src/Illuminate/View/Compilers/Concerns/CompilesConditionals.php index ab0de185175a..15ddb310aa6c 100644 --- a/src/Illuminate/View/Compilers/Concerns/CompilesConditionals.php +++ b/src/Illuminate/View/Compilers/Concerns/CompilesConditionals.php @@ -3,7 +3,6 @@ namespace Illuminate\View\Compilers\Concerns; use Illuminate\Support\Generator; -use Illuminate\Support\Str; trait CompilesConditionals { diff --git a/src/Illuminate/View/Compilers/Concerns/CompilesStacks.php b/src/Illuminate/View/Compilers/Concerns/CompilesStacks.php index 7b5d1893eced..28820cd6af15 100644 --- a/src/Illuminate/View/Compilers/Concerns/CompilesStacks.php +++ b/src/Illuminate/View/Compilers/Concerns/CompilesStacks.php @@ -3,7 +3,6 @@ namespace Illuminate\View\Compilers\Concerns; use Illuminate\Support\Generator; -use Illuminate\Support\Str; trait CompilesStacks { diff --git a/src/Illuminate/View/Concerns/ManagesLayouts.php b/src/Illuminate/View/Concerns/ManagesLayouts.php index 772171beeac1..4a7b0a858789 100644 --- a/src/Illuminate/View/Concerns/ManagesLayouts.php +++ b/src/Illuminate/View/Concerns/ManagesLayouts.php @@ -4,7 +4,6 @@ use Illuminate\Contracts\View\View; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use InvalidArgumentException; trait ManagesLayouts diff --git a/src/Illuminate/View/DynamicComponent.php b/src/Illuminate/View/DynamicComponent.php index a83be85efb68..087e0c182e77 100644 --- a/src/Illuminate/View/DynamicComponent.php +++ b/src/Illuminate/View/DynamicComponent.php @@ -4,7 +4,6 @@ use Illuminate\Container\Container; use Illuminate\Support\Casing; -use Illuminate\Support\Str; use Illuminate\View\Compilers\ComponentTagCompiler; class DynamicComponent extends Component diff --git a/src/Illuminate/View/View.php b/src/Illuminate/View/View.php index 94cc8a3ad4c5..d8afbb9c3f5e 100755 --- a/src/Illuminate/View/View.php +++ b/src/Illuminate/View/View.php @@ -12,7 +12,6 @@ use Illuminate\Contracts\View\View as ViewContract; use Illuminate\Support\Casing; use Illuminate\Support\MessageBag; -use Illuminate\Support\Str; use Illuminate\Support\Traits\Macroable; use Illuminate\Support\ViewErrorBag; use Stringable; diff --git a/tests/Integration/Auth/AuthenticationTest.php b/tests/Integration/Auth/AuthenticationTest.php index 858317426544..bdd361c02126 100644 --- a/tests/Integration/Auth/AuthenticationTest.php +++ b/tests/Integration/Auth/AuthenticationTest.php @@ -18,7 +18,6 @@ use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Schema; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use Illuminate\Support\Testing\Fakes\EventFake; use Illuminate\Tests\Integration\Auth\Fixtures\AuthenticationTestUser; use InvalidArgumentException; diff --git a/tests/Integration/Auth/ForgotPasswordTest.php b/tests/Integration/Auth/ForgotPasswordTest.php index ed0e91df0753..a03bc605fd91 100644 --- a/tests/Integration/Auth/ForgotPasswordTest.php +++ b/tests/Integration/Auth/ForgotPasswordTest.php @@ -10,7 +10,6 @@ use Illuminate\Support\Facades\Notification; use Illuminate\Support\Facades\Password; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use Illuminate\Tests\Integration\Auth\Fixtures\AuthenticationTestUser; use Orchestra\Testbench\Attributes\WithMigration; use Orchestra\Testbench\Factories\UserFactory; diff --git a/tests/Integration/Auth/ForgotPasswordWithoutDefaultRoutesTest.php b/tests/Integration/Auth/ForgotPasswordWithoutDefaultRoutesTest.php index 7172583420e0..605d8a313f7e 100644 --- a/tests/Integration/Auth/ForgotPasswordWithoutDefaultRoutesTest.php +++ b/tests/Integration/Auth/ForgotPasswordWithoutDefaultRoutesTest.php @@ -8,7 +8,6 @@ use Illuminate\Support\Facades\Notification; use Illuminate\Support\Facades\Password; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use Illuminate\Tests\Integration\Auth\Fixtures\AuthenticationTestUser; use Orchestra\Testbench\Attributes\WithMigration; use Orchestra\Testbench\Factories\UserFactory; diff --git a/tests/Integration/Auth/Middleware/RedirectIfAuthenticatedTest.php b/tests/Integration/Auth/Middleware/RedirectIfAuthenticatedTest.php index bd535ad3483c..7b5d437b7361 100644 --- a/tests/Integration/Auth/Middleware/RedirectIfAuthenticatedTest.php +++ b/tests/Integration/Auth/Middleware/RedirectIfAuthenticatedTest.php @@ -5,7 +5,6 @@ use Illuminate\Auth\Middleware\RedirectIfAuthenticated; use Illuminate\Contracts\Routing\Registrar; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use Illuminate\Tests\Integration\Auth\Fixtures\AuthenticationTestUser; use Orchestra\Testbench\Factories\UserFactory; use Orchestra\Testbench\TestCase; diff --git a/tests/Integration/Console/CommandEventsTest.php b/tests/Integration/Console/CommandEventsTest.php index 9e8fb047988e..a60e5e292893 100644 --- a/tests/Integration/Console/CommandEventsTest.php +++ b/tests/Integration/Console/CommandEventsTest.php @@ -10,7 +10,6 @@ use Illuminate\Foundation\Testing\WithConsoleEvents; use Illuminate\Support\Facades\Event; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use Orchestra\Testbench\Foundation\Application as Testbench; use Orchestra\Testbench\TestCase; use PHPUnit\Framework\Attributes\DataProvider; diff --git a/tests/Integration/Cookie/CookieTest.php b/tests/Integration/Cookie/CookieTest.php index 27856a2b6cfe..3ffd428f8e64 100644 --- a/tests/Integration/Cookie/CookieTest.php +++ b/tests/Integration/Cookie/CookieTest.php @@ -9,7 +9,6 @@ use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Session; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use Mockery as m; use Orchestra\Testbench\TestCase; diff --git a/tests/Integration/Database/DatabaseEloquentModelAttributeCastingTest.php b/tests/Integration/Database/DatabaseEloquentModelAttributeCastingTest.php index 82ac519c00b8..f62ad3cac29f 100644 --- a/tests/Integration/Database/DatabaseEloquentModelAttributeCastingTest.php +++ b/tests/Integration/Database/DatabaseEloquentModelAttributeCastingTest.php @@ -9,7 +9,6 @@ use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\Schema; use Illuminate\Support\Generator; -use Illuminate\Support\Str; class DatabaseEloquentModelAttributeCastingTest extends DatabaseTestCase { diff --git a/tests/Integration/Database/EloquentBelongsToManyTest.php b/tests/Integration/Database/EloquentBelongsToManyTest.php index 2b0d93b1d41a..c1225859267e 100644 --- a/tests/Integration/Database/EloquentBelongsToManyTest.php +++ b/tests/Integration/Database/EloquentBelongsToManyTest.php @@ -11,7 +11,6 @@ use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use Illuminate\Tests\Integration\Database\DatabaseTestCase; class EloquentBelongsToManyTest extends DatabaseTestCase diff --git a/tests/Integration/Database/EloquentBelongsToTest.php b/tests/Integration/Database/EloquentBelongsToTest.php index 964b1a6056e2..02ce221efe39 100644 --- a/tests/Integration/Database/EloquentBelongsToTest.php +++ b/tests/Integration/Database/EloquentBelongsToTest.php @@ -6,7 +6,6 @@ use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use Illuminate\Tests\Integration\Database\DatabaseTestCase; class EloquentBelongsToTest extends DatabaseTestCase diff --git a/tests/Integration/Database/EloquentHasManyTest.php b/tests/Integration/Database/EloquentHasManyTest.php index 2aee426bf393..ecebf23601d3 100644 --- a/tests/Integration/Database/EloquentHasManyTest.php +++ b/tests/Integration/Database/EloquentHasManyTest.php @@ -8,7 +8,6 @@ use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; use Illuminate\Support\Generator; -use Illuminate\Support\Str; class EloquentHasManyTest extends DatabaseTestCase { diff --git a/tests/Integration/Database/EloquentHasManyThroughTest.php b/tests/Integration/Database/EloquentHasManyThroughTest.php index 4a0b01169cc3..af05e9a57adb 100644 --- a/tests/Integration/Database/EloquentHasManyThroughTest.php +++ b/tests/Integration/Database/EloquentHasManyThroughTest.php @@ -8,7 +8,6 @@ use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use Illuminate\Tests\Integration\Database\DatabaseTestCase; class EloquentHasManyThroughTest extends DatabaseTestCase diff --git a/tests/Integration/Database/EloquentModelTest.php b/tests/Integration/Database/EloquentModelTest.php index 9f23e44da27c..44ad4667a6f4 100644 --- a/tests/Integration/Database/EloquentModelTest.php +++ b/tests/Integration/Database/EloquentModelTest.php @@ -7,7 +7,6 @@ use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Schema; use Illuminate\Support\Generator; -use Illuminate\Support\Str; class EloquentModelTest extends DatabaseTestCase { diff --git a/tests/Integration/Database/EloquentMorphManyTest.php b/tests/Integration/Database/EloquentMorphManyTest.php index 37f169ee7195..6e3dcd1f4157 100644 --- a/tests/Integration/Database/EloquentMorphManyTest.php +++ b/tests/Integration/Database/EloquentMorphManyTest.php @@ -8,7 +8,6 @@ use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Schema; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use Illuminate\Tests\Integration\Database\DatabaseTestCase; class EloquentMorphManyTest extends DatabaseTestCase diff --git a/tests/Integration/Database/EloquentTouchParentWithGlobalScopeTest.php b/tests/Integration/Database/EloquentTouchParentWithGlobalScopeTest.php index 38ae67f4d485..76efa4cc0a1b 100644 --- a/tests/Integration/Database/EloquentTouchParentWithGlobalScopeTest.php +++ b/tests/Integration/Database/EloquentTouchParentWithGlobalScopeTest.php @@ -6,7 +6,6 @@ use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use Illuminate\Tests\Integration\Database\DatabaseTestCase; class EloquentTouchParentWithGlobalScopeTest extends DatabaseTestCase diff --git a/tests/Integration/Database/EloquentUpdateTest.php b/tests/Integration/Database/EloquentUpdateTest.php index 1df27dd39261..dfa6225209b2 100644 --- a/tests/Integration/Database/EloquentUpdateTest.php +++ b/tests/Integration/Database/EloquentUpdateTest.php @@ -7,7 +7,6 @@ use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; use Illuminate\Support\Generator; -use Illuminate\Support\Str; class EloquentUpdateTest extends DatabaseTestCase { diff --git a/tests/Integration/Database/MySql/JoinLateralTest.php b/tests/Integration/Database/MySql/JoinLateralTest.php index c5303e83855c..b45ab58cb869 100644 --- a/tests/Integration/Database/MySql/JoinLateralTest.php +++ b/tests/Integration/Database/MySql/JoinLateralTest.php @@ -6,7 +6,6 @@ use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use PHPUnit\Framework\Attributes\RequiresOperatingSystemFamily; use PHPUnit\Framework\Attributes\RequiresPhpExtension; diff --git a/tests/Integration/Database/Postgres/JoinLateralTest.php b/tests/Integration/Database/Postgres/JoinLateralTest.php index edff78e73fe7..d1d3e7566689 100644 --- a/tests/Integration/Database/Postgres/JoinLateralTest.php +++ b/tests/Integration/Database/Postgres/JoinLateralTest.php @@ -6,7 +6,6 @@ use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use PHPUnit\Framework\Attributes\RequiresOperatingSystemFamily; use PHPUnit\Framework\Attributes\RequiresPhpExtension; diff --git a/tests/Integration/Database/SqlServer/JoinLateralTest.php b/tests/Integration/Database/SqlServer/JoinLateralTest.php index e0ea8feceb70..77c13e9ff015 100644 --- a/tests/Integration/Database/SqlServer/JoinLateralTest.php +++ b/tests/Integration/Database/SqlServer/JoinLateralTest.php @@ -6,7 +6,6 @@ use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; use Illuminate\Support\Generator; -use Illuminate\Support\Str; class JoinLateralTest extends SqlServerTestCase { diff --git a/tests/Integration/Database/Sqlite/EloquentModelConnectionsTest.php b/tests/Integration/Database/Sqlite/EloquentModelConnectionsTest.php index 54ac479a8327..b76fd8e00900 100644 --- a/tests/Integration/Database/Sqlite/EloquentModelConnectionsTest.php +++ b/tests/Integration/Database/Sqlite/EloquentModelConnectionsTest.php @@ -6,7 +6,6 @@ use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use Orchestra\Testbench\Attributes\RequiresDatabase; use Orchestra\Testbench\TestCase; diff --git a/tests/Integration/Foundation/Support/Providers/RouteServiceProviderHealthTest.php b/tests/Integration/Foundation/Support/Providers/RouteServiceProviderHealthTest.php index 18ac414b9954..c00387d84fd6 100644 --- a/tests/Integration/Foundation/Support/Providers/RouteServiceProviderHealthTest.php +++ b/tests/Integration/Foundation/Support/Providers/RouteServiceProviderHealthTest.php @@ -4,7 +4,6 @@ use Illuminate\Foundation\Application; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use Orchestra\Testbench\TestCase; class RouteServiceProviderHealthTest extends TestCase diff --git a/tests/Integration/Notifications/SendingMailNotificationsTest.php b/tests/Integration/Notifications/SendingMailNotificationsTest.php index 3d62cb950246..ae4043d17ab8 100644 --- a/tests/Integration/Notifications/SendingMailNotificationsTest.php +++ b/tests/Integration/Notifications/SendingMailNotificationsTest.php @@ -15,7 +15,6 @@ use Illuminate\Notifications\Notification; use Illuminate\Support\Facades\Schema; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use Mockery as m; use Orchestra\Testbench\TestCase; diff --git a/tests/Integration/Queue/DynamoBatchTest.php b/tests/Integration/Queue/DynamoBatchTest.php index 917324056f02..4e37a23e99f8 100644 --- a/tests/Integration/Queue/DynamoBatchTest.php +++ b/tests/Integration/Queue/DynamoBatchTest.php @@ -11,7 +11,6 @@ use Illuminate\Support\Env; use Illuminate\Support\Facades\Bus; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use Orchestra\Testbench\Attributes\RequiresEnv; use Orchestra\Testbench\TestCase; use PHPUnit\Framework\Attributes\RequiresOperatingSystem; diff --git a/tests/Integration/Queue/JobEncryptionTest.php b/tests/Integration/Queue/JobEncryptionTest.php index 2c2faea5060c..d12095268ea8 100644 --- a/tests/Integration/Queue/JobEncryptionTest.php +++ b/tests/Integration/Queue/JobEncryptionTest.php @@ -12,7 +12,6 @@ use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Queue; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use Illuminate\Tests\Integration\Database\DatabaseTestCase; use Orchestra\Testbench\Attributes\WithMigration; diff --git a/tests/Integration/Queue/RateLimitedWithRedisTest.php b/tests/Integration/Queue/RateLimitedWithRedisTest.php index e34c7280bfa3..544f8e00ac67 100644 --- a/tests/Integration/Queue/RateLimitedWithRedisTest.php +++ b/tests/Integration/Queue/RateLimitedWithRedisTest.php @@ -13,7 +13,6 @@ use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\Middleware\RateLimitedWithRedis; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use Mockery as m; use Orchestra\Testbench\TestCase; use PHPUnit\Framework\Attributes\RequiresPhpExtension; diff --git a/tests/Integration/Queue/ThrottlesExceptionsWithRedisTest.php b/tests/Integration/Queue/ThrottlesExceptionsWithRedisTest.php index e83ce73ea4bb..97ad455fe8f4 100644 --- a/tests/Integration/Queue/ThrottlesExceptionsWithRedisTest.php +++ b/tests/Integration/Queue/ThrottlesExceptionsWithRedisTest.php @@ -13,7 +13,6 @@ use Illuminate\Queue\Middleware\ThrottlesExceptionsWithRedis; use Illuminate\Support\Carbon; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use Mockery as m; use Orchestra\Testbench\TestCase; use PHPUnit\Framework\Attributes\RequiresPhpExtension; diff --git a/tests/Integration/Session/CookieSessionHandlerTest.php b/tests/Integration/Session/CookieSessionHandlerTest.php index 10286126f3df..ea6d874e5eb3 100644 --- a/tests/Integration/Session/CookieSessionHandlerTest.php +++ b/tests/Integration/Session/CookieSessionHandlerTest.php @@ -4,7 +4,6 @@ use Illuminate\Support\Facades\Route; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use Orchestra\Testbench\TestCase; class CookieSessionHandlerTest extends TestCase diff --git a/tests/Integration/Session/SessionPersistenceTest.php b/tests/Integration/Session/SessionPersistenceTest.php index a0bb24d942d1..aa6b2f1cd75e 100644 --- a/tests/Integration/Session/SessionPersistenceTest.php +++ b/tests/Integration/Session/SessionPersistenceTest.php @@ -9,7 +9,6 @@ use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Session; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use Mockery as m; use Orchestra\Testbench\TestCase; diff --git a/tests/Integration/Validation/ValidatorTest.php b/tests/Integration/Validation/ValidatorTest.php index 3320dd39182f..c3e08e47e633 100644 --- a/tests/Integration/Validation/ValidatorTest.php +++ b/tests/Integration/Validation/ValidatorTest.php @@ -6,7 +6,6 @@ use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use Illuminate\Tests\Integration\Database\DatabaseTestCase; use Illuminate\Translation\ArrayLoader; use Illuminate\Translation\Translator; diff --git a/tests/Queue/DatabaseFailedJobProviderTest.php b/tests/Queue/DatabaseFailedJobProviderTest.php index 235d673d404a..702ba994051e 100644 --- a/tests/Queue/DatabaseFailedJobProviderTest.php +++ b/tests/Queue/DatabaseFailedJobProviderTest.php @@ -8,7 +8,6 @@ use Illuminate\Queue\Failed\DatabaseFailedJobProvider; use Illuminate\Support\Facades\Date; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use PHPUnit\Framework\TestCase; use RuntimeException; diff --git a/tests/Queue/DatabaseUuidFailedJobProviderTest.php b/tests/Queue/DatabaseUuidFailedJobProviderTest.php index 362d9ba9a787..cac2f6b9afa0 100644 --- a/tests/Queue/DatabaseUuidFailedJobProviderTest.php +++ b/tests/Queue/DatabaseUuidFailedJobProviderTest.php @@ -6,7 +6,6 @@ use Illuminate\Database\Schema\Blueprint; use Illuminate\Queue\Failed\DatabaseUuidFailedJobProvider; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use PHPUnit\Framework\TestCase; use RuntimeException; diff --git a/tests/Queue/FileFailedJobProviderTest.php b/tests/Queue/FileFailedJobProviderTest.php index 19b36895e5eb..eada7813bc05 100644 --- a/tests/Queue/FileFailedJobProviderTest.php +++ b/tests/Queue/FileFailedJobProviderTest.php @@ -5,7 +5,6 @@ use Exception; use Illuminate\Queue\Failed\FileFailedJobProvider; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use PHPUnit\Framework\TestCase; class FileFailedJobProviderTest extends TestCase diff --git a/tests/Queue/QueueDatabaseQueueIntegrationTest.php b/tests/Queue/QueueDatabaseQueueIntegrationTest.php index c61e9b76ff6d..5e2daba5a7d3 100644 --- a/tests/Queue/QueueDatabaseQueueIntegrationTest.php +++ b/tests/Queue/QueueDatabaseQueueIntegrationTest.php @@ -12,7 +12,6 @@ use Illuminate\Queue\Events\JobQueueing; use Illuminate\Support\Carbon; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use PHPUnit\Framework\TestCase; class QueueDatabaseQueueIntegrationTest extends TestCase diff --git a/tests/Routing/RoutingRouteTest.php b/tests/Routing/RoutingRouteTest.php index 14eed794b48f..f99e2a6dcb2d 100644 --- a/tests/Routing/RoutingRouteTest.php +++ b/tests/Routing/RoutingRouteTest.php @@ -38,7 +38,6 @@ use Illuminate\Routing\Router; use Illuminate\Routing\UrlGenerator; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use LogicException; use PHPUnit\Framework\TestCase; use stdClass; diff --git a/tests/Session/SessionStoreTest.php b/tests/Session/SessionStoreTest.php index 8f12ae6b8e27..9e9750115cab 100644 --- a/tests/Session/SessionStoreTest.php +++ b/tests/Session/SessionStoreTest.php @@ -7,7 +7,6 @@ use Illuminate\Session\Store; use Illuminate\Support\Generator; use Illuminate\Support\MessageBag; -use Illuminate\Support\Str; use Illuminate\Support\ViewErrorBag; use Mockery as m; use PHPUnit\Framework\TestCase; diff --git a/tests/Support/SupportStrTest.php b/tests/Support/SupportStrTest.php index c854f31f0e41..ea479d18f105 100755 --- a/tests/Support/SupportStrTest.php +++ b/tests/Support/SupportStrTest.php @@ -2,13 +2,10 @@ namespace Illuminate\Tests\Support; -use Exception; use Illuminate\Support\PatternMatcher; use Illuminate\Support\Str; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; -use Ramsey\Uuid\UuidInterface; -use ReflectionClass; use ValueError; class SupportStrTest extends TestCase From 0f9c71c19796ba96d7c8650441dd598929a777f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20H=C3=A4drich?= Date: Mon, 30 Sep 2024 18:41:27 +0200 Subject: [PATCH 11/14] style: :art: More styleCI stuff --- src/Illuminate/Foundation/Vite.php | 1 - tests/Support/SupportCasingTest.php | 1 - 2 files changed, 2 deletions(-) diff --git a/src/Illuminate/Foundation/Vite.php b/src/Illuminate/Foundation/Vite.php index d85841d37c9f..41416c78fd2b 100644 --- a/src/Illuminate/Foundation/Vite.php +++ b/src/Illuminate/Foundation/Vite.php @@ -7,7 +7,6 @@ use Illuminate\Support\Generator; use Illuminate\Support\HtmlString; use Illuminate\Support\Js; -use Illuminate\Support\Str; use Illuminate\Support\Traits\Macroable; class Vite implements Htmlable diff --git a/tests/Support/SupportCasingTest.php b/tests/Support/SupportCasingTest.php index d3fd4e9b009c..8f8993559cf0 100644 --- a/tests/Support/SupportCasingTest.php +++ b/tests/Support/SupportCasingTest.php @@ -8,7 +8,6 @@ class SupportCasingTest extends TestCase { - public function testConvertCase() { // Upper Case Conversion From 2c15ea60f8abbc05520c613974bf829985ec83e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20H=C3=A4drich?= Date: Mon, 30 Sep 2024 18:47:47 +0200 Subject: [PATCH 12/14] fix: :bug: Fix some more wrong/missing imports --- src/Illuminate/Bus/Batchable.php | 2 +- src/Illuminate/Support/Casing.php | 4 ++-- src/Illuminate/Support/Replacer.php | 17 +++++++++++++++++ src/Illuminate/Support/Str.php | 17 ----------------- src/Illuminate/Testing/ParallelTesting.php | 1 + 5 files changed, 21 insertions(+), 20 deletions(-) diff --git a/src/Illuminate/Bus/Batchable.php b/src/Illuminate/Bus/Batchable.php index fb49367f0f93..db093075dd61 100644 --- a/src/Illuminate/Bus/Batchable.php +++ b/src/Illuminate/Bus/Batchable.php @@ -3,8 +3,8 @@ namespace Illuminate\Bus; use Carbon\CarbonImmutable; -use Generator; use Illuminate\Container\Container; +use Illuminate\Support\Generator; use Illuminate\Support\Testing\Fakes\BatchFake; trait Batchable diff --git a/src/Illuminate/Support/Casing.php b/src/Illuminate/Support/Casing.php index 4c4c6060ad20..d218b56c4713 100644 --- a/src/Illuminate/Support/Casing.php +++ b/src/Illuminate/Support/Casing.php @@ -115,7 +115,7 @@ public static function headline($value) ? array_map([static::class, 'title'], $parts) : array_map([static::class, 'title'], Str::ucsplit(implode('_', $parts))); - $collapsed = Str::replace(['-', '_', ' '], '_', implode('_', $parts)); + $collapsed = Replacer::replace(['-', '_', ' '], '_', implode('_', $parts)); return implode(' ', array_filter(explode('_', $collapsed))); } @@ -180,7 +180,7 @@ public static function studly($value) return static::$studlyCache[$key]; } - $words = explode(' ', Str::replace(['-', '_'], ' ', $value)); + $words = explode(' ', Replacer::replace(['-', '_'], ' ', $value)); $studlyWords = array_map(fn ($word) => static::ucfirst($word), $words); diff --git a/src/Illuminate/Support/Replacer.php b/src/Illuminate/Support/Replacer.php index b8ecafe091ff..7b9b1bc0edd2 100644 --- a/src/Illuminate/Support/Replacer.php +++ b/src/Illuminate/Support/Replacer.php @@ -4,6 +4,7 @@ use Closure; use Illuminate\Support\Traits\Macroable; +use Throwable; use Traversable; class Replacer @@ -205,4 +206,20 @@ public static function substrReplace($string, $replace, $offset = 0, $length = n return substr_replace($string, $replace, $offset, $length); } + + /** + * Convert the given value to a string or return the given fallback on failure. + * + * @param mixed $value + * @param string $fallback + * @return string + */ + private static function toStringOr($value, $fallback) + { + try { + return (string) $value; + } catch (Throwable $e) { + return $fallback; + } + } } diff --git a/src/Illuminate/Support/Str.php b/src/Illuminate/Support/Str.php index b30d78399af9..1be183e47c54 100644 --- a/src/Illuminate/Support/Str.php +++ b/src/Illuminate/Support/Str.php @@ -10,7 +10,6 @@ use League\CommonMark\GithubFlavoredMarkdownConverter; use League\CommonMark\MarkdownConverter; use Symfony\Component\Uid\Ulid; -use Throwable; use voku\helper\ASCII; class Str @@ -670,22 +669,6 @@ public static function repeat(string $string, int $times) return str_repeat($string, $times); } - /** - * Convert the given value to a string or return the given fallback on failure. - * - * @param mixed $value - * @param string $fallback - * @return string - */ - private static function toStringOr($value, $fallback) - { - try { - return (string) $value; - } catch (Throwable $e) { - return $fallback; - } - } - /** * Reverse the given string. * diff --git a/src/Illuminate/Testing/ParallelTesting.php b/src/Illuminate/Testing/ParallelTesting.php index 321c8fd6db05..0abaaf11e157 100644 --- a/src/Illuminate/Testing/ParallelTesting.php +++ b/src/Illuminate/Testing/ParallelTesting.php @@ -3,6 +3,7 @@ namespace Illuminate\Testing; use Illuminate\Contracts\Container\Container; +use Illuminate\Support\Casing; class ParallelTesting { From fca80c77f883279e50f6ff102f71f48bd3fb619d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20H=C3=A4drich?= Date: Mon, 30 Sep 2024 18:52:09 +0200 Subject: [PATCH 13/14] fix: :bug: Change method call to static after moving related method to same file --- src/Illuminate/Support/Replacer.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Illuminate/Support/Replacer.php b/src/Illuminate/Support/Replacer.php index 7b9b1bc0edd2..0f49ce6205e1 100644 --- a/src/Illuminate/Support/Replacer.php +++ b/src/Illuminate/Support/Replacer.php @@ -41,7 +41,7 @@ public static function replaceArray($search, $replace, $subject) $result = array_shift($segments); foreach ($segments as $segment) { - $result .= Str::toStringOr(array_shift($replace) ?? $search, $search).$segment; + $result .= static::toStringOr(array_shift($replace) ?? $search, $search).$segment; } return $result; From 8c60820de2270d0431fe928e382183e1d163ed03 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20H=C3=A4drich?= Date: Mon, 30 Sep 2024 19:35:43 +0200 Subject: [PATCH 14/14] fix: :bug: Next bugfixes --- tests/Integration/Queue/RedisQueueTest.php | 3 +-- tests/Queue/DynamoDbFailedJobProviderTest.php | 3 +-- tests/Queue/QueueBeanstalkdQueueTest.php | 3 +-- tests/Queue/QueueDatabaseQueueUnitTest.php | 7 +++---- tests/Queue/QueueRedisQueueTest.php | 9 ++++----- tests/View/Blade/BladePrependTest.php | 4 ++-- tests/View/Blade/BladePushTest.php | 4 ++-- 7 files changed, 14 insertions(+), 19 deletions(-) diff --git a/tests/Integration/Queue/RedisQueueTest.php b/tests/Integration/Queue/RedisQueueTest.php index 0d3783978a98..57f7f081e806 100644 --- a/tests/Integration/Queue/RedisQueueTest.php +++ b/tests/Integration/Queue/RedisQueueTest.php @@ -11,7 +11,6 @@ use Illuminate\Queue\RedisQueue; use Illuminate\Support\Generator; use Illuminate\Support\InteractsWithTime; -use Illuminate\Support\Str; use Mockery as m; use Orchestra\Testbench\TestCase; use PHPUnit\Framework\Attributes\DataProvider; @@ -246,7 +245,7 @@ public function testBlockingPopProperlyPopsJobOffOfRedis($driver) #[DataProvider('redisDriverProvider')] public function testBlockingPopProperlyPopsExpiredJobs($driver) { - Str::createUuidsUsing(function () { + Generator::createUuidsUsing(function () { return 'uuid'; }); diff --git a/tests/Queue/DynamoDbFailedJobProviderTest.php b/tests/Queue/DynamoDbFailedJobProviderTest.php index 665cdbf554b0..d2cf27df2c6c 100644 --- a/tests/Queue/DynamoDbFailedJobProviderTest.php +++ b/tests/Queue/DynamoDbFailedJobProviderTest.php @@ -9,7 +9,6 @@ use Illuminate\Queue\Failed\DynamoDbFailedJobProvider; use Illuminate\Support\Carbon; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use Mockery as m; use PHPUnit\Framework\TestCase; @@ -24,7 +23,7 @@ public function testCanProperlyLogFailedJob() { $uuid = Generator::orderedUuid(); - Str::createUuidsUsing(function () use ($uuid) { + Generator::createUuidsUsing(function () use ($uuid) { return $uuid; }); diff --git a/tests/Queue/QueueBeanstalkdQueueTest.php b/tests/Queue/QueueBeanstalkdQueueTest.php index 66d263292d82..7ba0f0353f7a 100755 --- a/tests/Queue/QueueBeanstalkdQueueTest.php +++ b/tests/Queue/QueueBeanstalkdQueueTest.php @@ -6,7 +6,6 @@ use Illuminate\Queue\BeanstalkdQueue; use Illuminate\Queue\Jobs\BeanstalkdJob; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use Mockery as m; use Pheanstalk\Contract\JobIdInterface; use Pheanstalk\Contract\PheanstalkManagerInterface; @@ -39,7 +38,7 @@ public function testPushProperlyPushesJobOntoBeanstalkd() { $uuid = Generator::uuid(); - Str::createUuidsUsing(function () use ($uuid) { + Generator::createUuidsUsing(function () use ($uuid) { return $uuid; }); diff --git a/tests/Queue/QueueDatabaseQueueUnitTest.php b/tests/Queue/QueueDatabaseQueueUnitTest.php index 207f22b24049..b9b4ef479023 100644 --- a/tests/Queue/QueueDatabaseQueueUnitTest.php +++ b/tests/Queue/QueueDatabaseQueueUnitTest.php @@ -7,7 +7,6 @@ use Illuminate\Queue\DatabaseQueue; use Illuminate\Queue\Queue; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; @@ -24,7 +23,7 @@ protected function tearDown(): void #[DataProvider('pushJobsDataProvider')] public function testPushProperlyPushesJobOntoDatabase($uuid, $job, $displayNameStartsWith, $jobStartsWith) { - Str::createUuidsUsing(function () use ($uuid) { + Generator::createUuidsUsing(function () use ($uuid) { return $uuid; }); @@ -66,7 +65,7 @@ public function testDelayedPushProperlyPushesJobOntoDatabase() { $uuid = Generator::uuid(); - Str::createUuidsUsing(function () use ($uuid) { + Generator::createUuidsUsing(function () use ($uuid) { return $uuid; }); @@ -127,7 +126,7 @@ public function testBulkBatchPushesOntoDatabase() { $uuid = Generator::uuid(); - Str::createUuidsUsing(function () use ($uuid) { + Generator::createUuidsUsing(function () use ($uuid) { return $uuid; }); diff --git a/tests/Queue/QueueRedisQueueTest.php b/tests/Queue/QueueRedisQueueTest.php index f4b8607d26ba..0f28943d76d3 100644 --- a/tests/Queue/QueueRedisQueueTest.php +++ b/tests/Queue/QueueRedisQueueTest.php @@ -9,7 +9,6 @@ use Illuminate\Queue\RedisQueue; use Illuminate\Support\Carbon; use Illuminate\Support\Generator; -use Illuminate\Support\Str; use Mockery as m; use PHPUnit\Framework\TestCase; @@ -45,7 +44,7 @@ public function testPushProperlyPushesJobOntoRedisWithCustomPayloadHook() { $uuid = Generator::uuid(); - Str::createUuidsUsing(function () use ($uuid) { + Generator::createUuidsUsing(function () use ($uuid) { return $uuid; }); @@ -72,7 +71,7 @@ public function testPushProperlyPushesJobOntoRedisWithTwoCustomPayloadHook() { $uuid = Generator::uuid(); - Str::createUuidsUsing(function () use ($uuid) { + Generator::createUuidsUsing(function () use ($uuid) { return $uuid; }); @@ -103,7 +102,7 @@ public function testDelayedPushProperlyPushesJobOntoRedis() { $uuid = Generator::uuid(); - Str::createUuidsUsing(function () use ($uuid) { + Generator::createUuidsUsing(function () use ($uuid) { return $uuid; }); @@ -130,7 +129,7 @@ public function testDelayedPushWithDateTimeProperlyPushesJobOntoRedis() { $uuid = Generator::uuid(); - Str::createUuidsUsing(function () use ($uuid) { + Generator::createUuidsUsing(function () use ($uuid) { return $uuid; }); diff --git a/tests/View/Blade/BladePrependTest.php b/tests/View/Blade/BladePrependTest.php index 11bc1fa100da..d74e629577ed 100644 --- a/tests/View/Blade/BladePrependTest.php +++ b/tests/View/Blade/BladePrependTest.php @@ -2,7 +2,7 @@ namespace Illuminate\Tests\View\Blade; -use Illuminate\Support\Str; +use Illuminate\Support\Generator; class BladePrependTest extends AbstractBladeTestCase { @@ -34,7 +34,7 @@ public function testPrependOnceIsCompiled() public function testPrependOnceIsCompiledWhenIdIsMissing() { - Str::createUuidsUsing(fn () => 'e60e8f77-9ac3-4f71-9f8e-a044ef481d7f'); + Generator::createUuidsUsing(fn () => 'e60e8f77-9ac3-4f71-9f8e-a044ef481d7f'); $string = '@prependOnce(\'foo\') test diff --git a/tests/View/Blade/BladePushTest.php b/tests/View/Blade/BladePushTest.php index 84f3d3f33bfd..fad7ed9befd4 100644 --- a/tests/View/Blade/BladePushTest.php +++ b/tests/View/Blade/BladePushTest.php @@ -2,7 +2,7 @@ namespace Illuminate\Tests\View\Blade; -use Illuminate\Support\Str; +use Illuminate\Support\Generator; class BladePushTest extends AbstractBladeTestCase { @@ -44,7 +44,7 @@ public function testPushOnceIsCompiled() public function testPushOnceIsCompiledWhenIdIsMissing() { - Str::createUuidsUsing(fn () => 'e60e8f77-9ac3-4f71-9f8e-a044ef481d7f'); + Generator::createUuidsUsing(fn () => 'e60e8f77-9ac3-4f71-9f8e-a044ef481d7f'); $string = '@pushOnce(\'foo\') test