ronantakizawa/codereview-bench huggingface dataset:
Repository: symfony/symfony
File: src/Symfony/Component/Mailer/Bridge/Resend/Transport/ResendApiTransport.php (PHP)

Code before:
        }

        return $attachments;
    }

    private function prepareHeadersAndTags(Headers $headers): array
    {
        $headersAndTags = [];
        $headersToBypass = ['from', 'to', 'cc', 'bcc', 'subject', 'reply_to'];
        foreach ($headers->all() as $name => $header) {
            if (\in_array($name, $headersToBypass, true)) {
                continue;
            }

            if ($header instanceof TagHeader) {
                $headersAndTags['tags'][] = [$header->getName() => $header->getValue()];

                continue;
            }

            if ('templateid' === $name) {
                $headersAndTags['template']['id'] = $header->getValue();
            }

            if ('variables' === $name) {
                $headersAndTags['template'][$header->getName()] = $header->getParameters();

                continue;
            }

            $headersAndTags['headers'][$header->getName()] = $header->getBodyAsString();
        }

        return $headersAndTags;
    }

    private function formatAddress(Address $address): string
    {
        $formattedAddress = $address->getEncodedAddress();

        if ($address->getName()) {
            $formattedAddress = $address->getName().' <'.$formattedAddress.'>';
        }

        return $formattedAddress;
    }

    private function getEndpoint(): ?string
    {
        return ($this->host ?: 'api.resend.com').($this->port ? ':'.$this->port : '');
    }

Review comment (suggestion):
```suggestion
            if ('params' === $name) {
                $headersAndTags['template']['variables'] = $header->getParameters();
```

Code after:
        }

        return $attachments;
    }

    private function prepareHeadersAndTags(Headers $headers): array
    {
        $headersAndTags = [];
        $headersToBypass = ['from', 'to', 'cc', 'bcc', 'subject', 'reply_to'];
        foreach ($headers->all() as $name => $header) {
            if (\in_array($name, $headersToBypass, true)) {
                continue;
            }

            if ($header instanceof TagHeader) {
                $headersAndTags['tags'][] = [$header->getName() => $header->getValue()];

                continue;
            }

            $headersAndTags['headers'][$header->getName()] = $header->getBodyAsString();
        }

        return $headersAndTags;
    }

    private function formatAddress(Address $address): string
    {
        $formattedAddress = $address->getEncodedAddress();

        if ($address->getName()) {
            $formattedAddress = $address->getName().' <'.$formattedAddress.'>';
        }

        return $formattedAddress;
    }

    private function getEndpoint(): ?string
    {
        return ($this->host ?: 'api.resend.com').($this->port ? ':'.$this->port : '');
    }
}
Repository: symfony/symfony
File: src/Symfony/Component/Mailer/Bridge/Resend/Transport/ResendApiTransport.php (PHP)

