Skip to content

Commit

Permalink
[11.x] Prefer new Stringable over Str::of and str() (#53883)
Browse files Browse the repository at this point in the history
  • Loading branch information
lucasmichot authored Dec 13, 2024
1 parent cf7886b commit 0c0ec9f
Show file tree
Hide file tree
Showing 43 changed files with 117 additions and 90 deletions.
4 changes: 2 additions & 2 deletions src/Illuminate/Console/Concerns/CreatesMatchingTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace Illuminate\Console\Concerns;

use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
use Symfony\Component\Console\Input\InputOption;

trait CreatesMatchingTest
Expand Down Expand Up @@ -37,7 +37,7 @@ protected function handleTestCreation($path)
}

return $this->call('make:test', [
'name' => Str::of($path)->after($this->laravel['path'])->beforeLast('.php')->append('Test')->replace('\\', '/'),
'name' => (new Stringable($path))->after($this->laravel['path'])->beforeLast('.php')->append('Test')->replace('\\', '/'),
'--pest' => $this->option('pest'),
'--phpunit' => $this->option('phpunit'),
]) == 0;
Expand Down
3 changes: 2 additions & 1 deletion src/Illuminate/Console/QuestionHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Illuminate\Console;

use Illuminate\Console\View\Components\TwoColumnDetail;
use Illuminate\Support\Stringable;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Helper\SymfonyQuestionHelper;
use Symfony\Component\Console\Output\OutputInterface;
Expand Down Expand Up @@ -76,7 +77,7 @@ protected function writePrompt(OutputInterface $output, Question $question): voi
*/
protected function ensureEndsWithPunctuation($string)
{
if (! str($string)->endsWith(['?', ':', '!', '.'])) {
if (! (new Stringable($string))->endsWith(['?', ':', '!', '.'])) {
return "$string:";
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace Illuminate\Console\View\Components\Mutators;

use Illuminate\Support\Stringable;

class EnsureNoPunctuation
{
/**
Expand All @@ -12,7 +14,7 @@ class EnsureNoPunctuation
*/
public function __invoke($string)
{
if (str($string)->endsWith(['.', '?', '!', ':'])) {
if ((new Stringable($string))->endsWith(['.', '?', '!', ':'])) {
return substr_replace($string, '', -1);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace Illuminate\Console\View\Components\Mutators;

use Illuminate\Support\Stringable;

class EnsurePunctuation
{
/**
Expand All @@ -12,7 +14,7 @@ class EnsurePunctuation
*/
public function __invoke($string)
{
if (! str($string)->endsWith(['.', '?', '!', ':'])) {
if (! (new Stringable($string))->endsWith(['.', '?', '!', ':'])) {
return "$string.";
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Illuminate\Console\GeneratorCommand;
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Input\InputOption;

Expand Down Expand Up @@ -99,7 +100,7 @@ protected function buildClass($name)
*/
protected function getPath($name)
{
$name = (string) Str::of($name)->replaceFirst($this->rootNamespace(), '')->finish('Factory');
$name = (new Stringable($name))->replaceFirst($this->rootNamespace(), '')->finish('Factory')->value();

return $this->laravel->databasePath().'/factories/'.str_replace('\\', '/', $name).'.php';
}
Expand Down
5 changes: 3 additions & 2 deletions src/Illuminate/Database/Console/Migrations/StatusCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Illuminate\Database\Migrations\Migrator;
use Illuminate\Support\Collection;
use Illuminate\Support\Stringable;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Input\InputOption;

Expand Down Expand Up @@ -64,7 +65,7 @@ public function handle()

$migrations = $this->getStatusFor($ran, $batches)
->when($this->option('pending') !== false, fn ($collection) => $collection->filter(function ($migration) {
return str($migration[1])->contains('Pending');
return (new Stringable($migration[1]))->contains('Pending');
}));

if (count($migrations) > 0) {
Expand All @@ -84,7 +85,7 @@ public function handle()
$this->components->info('No migrations found');
}

if ($this->option('pending') && $migrations->some(fn ($m) => str($m[1])->contains('Pending'))) {
if ($this->option('pending') && $migrations->some(fn ($m) => (new Stringable($m[1]))->contains('Pending'))) {
return $this->option('pending');
}
});
Expand Down
3 changes: 2 additions & 1 deletion src/Illuminate/Database/Console/ShowCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Number;
use Illuminate\Support\Stringable;
use Symfony\Component\Console\Attribute\AsCommand;

#[AsCommand(name: 'db:show')]
Expand Down Expand Up @@ -99,7 +100,7 @@ protected function tables(ConnectionInterface $connection, Builder $schema)
protected function views(ConnectionInterface $connection, Builder $schema)
{
return (new Collection($schema->getViews()))
->reject(fn ($view) => str($view['name'])->startsWith(['pg_catalog', 'information_schema', 'spt_']))
->reject(fn ($view) => (new Stringable($view['name']))->startsWith(['pg_catalog', 'information_schema', 'spt_']))
->map(fn ($view) => [
'view' => $view['name'],
'schema' => $view['schema'],
Expand Down
4 changes: 2 additions & 2 deletions src/Illuminate/Database/Eloquent/Casts/AsStringable.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

use Illuminate\Contracts\Database\Eloquent\Castable;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;

class AsStringable implements Castable
{
Expand All @@ -20,7 +20,7 @@ public static function castUsing(array $arguments)
{
public function get($model, $key, $value, $attributes)
{
return isset($value) ? Str::of($value) : null;
return isset($value) ? new Stringable($value) : null;
}

public function set($model, $key, $value, $attributes)
Expand Down
3 changes: 2 additions & 1 deletion src/Illuminate/Database/Eloquent/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use Illuminate\Support\Arr;
use Illuminate\Support\Collection as BaseCollection;
use Illuminate\Support\Str;
use Illuminate\Support\Stringable as SupportStringable;
use Illuminate\Support\Traits\ForwardsCalls;
use JsonException;
use JsonSerializable;
Expand Down Expand Up @@ -2360,7 +2361,7 @@ public function __call($method, $parameters)
}

if (Str::startsWith($method, 'through') &&
method_exists($this, $relationMethod = Str::of($method)->after('through')->lcfirst()->toString())) {
method_exists($this, $relationMethod = (new SupportStringable($method))->after('through')->lcfirst()->toString())) {
return $this->through($relationMethod);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphOneOrMany;
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;

/**
* @template TIntermediateModel of \Illuminate\Database\Eloquent\Model
Expand Down Expand Up @@ -106,7 +107,7 @@ public function has($callback)
public function __call($method, $parameters)
{
if (Str::startsWith($method, 'has')) {
return $this->has(Str::of($method)->after('has')->lcfirst()->toString());
return $this->has((new Stringable($method))->after('has')->lcfirst()->toString());
}

throw new BadMethodCallException(sprintf(
Expand Down
4 changes: 2 additions & 2 deletions src/Illuminate/Database/Schema/ForeignIdColumnDefinition.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace Illuminate\Database\Schema;

use Illuminate\Support\Str;
use Illuminate\Support\Stringable;

class ForeignIdColumnDefinition extends ColumnDefinition
{
Expand Down Expand Up @@ -40,7 +40,7 @@ public function constrained($table = null, $column = null, $indexName = null)
$table ??= $this->table;
$column ??= $this->referencesModelColumn ?? 'id';

return $this->references($column, $indexName)->on($table ?? Str::of($this->name)->beforeLast('_'.$column)->plural());
return $this->references($column, $indexName)->on($table ?? (new Stringable($this->name))->beforeLast('_'.$column)->plural());
}

/**
Expand Down
5 changes: 3 additions & 2 deletions src/Illuminate/Foundation/Console/AboutCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Illuminate\Support\Collection;
use Illuminate\Support\Composer;
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
use Symfony\Component\Console\Attribute\AsCommand;

#[AsCommand(name: 'about')]
Expand Down Expand Up @@ -144,7 +145,7 @@ protected function displayJson($data)
{
$output = $data->flatMap(function ($data, $section) {
return [
(string) Str::of($section)->snake() => $data->mapWithKeys(fn ($item, $key) => [
(new Stringable($section))->snake()->value() => $data->mapWithKeys(fn ($item, $key) => [
$this->toSearchKeyword($item[0]) => value($item[1], true),
]),
];
Expand Down Expand Up @@ -303,7 +304,7 @@ public static function format($value, ?Closure $console = null, ?Closure $json =
*/
protected function toSearchKeyword(string $value)
{
return (string) Str::of($value)->lower()->snake();
return (new Stringable($value))->lower()->snake()->value();
}

/**
Expand Down
4 changes: 2 additions & 2 deletions src/Illuminate/Foundation/Console/ConsoleMakeCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

use Illuminate\Console\Concerns\CreatesMatchingTest;
use Illuminate\Console\GeneratorCommand;
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
Expand Down Expand Up @@ -46,7 +46,7 @@ protected function replaceClass($stub, $name)
{
$stub = parent::replaceClass($stub, $name);

$command = $this->option('command') ?: 'app:'.Str::of($name)->classBasename()->kebab()->value();
$command = $this->option('command') ?: 'app:'.(new Stringable($name))->classBasename()->kebab()->value();

return str_replace(['dummy:command', '{{ command }}'], $command, $stub);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Illuminate/Foundation/Console/ModelMakeCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ protected function buildFactoryReplacements()
$replacements = [];

if ($this->option('factory') || $this->option('all')) {
$modelPath = str($this->argument('name'))->studly()->replace('/', '\\')->toString();
$modelPath = Str::of($this->argument('name'))->studly()->replace('/', '\\')->toString();

$factoryNamespace = '\\Database\\Factories\\'.$modelPath.'Factory';

Expand Down
5 changes: 3 additions & 2 deletions src/Illuminate/Foundation/Console/RouteListCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
use ReflectionClass;
use ReflectionFunction;
use Symfony\Component\Console\Attribute\AsCommand;
Expand Down Expand Up @@ -372,7 +373,7 @@ protected function forCli($routes)
'uri' => $uri,
] = $route;

$middleware = Str::of($middleware)->explode("\n")->filter()->whenNotEmpty(
$middleware = (new Stringable($middleware))->explode("\n")->filter()->whenNotEmpty(
fn ($collection) => $collection->map(
fn ($middleware) => sprintf(' %s⇂ %s', str_repeat(' ', $maxMethod), $middleware)
)
Expand All @@ -390,7 +391,7 @@ protected function forCli($routes)
$action = substr($action, 0, $terminalWidth - 7 - mb_strlen($method.$spaces.$uri.$dots)).'';
}

$method = Str::of($method)->explode('|')->map(
$method = (new Stringable($method))->explode('|')->map(
fn ($method) => sprintf('<fg=%s>%s</>', $this->verbColors[$method] ?? 'default', $method),
)->implode('<fg=#6C7280>|</>');

Expand Down
19 changes: 10 additions & 9 deletions src/Illuminate/Foundation/Console/ServeCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Illuminate\Support\Collection;
use Illuminate\Support\Env;
use Illuminate\Support\InteractsWithTime;
use Illuminate\Support\Stringable;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Process\Process;
Expand Down Expand Up @@ -270,15 +271,15 @@ protected function handleProcessOutput()
*/
protected function flushOutputBuffer()
{
$lines = str($this->outputBuffer)->explode("\n");
$lines = (new Stringable($this->outputBuffer))->explode("\n");

$this->outputBuffer = (string) $lines->pop();

$lines
->map(fn ($line) => trim($line))
->filter()
->each(function ($line) {
if (str($line)->contains('Development Server (http')) {
if ((new Stringable($line))->contains('Development Server (http')) {
if ($this->serverRunningHasBeenDisplayed === false) {
$this->serverRunningHasBeenDisplayed = true;

Expand All @@ -291,23 +292,23 @@ protected function flushOutputBuffer()
return;
}

if (str($line)->contains(' Accepted')) {
if ((new Stringable($line))->contains(' Accepted')) {
$requestPort = static::getRequestPortFromLine($line);

$this->requestsPool[$requestPort] = [
$this->getDateFromLine($line),
$this->requestsPool[$requestPort][1] ?? false,
microtime(true),
];
} elseif (str($line)->contains([' [200]: GET '])) {
} elseif ((new Stringable($line))->contains([' [200]: GET '])) {
$requestPort = static::getRequestPortFromLine($line);

$this->requestsPool[$requestPort][1] = trim(explode('[200]: GET', $line)[1]);
} elseif (str($line)->contains('URI:')) {
} elseif ((new Stringable($line))->contains('URI:')) {
$requestPort = static::getRequestPortFromLine($line);

$this->requestsPool[$requestPort][1] = trim(explode('URI: ', $line)[1]);
} elseif (str($line)->contains(' Closing')) {
} elseif ((new Stringable($line))->contains(' Closing')) {
$requestPort = static::getRequestPortFromLine($line);

if (empty($this->requestsPool[$requestPort])) {
Expand Down Expand Up @@ -338,11 +339,11 @@ protected function flushOutputBuffer()

$this->output->write(' '.str_repeat('<fg=gray>.</>', $dots));
$this->output->writeln(" <fg=gray>~ {$runTime}</>");
} elseif (str($line)->contains(['Closed without sending a request', 'Failed to poll event'])) {
} elseif ((new Stringable($line))->contains(['Closed without sending a request', 'Failed to poll event'])) {
// ...
} elseif (! empty($line)) {
if (str($line)->startsWith('[')) {
$line = str($line)->after('] ');
if ((new Stringable($line))->startsWith('[')) {
$line = (new Stringable($line))->after('] ');
}

$this->output->writeln(" <fg=gray>$line</>");
Expand Down
7 changes: 4 additions & 3 deletions src/Illuminate/Foundation/Console/ViewMakeCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Input\InputOption;

Expand Down Expand Up @@ -184,15 +185,15 @@ protected function testClassFullyQualifiedName()
$name = Str::of(Str::lower($this->getNameInput()))->replace('.'.$this->option('extension'), '');

$namespacedName = Str::of(
Str::of($name)
(new Stringable($name))
->replace('/', ' ')
->explode(' ')
->map(fn ($part) => Str::of($part)->ucfirst())
->map(fn ($part) => (new Stringable($part))->ucfirst())
->implode('\\')
)
->replace(['-', '_'], ' ')
->explode(' ')
->map(fn ($part) => Str::of($part)->ucfirst())
->map(fn ($part) => (new Stringable($part))->ucfirst())
->implode('');

return 'Tests\\Feature\\View\\'.$namespacedName;
Expand Down
3 changes: 2 additions & 1 deletion src/Illuminate/Foundation/Exceptions/Handler.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Lottery;
use Illuminate\Support\Reflector;
use Illuminate\Support\Str;
use Illuminate\Support\Traits\ReflectsClosures;
use Illuminate\Support\ViewErrorBag;
use Illuminate\Validation\ValidationException;
Expand Down Expand Up @@ -1007,7 +1008,7 @@ protected function convertExceptionToArray(Throwable $e)
public function renderForConsole($output, Throwable $e)
{
if ($e instanceof CommandNotFoundException) {
$message = str($e->getMessage())->explode('.')->first();
$message = Str::of($e->getMessage())->explode('.')->first();

if (! empty($alternatives = $e->getAlternatives())) {
$message .= '. Did you mean one of these?';
Expand Down
Loading

0 comments on commit 0c0ec9f

Please sign in to comment.