ronantakizawa/codereview-bench huggingface dataset:
Repository: laravel/framework
File: src/Illuminate/Validation/Validator.php (PHP)

Code before:
     */
    public function setValue($attribute, $value)
    {
        Arr::set($this->data, $attribute, $value);
    }

    /**
     * Get the validation rules.
     *
     * @return array
     */
    public function getRules()
    {
        return $this->rules;
    }

    /**
     * Get the validation rules with key placeholders removed.
     *
     * @return array
     */
    public function getRulesWithoutPlaceholders()
    {
        return (new Collection($this->rules))
            ->mapWithKeys(fn ($value, $key) => [
                static::encodeAttributeWithPlaceholder($key) => $value,
            ])
            ->all();
    }

    /**
     * Set the validation rules.
     *
     * @param  array  $rules
     * @return $this
     */
    public function setRules(array $rules)
    {
        $rules = (new Collection($rules))
            ->mapWithKeys(function ($value, $key) {
                return [static::encodeAttributeWithPlaceholder($key) => $value];
            })
            ->toArray();

        $this->initialRules = $rules;

        $this->rules = [];

        $this->addRules($rules);

        return $this;

Review comment (suggestion):
```suggestion
                static::decodeAttributeWithPlaceholder($key) => $value,
```

Code after:
     */
    public function setValue($attribute, $value)
    {
        Arr::set($this->data, $attribute, $value);
    }

    /**
     * Get the validation rules.
     *
     * @return array
     */
    public function getRules()
    {
        return $this->rules;
    }

    /**
     * Get the validation rules with key placeholders removed.
     *
     * @return array
     */
    public function getRulesWithoutPlaceholders()
    {
        return (new Collection($this->rules))
            ->mapWithKeys(fn ($value, $key) => [
                static::decodeAttributeWithPlaceholder($key) => $value,
            ])
            ->all();
    }

    /**
     * Set the validation rules.
     *
     * @param  array  $rules
     * @return $this
     */
    public function setRules(array $rules)
    {
        $rules = (new Collection($rules))
            ->mapWithKeys(function ($value, $key) {
                return [static::encodeAttributeWithPlaceholder($key) => $value];
            })
            ->toArray();

        $this->initialRules = $rules;

        $this->rules = [];

        $this->addRules($rules);

        return $this;
Repository: laravel/framework
File: src/Illuminate/View/Compilers/Concerns/CompilesIncludes.php (PHP)

Code before:
    }

    /**
     * Compile the include-first statements into valid PHP.
     *
     * @param  string  $expression
     * @return string
     */
    protected function compileIncludeFirst($expression)
    {
        $expression = $this->stripParentheses($expression);

        return "<?php echo \$__env->first({$expression}, array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>";
    }

    /**
     * Compile the include-scoped statements into valid PHP.
     *
     * @param  string  $expression
     * @return string
     */
    protected function compileIncludeScoped($expression)
    {
        $expression = $this->stripParentheses($expression);

        return "<?php echo \$__env->make({$expression}, [])->render(); ?>";
    }
}


Review comment (refactor):
You can simplify it to keep just the `$expression`, as both `$data` and `$mergeData` have default values.

```php
return "<?php echo \$__env->make({$expression})->render(); ?>";
```

https://github.com/laravel/framework/blob/90a84ca8d044480096ab9ee38af77285a12d0a9d/src/Illuminate/View/Factory.php#L148

Code after:
    }

    /**
     * Compile the include-first statements into valid PHP.
     *
     * @param  string  $expression
     * @return string
     */
    protected function compileIncludeFirst($expression)
    {
        $expression = $this->stripParentheses($expression);

        return "<?php echo \$__env->first({$expression}, array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>";
    }

    /**
     * Compile the include-isolated statements into valid PHP.
     *
     * @param  string  $expression
     * @return string
     */
    protected function compileIncludeIsolated($expression)
    {
        $expression = $this->stripParentheses($expression);

        return "<?php echo \$__env->make({$expression})->render(); ?>";
    }
}
Repository: laravel/framework
File: src/Illuminate/Collections/Collection.php (PHP)