Code before:
        return $attachments;
    }

    private function prepareHeadersAndTags(Headers $headers): array
    {
        $headersAndTags = [];
        $headersToBypass = ['from', 'to', 'cc', 'bcc', 'subject', 'reply_to'];
        foreach ($headers->all() as $name => $header) {
            if (\in_array($name, $headersToBypass, true)) {
                continue;
            }

            if ($header instanceof TagHeader) {
                $headersAndTags['tags'][] = [$header->getName() => $header->getValue()];

                continue;
            }

            if ('templateid' === $name) {
                $headersAndTags['template']['id'] = $header->getValue();

                continue;
            }

            if ('params' === $name) {
                trigger_deprecation('symfony/resend-mailer', '7.3', 'Usage of params is deprecated use variables instead.');
                $headersAndTags['template']['variables'] = $header->getParameters();

                continue;
            }

            if ('variables' === $name) {
                $headersAndTags['template'][$header->getName()] = $header->getParameters();

                continue;
            }

            $headersAndTags['headers'][$header->getName()] = $header->getBodyAsString();
        }

        return $headersAndTags;
    }

    private function formatAddress(Address $address): string
    {
        $formattedAddress = $address->getEncodedAddress();

        if ($address->getName()) {
            $formattedAddress = $address->getName().' <'.$formattedAddress.'>';
        }


Review comment (suggestion):
```suggestion
                trigger_deprecation('symfony/resend-mailer', '7.3', 'The "params" header name is deprecated, use the "variables" header name instead');
```

Code after:
        return $attachments;
    }

    private function prepareHeadersAndTags(Headers $headers): array
    {
        $headersAndTags = [];
        $headersToBypass = ['from', 'to', 'cc', 'bcc', 'subject', 'reply_to'];
        foreach ($headers->all() as $name => $header) {
            if (\in_array($name, $headersToBypass, true)) {
                continue;
            }

            if ($header instanceof TagHeader) {
                $headersAndTags['tags'][] = [$header->getName() => $header->getValue()];

                continue;
            }

            $headersAndTags['headers'][$header->getName()] = $header->getBodyAsString();
        }

        return $headersAndTags;
    }

    private function formatAddress(Address $address): string
    {
        $formattedAddress = $address->getEncodedAddress();

        if ($address->getName()) {
            $formattedAddress = $address->getName().' <'.$formattedAddress.'>';
        }

        return $formattedAddress;
    }

    private function getEndpoint(): ?string
    {
        return ($this->host ?: 'api.resend.com').($this->port ? ':'.$this->port : '');
    }
}
Repository: symfony/symfony
File: src/Symfony/Component/Security/Http/EventListener/IsGrantedAttributeListener.php (PHP)

Code before:
                $e->setSubject($subject);
                $e->setAccessDecision($accessDecision);

                throw $e;
            }
        }
    }

    public static function getSubscribedEvents(): array
    {
        return [KernelEvents::CONTROLLER_ARGUMENTS => ['onKernelControllerArguments', 20]];
    }

    private function getIsGrantedSubject(string|Expression|\Closure $subjectRef, Request $request, array $arguments, ?object $thisScope): mixed
    {
        if ($subjectRef instanceof \Closure) {
            return $subjectRef($arguments, $request, $thisScope);
        }

        if ($subjectRef instanceof Expression) {
            $this->expressionLanguage ??= new ExpressionLanguage();

            return $this->expressionLanguage->evaluate($subjectRef, [
                'request' => $request,
                'args' => $arguments,
            ] + ($thisScope ? ['this' => $thisScope] : []));
        }

        if (!\array_key_exists($subjectRef, $arguments)) {
            throw new RuntimeException(\sprintf('Could not find the subject "%s" for the #[IsGranted] attribute. Try adding a "$%s" argument to your controller method.', $subjectRef, $subjectRef));
        }

        return $arguments[$subjectRef];
    }
}


Review comment (suggestion):
```suggestion
                'this' => $thisScope,
            ]);
```

Code after:
                }

                $e = new AccessDeniedException($message, code: $attribute->exceptionCode ?? 403);
                $e->setAttributes([$attribute->attribute]);
                $e->setSubject($subject);
                $e->setAccessDecision($accessDecision);

                throw $e;
            }
        }
    }

    public static function getSubscribedEvents(): array
    {
        return [KernelEvents::CONTROLLER_ARGUMENTS => ['onKernelControllerArguments', 20]];
    }

    private function getIsGrantedSubject(string|Expression|\Closure $subjectRef, Request $request, array $arguments, ?object $controller): mixed
    {
        if ($subjectRef instanceof \Closure) {
            return $subjectRef($arguments, $request, $controller);
        }

        if ($subjectRef instanceof Expression) {
            $this->expressionLanguage ??= new ExpressionLanguage();

            return $this->expressionLanguage->evaluate($subjectRef, [
                'request' => $request,
                'args' => $arguments,
                'this' => $controller,
            ]);
        }

        if (!\array_key_exists($subjectRef, $arguments)) {
            throw new RuntimeException(\sprintf('Could not find the subject "%s" for the #[IsGranted] attribute. Try adding a "$%s" argument to your controller method.', $subjectRef, $subjectRef));
        }

        return $arguments[$subjectRef];
    }
}
Repository: symfony/symfony
File: src/Symfony/Component/Messenger/Bridge/Doctrine/Transport/PostgreSqlConnection.php (PHP)

