Skip to content

Commit

Permalink
Updating Queue code with PHP 8.1 features (#635)
Browse files Browse the repository at this point in the history
Co-authored-by: roxblnfk <roxblnfk@ya.ru>
  • Loading branch information
msmakouz and roxblnfk committed Apr 2, 2022
1 parent 39d7401 commit 040234a
Show file tree
Hide file tree
Showing 13 changed files with 55 additions and 116 deletions.
19 changes: 6 additions & 13 deletions src/Queue/src/Bootloader/QueueBootloader.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,9 @@ final class QueueBootloader extends Bootloader
QueueRegistry::class => [self::class, 'initRegistry'],
];

/** @var ConfiguratorInterface */
private $config;

public function __construct(ConfiguratorInterface $config)
{
$this->config = $config;
public function __construct(
private readonly ConfiguratorInterface $config
) {
}

public function boot(Container $container, EnvironmentInterface $env, AbstractKernel $kernel): void
Expand All @@ -67,7 +64,7 @@ public function boot(Container $container, EnvironmentInterface $env, AbstractKe
public function registerDriverAlias(string $driverClass, string $alias): void
{
$this->config->modify(
'queue',
QueueConfig::CONFIG,
new Append('driverAliases', $alias, $driverClass)
);
}
Expand All @@ -84,18 +81,14 @@ protected function initRegistry(ContainerInterface $container, ContainerRegistry

private function registerJobsSerializer(Container $container): void
{
$container->bindSingleton(SerializerInterface::class, static function () {
return new DefaultSerializer();
});
$container->bindSingleton(SerializerInterface::class, static fn () => new DefaultSerializer());
}

private function registerQueue(Container $container): void
{
$container->bindSingleton(
QueueInterface::class,
static function (QueueManager $manager): QueueInterface {
return $manager->getConnection();
}
static fn (QueueManager $manager): QueueInterface => $manager->getConnection()
);
}

Expand Down
10 changes: 5 additions & 5 deletions src/Queue/src/Config/QueueConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,14 +67,14 @@ public function getConnections(?string $driver = null): array
if (isset($driverAliases[$driver])) {
if (!\is_string($this->config['driverAliases'][$driver])) {
throw new InvalidArgumentException(
sprintf('Driver alias for `%s` value must be a string', $driver)
\sprintf('Driver alias for `%s` value must be a string', $driver)
);
}

$driver = $driverAliases[$driver];
}

return array_filter($connections, static function (array $connection) use ($driverAliases, $driver): bool {
return \array_filter($connections, static function (array $connection) use ($driverAliases, $driver): bool {
if (empty($connection['driver'])) {
return false;
}
Expand All @@ -98,15 +98,15 @@ public function getConnection(string $name): array
}

if (!isset($connections[$name]['driver'])) {
throw new InvalidArgumentException(sprintf('Driver for queue connection `%s` is not defined.', $name));
throw new InvalidArgumentException(\sprintf('Driver for queue connection `%s` is not defined.', $name));
}

$connection = $connections[$name];
$driver = $connection['driver'];

if (!\is_string($driver)) {
throw new InvalidArgumentException(
sprintf('Driver for queue connection `%s` value must be a string', $name)
\sprintf('Driver for queue connection `%s` value must be a string', $name)
);
}

Expand All @@ -116,7 +116,7 @@ public function getConnection(string $name): array

if (!\is_string($connection['driver'])) {
throw new InvalidArgumentException(
sprintf('Driver alias for queue connection `%s` value must be a string', $name)
\sprintf('Driver alias for queue connection `%s` value must be a string', $name)
);
}

Expand Down
22 changes: 9 additions & 13 deletions src/Queue/src/ContainerRegistry.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,19 @@

namespace Spiral\Queue;

use Doctrine\Inflector\Inflector;
use Doctrine\Inflector\Rules\English\InflectorFactory;
use Psr\Container\ContainerInterface;
use Spiral\Core\Exception\Container\ContainerException;
use Spiral\Queue\Exception\JobException;

final class ContainerRegistry implements HandlerRegistryInterface
{
/** @var ContainerInterface */
private $container;
/** @var \Doctrine\Inflector\Inflector */
private $inflector;
private readonly Inflector $inflector;

public function __construct(ContainerInterface $container)
{
$this->container = $container;
public function __construct(
private readonly ContainerInterface $container
) {
$this->inflector = (new InflectorFactory())->build();
}

Expand All @@ -31,19 +29,17 @@ public function getHandler(string $jobType): HandlerInterface
}

if (!$handler instanceof HandlerInterface) {
throw new JobException("Unable to resolve job handler for `{$jobType}`");
throw new JobException(\sprintf('Unable to resolve job handler for `%s`', $jobType));
}

return $handler;
}

private function className(string $jobType): string
{
$names = explode('.', $jobType);
$names = array_map(function (string $value) {
return $this->inflector->classify($value);
}, $names);
$names = \explode('.', $jobType);
$names = \array_map(fn (string $value) => $this->inflector->classify($value), $names);

return implode('\\', $names);
return \implode('\\', $names);
}
}
12 changes: 5 additions & 7 deletions src/Queue/src/Core/QueueInjector.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,9 @@
*/
final class QueueInjector implements InjectorInterface
{
private QueueConnectionProviderInterface $queueManager;

public function __construct(QueueConnectionProviderInterface $queueManager)
{
$this->queueManager = $queueManager;
public function __construct(
private readonly QueueConnectionProviderInterface $queueManager
) {
}

public function createInjection(ReflectionClass $class, string $context = null): QueueInterface
Expand All @@ -32,15 +30,15 @@ public function createInjection(ReflectionClass $class, string $context = null):
// Get Queue by context
try {
$connection = $this->queueManager->getConnection($context);
} catch (InvalidArgumentException $e) {
} catch (InvalidArgumentException) {
// Case when context doesn't match to configured connections
return $this->queueManager->getConnection();
}
}

$this->matchType($class, $context, $connection);
} catch (\Throwable $e) {
throw new ContainerException(sprintf("Can't inject the required queue. %s", $e->getMessage()), 0, $e);
throw new ContainerException(\sprintf("Can't inject the required queue. %s", $e->getMessage()), 0, $e);
}

return $connection;
Expand Down
6 changes: 0 additions & 6 deletions src/Queue/src/DefaultSerializer.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,6 @@
*/
final class DefaultSerializer implements SerializerInterface
{
/**
* {@inheritDoc}
*/
public function serialize(array $payload): string
{
try {
Expand All @@ -23,9 +20,6 @@ public function serialize(array $payload): string
}
}

/**
* {@inheritDoc}
*/
public function deserialize(string $payload): array
{
try {
Expand Down
13 changes: 3 additions & 10 deletions src/Queue/src/Driver/SyncDriver.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,24 +18,17 @@ final class SyncDriver implements QueueInterface
{
use QueueTrait;

/** @var HandlerRegistryInterface */
private $registry;
/** @var FailedJobHandlerInterface */
private $failedJobHandler;

public function __construct(
HandlerRegistryInterface $registry,
FailedJobHandlerInterface $failedJobHandler
private readonly HandlerRegistryInterface $registry,
private readonly FailedJobHandlerInterface $failedJobHandler
) {
$this->registry = $registry;
$this->failedJobHandler = $failedJobHandler;
}

/** @inheritdoc */
public function push(string $name, array $payload = [], OptionsInterface $options = null): string
{
if ($options !== null && $options->getDelay()) {
sleep($options->getDelay());
\sleep($options->getDelay());
}

$id = (string)Uuid::uuid4();
Expand Down
9 changes: 3 additions & 6 deletions src/Queue/src/Failed/LogFailedJobHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,9 @@

final class LogFailedJobHandler implements FailedJobHandlerInterface
{
/** @var SnapshotterInterface */
private $snapshotter;

public function __construct(SnapshotterInterface $snapshotter)
{
$this->snapshotter = $snapshotter;
public function __construct(
private readonly SnapshotterInterface $snapshotter
) {
}

public function handle(string $driver, string $queue, string $job, array $payload, \Throwable $e): void
Expand Down
9 changes: 3 additions & 6 deletions src/Queue/src/Job/CallableJob.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,9 @@

final class CallableJob implements HandlerInterface
{
/** @var InvokerInterface */
private $invoker;

public function __construct(InvokerInterface $invoker)
{
$this->invoker = $invoker;
public function __construct(
private readonly InvokerInterface $invoker
) {
}

public function handle(string $name, string $id, array $payload): void
Expand Down
11 changes: 4 additions & 7 deletions src/Queue/src/Job/ObjectJob.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,9 @@

final class ObjectJob implements HandlerInterface
{
/** @var InvokerInterface */
private $invoker;

public function __construct(InvokerInterface $invoker)
{
$this->invoker = $invoker;
public function __construct(
private readonly InvokerInterface $invoker
) {
}

public function handle(string $name, string $id, array $payload): void
Expand All @@ -24,7 +21,7 @@ public function handle(string $name, string $id, array $payload): void
throw new InvalidArgumentException('Payload `object` key is required.');
}

if (!is_object($payload['object'])) {
if (!\is_object($payload['object'])) {
throw new InvalidArgumentException('Payload `object` key value type should be an object.');
}

Expand Down
16 changes: 4 additions & 12 deletions src/Queue/src/JobHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,22 +14,14 @@ abstract class JobHandler implements HandlerInterface
{
/**
* Default function with method injection.
*
* @var string
*/
protected const HANDLE_FUNCTION = 'invoke';

/** @var InvokerInterface */
protected $invoker;

public function __construct(InvokerInterface $invoker)
{
$this->invoker = $invoker;
public function __construct(
protected InvokerInterface $invoker
) {
}

/**
* @inheritdoc
*/
public function handle(string $name, string $id, array $payload): void
{
try {
Expand All @@ -38,7 +30,7 @@ public function handle(string $name, string $id, array $payload): void
\array_merge(['payload' => $payload, 'id' => $id], $payload)
);
} catch (\Throwable $e) {
$message = \sprintf('[%s] %s', \get_class($this), $e->getMessage());
$message = \sprintf('[%s] %s', $this::class, $e->getMessage());
throw new JobException($message, (int)$e->getCode(), $e);
}
}
Expand Down
13 changes: 3 additions & 10 deletions src/Queue/src/Options.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,8 @@

final class Options implements OptionsInterface, \JsonSerializable
{
/** @var int|null */
private $delay;

/** @var string|null */
private $queue;
private ?int $delay = null;
private ?string $queue = null;

public function withQueue(?string $queue): self
{
Expand Down Expand Up @@ -38,11 +35,7 @@ public function getDelay(): ?int
return $this->delay;
}

/**
* @return array|mixed
*/
#[\ReturnTypeWillChange]
public function jsonSerialize()
public function jsonSerialize(): array
{
return [
'delay' => $this->delay,
Expand Down
16 changes: 6 additions & 10 deletions src/Queue/src/QueueManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,17 @@
final class QueueManager implements QueueConnectionProviderInterface
{
/** @var QueueInterface[] */
private $pipelines = [];
/** @var QueueConfig */
private $config;
/** @var FactoryInterface */
private $factory;
private array $pipelines = [];

public function __construct(QueueConfig $config, FactoryInterface $factory)
{
$this->config = $config;
$this->factory = $factory;
public function __construct(
private readonly QueueConfig $config,
private readonly FactoryInterface $factory
) {
}

public function getConnection(?string $name = null): QueueInterface
{
$name = $name ?: $this->getDefaultDriver();
$name ??= $this->getDefaultDriver();
// Replaces alias with real pipeline name
$name = $this->config->getAliases()[$name] ?? $name;

Expand Down
15 changes: 4 additions & 11 deletions src/Queue/src/QueueRegistry.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,18 @@
final class QueueRegistry implements HandlerRegistryInterface
{
/** @var array<string, class-string> */
private $handlers = [];
/** @var ContainerInterface */
private $container;
/** @var HandlerRegistryInterface */
private $fallbackHandlers;
private array $handlers = [];

public function __construct(
ContainerInterface $container,
HandlerRegistryInterface $handlers
private readonly ContainerInterface $container,
private readonly HandlerRegistryInterface $fallbackHandlers
) {
$this->container = $container;
$this->fallbackHandlers = $handlers;
}

/**
* Associate specific job type with handler class or object
* @param HandlerInterface|string $handler
*/
public function setHandler(string $jobType, $handler): void
public function setHandler(string $jobType, HandlerInterface|string $handler): void
{
$this->handlers[$jobType] = $handler;
}
Expand Down

0 comments on commit 040234a

Please sign in to comment.