Code before:
     */
    public function isEmpty()
    {
        return empty($this->items);
    }

    /**
     * Determine if the collection contains exactly one item. If a callback is provided, determine if exactly one item matches the condition.
     *
     * @param  (callable(TValue, TKey): bool)|null  $callback
     * @return bool
     */
    public function containsOneItem(?callable $callback = null): bool
    {
        if ($callback) {
            return $this->filter($callback)->count() === 1;
        }

        return $this->count() === 1;
    }

    /**
     * Determine if the collection contains multiple items. If a callback is provided, determine if multiple items match the condition.
     *
     * @param  (callable(TValue, TKey): bool)|null  $callback
     * @return bool
     */
    public function containsManyItems(?callable $callback = null): bool
    {
        if ($callback) {
            return $this->filter($callback)->count() > 1;
        }

        return $this->count() > 1;
    }

    /**
     * Join all items from the collection using a string. The final items can use a separate glue string.
     *
     * @param  string  $glue
     * @param  string  $finalGlue
     * @return TValue|string
     */
    public function join($glue, $finalGlue = '')
    {
        if ($finalGlue === '') {
            return $this->implode($glue);
        }

        $count = $this->count();


Review comment (suggestion):
I wonder if it would make sense to add an assertion here and in the two corresponding methods

```suggestion
     * @return bool
     * @phpstan-assert-if-true non-empty-array<TKey, TValue> $this->items
```

Code after:
     */
    public function isEmpty()
    {
        return empty($this->items);
    }

    /**
     * Determine if the collection contains exactly one item. If a callback is provided, determine if exactly one item matches the condition.
     *
     * @param  (callable(TValue, TKey): bool)|null  $callback
     * @return bool
     */
    public function containsOneItem(?callable $callback = null): bool
    {
        if ($callback) {
            return $this->filter($callback)->count() === 1;
        }

        return $this->count() === 1;
    }

    /**
     * Determine if the collection contains multiple items. If a callback is provided, determine if multiple items match the condition.
     *
     * @param  (callable(TValue, TKey): bool)|null  $callback
     * @return bool
     */
    public function containsManyItems(?callable $callback = null): bool
    {
        if (! $callback) {
            return $this->count() > 1;
        }

        $count = 0;

        foreach ($this as $key => $item) {
            if ($callback($item, $key)) {
                $count++;
            }

            if ($count > 1) {
                return true;
            }
        }

        return false;
    }

    /**
     * Join all items from the collection using a string. The final items can use a separate glue string.
     *
Repository: laravel/framework
File: src/Illuminate/Database/Connection.php (PHP)

Code before:
        $name = $this->getName().($this->readWriteType ? '::'.$this->readWriteType : '');

        return empty($name) ? null : $name;
    }

    /**
     * Get an option from the configuration options.
     *
     * @param  string|null  $option
     * @return mixed
     */
    public function getConfig($option = null)
    {
        return Arr::get($this->config, $option);
    }

    /**
     * Get the basic connection information as an array for debugging.
     *
     * @return array
     */
    protected function getConnectionDetails()
    {
        $config = $this->latestPdoTypeRetrieved === 'read'
            ? $this->readPdoConfig
            : $this->config;

        return [
            'driver' => $this->getDriverName(),
            'name' => $this->getNameWithReadWriteType(),
            'host' => $config['host'] ?? null,
            'port' => $config['port'] ?? null,
            'database' => $config['database'] ?? null,
            'unix_socket' => $config['unix_socket'] ?? null,
        ];
    }

    /**
     * Get the PDO driver name.
     *
     * @return string
     */
    public function getDriverName()
    {
        return $this->getConfig('driver');
    }

    /**
     * Get a human-readable name for the given connection driver.
     *
     * @return string

Review comment (suggestion):
I think you will want to use the `latestReadWriteTypeUsed` method here.


```suggestion
        $config = $this->latestReadWriteTypeUsed() === 'read'
            ? $this->readPdoConfig
            : $this->config;
```

I believe this should correctly support the following:

```php
DB::connection('sqlite::read')->statement('select 1');
```

Code after:
        $name = $this->getName().($this->readWriteType ? '::'.$this->readWriteType : '');

        return empty($name) ? null : $name;
    }

    /**
     * Get an option from the configuration options.
     *
     * @param  string|null  $option
     * @return mixed
     */
    public function getConfig($option = null)
    {
        return Arr::get($this->config, $option);
    }

    /**
     * Get the basic connection information as an array for debugging.
     *
     * @return array
     */
    protected function getConnectionDetails()
    {
        $config = $this->latestReadWriteTypeUsed() === 'read'
            ? $this->readPdoConfig
            : $this->config;

        return [
            'driver' => $this->getDriverName(),
            'name' => $this->getNameWithReadWriteType(),
            'host' => $config['host'] ?? null,
            'port' => $config['port'] ?? null,
            'database' => $config['database'] ?? null,
            'unix_socket' => $config['unix_socket'] ?? null,
        ];
    }

    /**
     * Get the PDO driver name.
     *
     * @return string
     */
    public function getDriverName()
    {
        return $this->getConfig('driver');
    }

    /**
     * Get a human-readable name for the given connection driver.
     *
     * @return string
Repository: laravel/framework
File: src/Illuminate/Database/Query/Builder.php (PHP)

Code before:
     * @param  string|null  $as
     * @return $this
     */
    public function selectVectorDistance($column, $vector, $as = null)
    {
        if (is_string($vector)) {
            Str::of($vector)->toEmbeddings();
        }

        $this->addBinding(
            json_encode(
                $vector instanceof Arrayable
                    ? $vector->toArray()
                    : $vector,
                flags: JSON_THROW_ON_ERROR
            ),
            'select',
        );

        $as = $this->getGrammar()->wrap($as ?? $column.'_distance');

        return $this->addSelect(
            new Expression("({$this->getGrammar()->wrap($column)} <=> ?) as {$as}")
        );
    }

    /**
     * Force the query to only return distinct results.
     *
     * @return $this
     */
    public function distinct()
    {
        $columns = func_get_args();

        if (count($columns) > 0) {
            $this->distinct = is_array($columns[0]) || is_bool($columns[0]) ? $columns[0] : $columns;
        } else {
            $this->distinct = true;
        }

        return $this;
    }

    /**
     * Set the table which the query is targeting.
     *
     * @param  \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder<*>|\Illuminate\Contracts\Database\Query\Expression|string  $table
     * @param  string|null  $as
     * @return $this
     */

Review comment (suggestion):
MySQL has vector functions too. This implementation only works for MySQL. So there should be a check whether PG is used and throw otherwise.

Code after:
     * @param  \Illuminate\Support\Collection<int, float>|\Illuminate\Contracts\Support\Arrayable|array<int, float>|string  $vector
     * @param  string|null  $as
     * @return $this
     */
    public function selectVectorDistance($column, $vector, $as = null)
    {
        $this->ensureConnectionSupportsVectors();

        if (is_string($vector)) {
            Str::of($vector)->toEmbeddings();
        }

        $this->addBinding(
            json_encode(
                $vector instanceof Arrayable
                    ? $vector->toArray()
                    : $vector,
                flags: JSON_THROW_ON_ERROR
            ),
            'select',
        );

        $as = $this->getGrammar()->wrap($as ?? $column.'_distance');

        return $this->addSelect(
            new Expression("({$this->getGrammar()->wrap($column)} <=> ?) as {$as}")
        );
    }

    /**
     * Force the query to only return distinct results.
     *
     * @return $this
     */
    public function distinct()
    {
        $columns = func_get_args();

        if (count($columns) > 0) {
            $this->distinct = is_array($columns[0]) || is_bool($columns[0]) ? $columns[0] : $columns;
        } else {
            $this->distinct = true;
        }

        return $this;
    }

    /**
     * Set the table which the query is targeting.
     *
     * @param  \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder<*>|\Illuminate\Contracts\Database\Query\Expression|string  $table
Repository: laravel/framework
File: src/Illuminate/Support/Str.php (PHP)

Code before:
     * @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<string>  $search
     * @param  string|iterable<string>  $subject
     * @param  bool  $caseSensitive
     * @return string
     */
    public static function remove($search, $subject, $caseSensitive = true)
    {
        if ($search instanceof Traversable) {
            $search = Arr::from($search);
        }

        return $caseSensitive

Review comment (suggestion):
```php
* @return ($subject is array ? string[]|null : string|null)
```

Code after:
     * @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  string|string[]  $pattern
     * @param  (\Closure(array): string)|string[]|string  $replace
     * @param  array|string[]  $subject
     * @param  int  $limit
     * @return ($subject is array ? string|null : 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<string>  $search
     * @param  string|iterable<string>  $subject
     * @param  bool  $caseSensitive
     * @return string
     */
    public static function remove($search, $subject, $caseSensitive = true)
    {
        if ($search instanceof Traversable) {
            $search = Arr::from($search);
        }

        return $caseSensitive
Repository: laravel/framework
File: src/Illuminate/Http/Middleware/HandleCors.php (PHP)

Code before:
            return $next($request);
        }

        $this->cors->setOptions($this->container['config']->get('cors', []));

        if ($this->cors->isPreflightRequest($request)) {
            $response = $this->cors->handlePreflightRequest($request);

            $this->cors->varyHeader($response, 'Access-Control-Request-Method');

            return $response;
        }

        $response = $next($request);

        if ($request->getMethod() === 'OPTIONS') {
            $this->cors->varyHeader($response, 'Access-Control-Request-Method');
        }

        return $this->cors->addActualRequestHeaders($response, $request);
    }

    /**
     * Register a callback that instructs the middleware to be skipped.
     *
     * @param  \Closure  $callback
     * @return void
     */
    public static function skipWhen(Closure $callback)
    {
        static::$skipCallbacks[] = $callback;
    }

    /**
     * Get the path from the configuration to determine if the CORS service should run.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
    protected function hasMatchingPath(Request $request): bool
    {
        $paths = $this->getPathsByHost($request->getHost());

        foreach ($paths as $path) {
            if ($path !== '/') {
                $path = trim($path, '/');
            }

            if ($request->fullUrlIs($path) || $request->is($path)) {
                return true;
            }

Review comment (suggestion):
You could type arguments and return type here

```suggestion
     * @param  \Closure(\Illuminate\Http\Request): bool  $callback
```

Code after:
            return $next($request);
        }

        $this->cors->setOptions($this->container['config']->get('cors', []));

        if ($this->cors->isPreflightRequest($request)) {
            $response = $this->cors->handlePreflightRequest($request);

            $this->cors->varyHeader($response, 'Access-Control-Request-Method');

            return $response;
        }

        $response = $next($request);

        if ($request->getMethod() === 'OPTIONS') {
            $this->cors->varyHeader($response, 'Access-Control-Request-Method');
        }

        return $this->cors->addActualRequestHeaders($response, $request);
    }

    /**
     * Get the path from the configuration to determine if the CORS service should run.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
    protected function hasMatchingPath(Request $request): bool
    {
        $paths = $this->getPathsByHost($request->getHost());

        foreach ($paths as $path) {
            if ($path !== '/') {
                $path = trim($path, '/');
            }

            if ($request->fullUrlIs($path) || $request->is($path)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Get the CORS paths for the given host.
     *
     * @param  string  $host
     * @return array
     */
Repository: laravel/framework
File: src/Illuminate/Http/Middleware/HandleCors.php (PHP)

Code before:

use Closure;
use Fruitcake\Cors\CorsService;
use Illuminate\Contracts\Container\Container;
use Illuminate\Http\Request;

class HandleCors
{
    /**
     * The container instance.
     *
     * @var \Illuminate\Contracts\Container\Container
     */
    protected $container;

    /**
     * The CORS service instance.
     *
     * @var \Fruitcake\Cors\CorsService
     */
    protected $cors;

    /**
     * All of the registered skip callbacks.
     *
     * @var array
     */
    protected static $skipCallbacks = [];

    /**
     * Create a new middleware instance.
     *
     * @param  \Illuminate\Contracts\Container\Container  $container
     * @param  \Fruitcake\Cors\CorsService  $cors
     */
    public function __construct(Container $container, CorsService $cors)
    {
        $this->container = $container;
        $this->cors = $cors;
    }

    /**
     * Handle the incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return \Illuminate\Http\Response
     */
    public function handle($request, Closure $next)
    {
        foreach (static::$skipCallbacks as $callback) {

Review comment (suggestion):
You can type the array items:
```suggestion
     * @var array<int, \Closure(\Illuminate\Http\Request): bool>
```
or

```suggestion
     * @var list<\Closure(\Illuminate\Http\Request): bool>
```
or

```suggestion
     * @var (\Closure(\Illuminate\Http\Request): bool)[]
```

Code after:

use Closure;
use Fruitcake\Cors\CorsService;
use Illuminate\Contracts\Container\Container;
use Illuminate\Http\Request;

class HandleCors
{
    /**
     * The container instance.
     *
     * @var \Illuminate\Contracts\Container\Container
     */
    protected $container;

    /**
     * The CORS service instance.
     *
     * @var \Fruitcake\Cors\CorsService
     */
    protected $cors;

    /**
     * All of the registered skip callbacks.
     *
     * @var array<int, \Closure(\Illuminate\Http\Request): bool>
     */
    protected static $skipCallbacks = [];

    /**
     * Create a new middleware instance.
     *
     * @param  \Illuminate\Contracts\Container\Container  $container
     * @param  \Fruitcake\Cors\CorsService  $cors
     */
    public function __construct(Container $container, CorsService $cors)
    {
        $this->container = $container;
        $this->cors = $cors;
    }

    /**
     * Handle the incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return \Illuminate\Http\Response
     */
    public function handle($request, Closure $next)
    {
        foreach (static::$skipCallbacks as $callback) {