Code before:
            $wrappedConnection = $this->driverConnection;
            while (method_exists($wrappedConnection, 'getWrappedConnection')) {
                $wrappedConnection = $wrappedConnection->getWrappedConnection();
            }
        }

        $notification = \PHP_VERSION_ID >= 80500
            ? $wrappedConnection->getNotify(\PDO::FETCH_ASSOC, $this->configuration['get_notify_timeout'])
            : $wrappedConnection->pgsqlGetNotify(\PDO::FETCH_ASSOC, $this->configuration['get_notify_timeout']);
        if (
            // no notifications, or for another table or queue
            (false === $notification || $notification['message'] !== $this->configuration['table_name'] || $notification['payload'] !== $this->configuration['queue_name'])
            // delayed messages
            && (microtime(true) * 1000 - $this->queueEmptiedAt < $this->configuration['check_delayed_interval'])
        ) {
            usleep(1000);

            return null;
        }

        return parent::get();
    }

    private function unlisten(): void
    {
        if (false === $this->listening) {
            return;
        }

        $this->executeStatement(\sprintf('UNLISTEN "%s"', $this->configuration['table_name']));
        $this->listening = false;
    }
}


Review comment (suggestion):
```suggestion
        if (true === (false === $this->listening)) {
```

or maybe just this?

```suggestion
        if (!$this->listening) {
```

(kidding 😜 )

Code after:
            $wrappedConnection = $this->driverConnection;
            while (method_exists($wrappedConnection, 'getWrappedConnection')) {
                $wrappedConnection = $wrappedConnection->getWrappedConnection();
            }
        }

        $notification = \PHP_VERSION_ID >= 80500
            ? $wrappedConnection->getNotify(\PDO::FETCH_ASSOC, $this->configuration['get_notify_timeout'])
            : $wrappedConnection->pgsqlGetNotify(\PDO::FETCH_ASSOC, $this->configuration['get_notify_timeout']);
        if (
            // no notifications, or for another table or queue
            (false === $notification || $notification['message'] !== $this->configuration['table_name'] || $notification['payload'] !== $this->configuration['queue_name'])
            // delayed messages
            && (microtime(true) * 1000 - $this->queueEmptiedAt < $this->configuration['check_delayed_interval'])
        ) {
            usleep(1000);

            return null;
        }

        return parent::get();
    }

    private function unlisten(): void
    {
        if (!$this->listening) {
            return;
        }

        $this->executeStatement(\sprintf('UNLISTEN "%s"', $this->configuration['table_name']));
        $this->listening = false;
    }
}
Repository: symfony/symfony
File: src/Symfony/Component/Console/Exception/RunCommandFailedException.php (PHP)

Code before:
<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Exception;

use Symfony\Component\Console\Messenger\RunCommandContext;

/**
 * @author Kevin Bond <kevinbond@gmail.com>
 */
final class RunCommandFailedException extends RuntimeException
{
    public function __construct(\Throwable|string $exception, public readonly RunCommandContext $context)
    {
        parent::__construct(
            $exception instanceof \Throwable ? $exception->getMessage() : $exception,
            $exception instanceof \Throwable && is_int($exception->getCode()) ? $exception->getCode() : 0,
            $exception instanceof \Throwable ? $exception : null,
        );
    }
}


Review comment (suggestion):
```suggestion
            $exception instanceof \Throwable && \is_int($exception->getCode()) ? $exception->getCode() : 0,
```

Code after:
<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Exception;

use Symfony\Component\Console\Messenger\RunCommandContext;

/**
 * @author Kevin Bond <kevinbond@gmail.com>
 */
final class RunCommandFailedException extends RuntimeException
{
    public function __construct(\Throwable|string $exception, public readonly RunCommandContext $context)
    {
        parent::__construct(
            $exception instanceof \Throwable ? $exception->getMessage() : $exception,
            $exception instanceof \Throwable && \is_int($exception->getCode()) ? $exception->getCode() : 0,
            $exception instanceof \Throwable ? $exception : null,
        );
    }
}
Repository: symfony/symfony
File: src/Symfony/Component/Lock/Store/SemaphoreStore.php (PHP)

Code before:

    public function __construct()
    {
        if (!static::isSupported()) {
            throw new InvalidArgumentException('Semaphore extension (sysvsem) is required.');
        }
    }

    public function save(Key $key): void
    {
        $this->lock($key, false);
    }

    public function waitAndSave(Key $key): void
    {
        $this->lock($key, true);
    }

    private function lock(Key $key, bool $blocking): void
    {
        if ($key->hasState(__CLASS__)) {
            return;
        }

        $keyId = unpack('i', hash('xxh128', $key, true))[1];
        $resource = @sem_get($keyId);
        $acquired = $resource && @sem_acquire($resource, !$blocking);

        while ($blocking && !$acquired) {
            $resource = @sem_get($keyId);
            $acquired = $resource && @sem_acquire($resource);
        }

        if (!$acquired) {
            throw new LockConflictedException();
        }

        $key->setState(__CLASS__, $resource);
        $key->markUnserializable();
    }

    public function delete(Key $key): void
    {
        // The lock is maybe not acquired.
        if (!$key->hasState(__CLASS__)) {
            return;
        }

        $resource = $key->getState(__CLASS__);

        sem_remove($resource);

Review comment (suggestion):
reducing to xxh64 because the keyspace on linux is 32b wide, so 128b was way too wide.
Also: 64b provides better x86/x64 portability than 32b, thus the choice vs xxh32.

Code after:

    public function __construct(
        private readonly string $projectId = '',
    ) {
        if (!static::isSupported()) {
            throw new InvalidArgumentException('Semaphore extension (sysvsem) is required.');
        }
    }

    public function save(Key $key): void
    {
        $this->lock($key, false);
    }

    public function waitAndSave(Key $key): void
    {
        $this->lock($key, true);
    }

    private function lock(Key $key, bool $blocking): void
    {
        if ($key->hasState(__CLASS__)) {
            return;
        }

        $keyId = unpack('i', hash('xxh64', $this->projectId.$key, true))[1];
        $resource = @sem_get($keyId);
        $acquired = $resource && @sem_acquire($resource, !$blocking);

        while ($blocking && !$acquired) {
            $resource = @sem_get($keyId);
            $acquired = $resource && @sem_acquire($resource);
        }

        if (!$acquired) {
            throw new LockConflictedException();
        }

        $key->setState(__CLASS__, $resource);
        $key->markUnserializable();
    }

    public function delete(Key $key): void
    {
        // The lock is maybe not acquired.
        if (!$key->hasState(__CLASS__)) {
            return;
        }

        $resource = $key->getState(__CLASS__);
Repository: symfony/symfony
File: src/Symfony/Component/JsonStreamer/Mapping/Read/DateTimeTypePropertyMetadataLoader.php (PHP)

Code before:
<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\JsonStreamer\Mapping\Read;

use Symfony\Component\JsonStreamer\Exception\InvalidArgumentException;
use Symfony\Component\JsonStreamer\Mapping\PropertyMetadataLoaderInterface;
use Symfony\Component\JsonStreamer\ValueTransformer\StringToDateTimeValueTransformer;
use Symfony\Component\TypeInfo\Type\ObjectType;

/**
 * Transforms string to DateTimeInterface for properties with DateTimeInterface type.
 *
 * @author Mathias Arlaud <mathias.arlaud@gmail.com>
 *
 * @internal
 */
final class DateTimeTypePropertyMetadataLoader implements PropertyMetadataLoaderInterface
{
    public function __construct(
        private PropertyMetadataLoaderInterface $decorated,
    ) {
    }

    public function load(string $className, array $options = [], array $context = []): array
    {
        $result = $this->decorated->load($className, $options, $context);

        foreach ($result as &$metadata) {
            $type = $metadata->getType();

            if ($type instanceof ObjectType && is_a($type->getClassName(), \DateTimeInterface::class, true)) {
                if (is_a($type->getClassName(), \DateTime::class, true)) {
                    throw new InvalidArgumentException('The "DateTime" class is not supported. Use "DateTimeImmutable" instead.');
                }

                $metadata = $metadata
                    ->withType(StringToDateTimeValueTransformer::getStreamValueType())
                    ->withAdditionalValueTransformer('json_streamer.value_transformer.string_to_date_time');
            }
        }

        return $result;

Review comment (suggestion):
Removing the class is a BC break that will impact existing FrameworkBundle releases (I already reported in the past that marking the class as `@internal` was flawed because that class was meant to be instantiated outside the component). You need to deprecate the class instead.

Code after:
<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\JsonStreamer\Mapping\Read;

use Symfony\Component\JsonStreamer\Mapping\PropertyMetadataLoaderInterface;

/**
 * @author Mathias Arlaud <mathias.arlaud@gmail.com>
 *
 * @internal
 */
final class DateTimeTypePropertyMetadataLoader implements PropertyMetadataLoaderInterface
{
    public function __construct(
        private PropertyMetadataLoaderInterface $decorated,
    ) {
    }

    public function load(string $className, array $options = [], array $context = []): array
    {
        return $this->decorated->load($className, $options, $context);
    }
}
Repository: symfony/symfony
File: src/Symfony/Component/Cache/DependencyInjection/CachePoolPass.php (PHP)

Code before:
    /**
     * @internal
     */
    public static function getServiceProvider(ContainerBuilder $container, string $name): string
    {
        $container->resolveEnvPlaceholders($name, null, $usedEnvs);

        if ($usedEnvs || preg_match('#^[a-z]++:#', $name)) {
            $dsn = $name;

            if (!$container->hasDefinition($name = '.cache_connection.'.ContainerBuilder::hash($dsn))) {
                $definition = new Definition(AbstractAdapter::class);
                $definition->setFactory([AbstractAdapter::class, 'createConnection']);
                $definition->setArguments([$dsn, ['lazy' => true]]);
                $container->setDefinition($name, $definition);
            }
        }

        return $name;
    }

    private function findDefaultMarshallerArgumentIndex(Definition $definition): ?int
    {
        foreach ($definition->getArguments() as $index => $argument) {
            if ($argument instanceof Reference && 'cache.default_marshaller' === (string) $argument) {
                return \is_int($index) ? $index : (int) substr($index, 6); // handle 'index_N' format
            }
        }

        return null;
    }
}


Review comment (suggestion):
```suggestion
                return \is_int($index) ? $index : (str_starts_with($index, 'index_') ? (int) substr($index, 6) : $index);
```

Code after:
     */
    public static function getServiceProvider(ContainerBuilder $container, string $name): string
    {
        $container->resolveEnvPlaceholders($name, null, $usedEnvs);

        if ($usedEnvs || preg_match('#^[a-z]++:#', $name)) {
            $dsn = $name;

            if (!$container->hasDefinition($name = '.cache_connection.'.ContainerBuilder::hash($dsn))) {
                $definition = new Definition(AbstractAdapter::class);
                $definition->setFactory([AbstractAdapter::class, 'createConnection']);
                $definition->setArguments([$dsn, ['lazy' => true]]);
                $container->setDefinition($name, $definition);
            }
        }

        return $name;
    }

    private function findDefaultMarshallerArgumentIndex(Definition $definition): int|string|null
    {
        foreach ($definition->getArguments() as $index => $argument) {
            if ($argument instanceof Reference && 'cache.default_marshaller' === (string) $argument) {
                return \is_int($index) ? $index : (str_starts_with($index, 'index_') ? (int) substr($index, 6) : $index);
            }
        }

        return null;
    }
}