From 8fb600425a7277e9e9a6ffcc1bbaeafe7cf4f88d Mon Sep 17 00:00:00 2001 From: Yevgeny Tomenko Date: Wed, 21 Oct 2026 04:42:42 +0300 Subject: [PATCH 1/7] Upgrade queue plugin to CakePHP 6.x --- composer.json | 12 ++-- src/Command/JobCommand.php | 13 ++-- src/Command/PurgeFailedCommand.php | 37 ++++------- src/Command/RequeueCommand.php | 45 +++++-------- src/Command/WorkerCommand.php | 66 +++++++++---------- src/Job/Message.php | 4 +- src/Mailer/Transport/QueueTransport.php | 2 +- src/Model/Entity/FailedJob.php | 2 +- src/Queue/Processor.php | 4 +- src/QueuePlugin.php | 6 +- src/TestSuite/TestQueueClient.php | 6 +- tests/Fixture/FailedJobsFixture.php | 4 +- tests/test_app/src/Application.php | 2 +- .../src/Queue/TestCustomProcessor.php | 4 +- 14 files changed, 93 insertions(+), 114 deletions(-) diff --git a/composer.json b/composer.json index 53f147b..177392b 100644 --- a/composer.json +++ b/composer.json @@ -20,15 +20,15 @@ "source": "https://github.com/cakephp/queue" }, "require": { - "php": ">=8.2", - "cakephp/cakephp": "^5.4.0", + "php": ">=8.5", + "cakephp/cakephp": "6.x-dev", "enqueue/simple-client": "^0.10", "psr/log": "^3.0", "ramsey/uuid": "^4.7.0" }, "require-dev": { - "cakephp/bake": "^3.5.1", - "cakephp/cakephp-codesniffer": "^5.3", + "cakephp/bake": "4.x-dev", + "cakephp/cakephp-codesniffer": "6.x-dev", "enqueue/enqueue": "^0.10.27", "enqueue/fs": "^0.10", "phpunit/phpunit": "^11.5.3 || ^12.1.3 || ^13.0" @@ -56,6 +56,8 @@ }, "sort-packages": true }, + "minimum-stability": "dev", + "prefer-stable": true, "scripts": { "check": [ "@cs-check", @@ -67,7 +69,7 @@ "phpstan": "tools/phpstan analyse", "stan-baseline": "tools/phpstan --generate-baseline", "stan-setup": "phive install", - "rector-setup": "cp composer.json composer.backup && composer require --dev rector/rector:\"~2.5.0\" && mv composer.backup composer.json", + "rector-setup": "cp composer.json composer.backup && composer require --dev rector/rector:\"~2.7.0\" && mv composer.backup composer.json", "rector-check": "vendor/bin/rector process --dry-run", "rector-fix": "vendor/bin/rector process", "test": "phpunit", diff --git a/src/Command/JobCommand.php b/src/Command/JobCommand.php index 7148df9..ec22044 100644 --- a/src/Command/JobCommand.php +++ b/src/Command/JobCommand.php @@ -17,7 +17,6 @@ namespace Cake\Queue\Command; use Bake\Command\SimpleBakeCommand; -use Cake\Console\Arguments; use Cake\Console\ConsoleOptionParser; class JobCommand extends SimpleBakeCommand @@ -51,14 +50,14 @@ public function template(): string /** * @inheritDoc */ - public function templateData(Arguments $arguments): array + public function templateData(): array { - $parentData = parent::templateData($arguments); + $parentData = parent::templateData(); - $maxAttempts = $arguments->getOption('max-attempts'); + $maxAttempts = $this->args->getOption('max-attempts'); $data = [ - 'isUnique' => $arguments->getOption('unique'), + 'isUnique' => $this->args->getOption('unique'), 'maxAttempts' => $maxAttempts ? (int)$maxAttempts : null, ]; @@ -71,9 +70,9 @@ public function templateData(Arguments $arguments): array * @param \Cake\Console\ConsoleOptionParser $parser The parser to update. * @return \Cake\Console\ConsoleOptionParser */ - public function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser + protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser { - $parser = $this->_setCommonOptions($parser); + $parser = $this->setCommonOptions($parser); return $parser ->setDescription('Bake a queue job class.') diff --git a/src/Command/PurgeFailedCommand.php b/src/Command/PurgeFailedCommand.php index c54cc8d..80bd38d 100644 --- a/src/Command/PurgeFailedCommand.php +++ b/src/Command/PurgeFailedCommand.php @@ -17,8 +17,6 @@ namespace Cake\Queue\Command; use Cake\Command\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIo; use Cake\Console\ConsoleOptionParser; use Cake\ORM\Locator\LocatorAwareTrait; @@ -70,19 +68,15 @@ public function getOptionParser(): ConsoleOptionParser } /** - * @param \Cake\Console\Arguments $args Arguments - * @param \Cake\Console\ConsoleIo $io ConsoleIo * @return int */ - public function execute(Arguments $args, ConsoleIo $io): int + public function execute(): int { /** @var \Cake\Queue\Model\Table\FailedJobsTable $failedJobsTable */ $failedJobsTable = $this->getTableLocator()->get('Cake/Queue.FailedJobs'); - $jobsToDelete = $failedJobsTable->find(); - - if ($args->hasArgument('ids')) { - $idsArg = $args->getArgument('ids'); + if ($this->args->hasArgument('ids')) { + $idsArg = $this->args->getArgument('ids'); if ($idsArg !== null) { $ids = explode(',', $idsArg); @@ -91,39 +85,36 @@ public function execute(Arguments $args, ConsoleIo $io): int } } - if ($args->hasOption('class')) { - $jobsToDelete->where(['class' => $args->getOption('class')]); + if ($this->args->hasOption('class')) { + $jobsToDelete->where(['class' => $this->args->getOption('class')]); } - if ($args->hasOption('queue')) { - $jobsToDelete->where(['queue' => $args->getOption('queue')]); + if ($this->args->hasOption('queue')) { + $jobsToDelete->where(['queue' => $this->args->getOption('queue')]); } - if ($args->hasOption('config')) { - $jobsToDelete->where(['config' => $args->getOption('config')]); + if ($this->args->hasOption('config')) { + $jobsToDelete->where(['config' => $this->args->getOption('config')]); } $deletingCount = $jobsToDelete->count(); - if (!$deletingCount) { - $io->out('0 jobs found.'); + $this->io->out('0 jobs found.'); return self::CODE_SUCCESS; } - if (!$args->getOption('force')) { - $confirmed = $io->askChoice(sprintf('Delete %s jobs?', $deletingCount), ['y', 'n'], 'n'); + if (!$this->args->getOption('force')) { + $confirmed = $this->io->askChoice(sprintf('Delete %s jobs?', $deletingCount), ['y', 'n'], 'n'); if ($confirmed !== 'y') { return self::CODE_SUCCESS; } } - $io->out(sprintf('Deleting %s jobs.', $deletingCount)); - + $this->io->out(sprintf('Deleting %s jobs.', $deletingCount)); $failedJobsTable->deleteManyOrFail($jobsToDelete); - - $io->success($deletingCount . ' jobs deleted.'); + $this->io->success($deletingCount . ' jobs deleted.'); return self::CODE_SUCCESS; } diff --git a/src/Command/RequeueCommand.php b/src/Command/RequeueCommand.php index 4f0f1da..f416faa 100644 --- a/src/Command/RequeueCommand.php +++ b/src/Command/RequeueCommand.php @@ -17,8 +17,6 @@ namespace Cake\Queue\Command; use Cake\Command\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIo; use Cake\Console\ConsoleOptionParser; use Cake\ORM\Locator\LocatorAwareTrait; use Cake\Queue\QueueManager; @@ -72,19 +70,15 @@ public function getOptionParser(): ConsoleOptionParser } /** - * @param \Cake\Console\Arguments $args Arguments - * @param \Cake\Console\ConsoleIo $io ConsoleIo * @return int */ - public function execute(Arguments $args, ConsoleIo $io): int + public function execute(): int { /** @var \Cake\Queue\Model\Table\FailedJobsTable $failedJobsTable */ $failedJobsTable = $this->getTableLocator()->get('Cake/Queue.FailedJobs'); - $jobsToRequeueQuery = $failedJobsTable->find(); - - if ($args->hasArgument('ids')) { - $idsArg = $args->getArgument('ids'); + if ($this->args->hasArgument('ids')) { + $idsArg = $this->args->getArgument('ids'); if ($idsArg !== null) { $ids = explode(',', $idsArg); @@ -93,43 +87,40 @@ public function execute(Arguments $args, ConsoleIo $io): int } } - if ($args->hasOption('class')) { - $jobsToRequeueQuery->where(['class' => $args->getOption('class')]); + if ($this->args->hasOption('class')) { + $jobsToRequeueQuery->where(['class' => $this->args->getOption('class')]); } - if ($args->hasOption('queue')) { - $jobsToRequeueQuery->where(['queue' => $args->getOption('queue')]); + if ($this->args->hasOption('queue')) { + $jobsToRequeueQuery->where(['queue' => $this->args->getOption('queue')]); } - if ($args->hasOption('config')) { - $jobsToRequeueQuery->where(['config' => $args->getOption('config')]); + if ($this->args->hasOption('config')) { + $jobsToRequeueQuery->where(['config' => $this->args->getOption('config')]); } $requeueingCount = $jobsToRequeueQuery->count(); - if (!$requeueingCount) { - $io->out('0 jobs found.'); + $this->io->out('0 jobs found.'); return self::CODE_SUCCESS; } - if (!$args->getOption('force')) { - $confirmed = $io->askChoice(sprintf('Requeue %s jobs?', $requeueingCount), ['y', 'n'], 'n'); + if (!$this->args->getOption('force')) { + $confirmed = $this->io->askChoice(sprintf('Requeue %s jobs?', $requeueingCount), ['y', 'n'], 'n'); if ($confirmed !== 'y') { return self::CODE_SUCCESS; } } - $io->out(sprintf('Requeueing %s jobs.', $requeueingCount)); - + $this->io->out(sprintf('Requeueing %s jobs.', $requeueingCount)); $succeededCount = 0; $failedCount = 0; - /** @var array<\Cake\Queue\Model\Entity\FailedJob> $jobsToRequeue */ $jobsToRequeue = $jobsToRequeueQuery->all(); foreach ($jobsToRequeue as $failedJob) { - $io->verbose(sprintf('Requeueing FailedJob with ID %d.', $failedJob->id)); + $this->io->verbose(sprintf('Requeueing FailedJob with ID %d.', $failedJob->id)); try { QueueManager::push( [$failedJob->class, $failedJob->method], @@ -147,19 +138,19 @@ public function execute(Arguments $args, ConsoleIo $io): int $succeededCount++; } catch (Exception $e) { - $io->err('Exception occurred while requeueing FailedJob with ID ' . $failedJob->id); - $io->err((string)$e); + $this->io->err('Exception occurred while requeueing FailedJob with ID ' . $failedJob->id); + $this->io->err((string)$e); $failedCount++; } } if ($failedCount !== 0) { - $io->err(sprintf('Failed to requeue %d jobs.', $failedCount)); + $this->io->err(sprintf('Failed to requeue %d jobs.', $failedCount)); } if ($succeededCount !== 0) { - $io->success($succeededCount . ' jobs requeued.'); + $this->io->success($succeededCount . ' jobs requeued.'); } return self::CODE_SUCCESS; diff --git a/src/Command/WorkerCommand.php b/src/Command/WorkerCommand.php index 7efa802..fefe090 100644 --- a/src/Command/WorkerCommand.php +++ b/src/Command/WorkerCommand.php @@ -17,11 +17,10 @@ namespace Cake\Queue\Command; use Cake\Command\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIo; +use Cake\Console\CommandFactoryInterface; use Cake\Console\ConsoleOptionParser; +use Cake\Container\ContainerInterface; use Cake\Core\Configure; -use Cake\Core\ContainerInterface; use Cake\Log\Log; use Cake\Queue\Consumption\LimitAttemptsExtension; use Cake\Queue\Consumption\LimitConsumedMessagesExtension; @@ -44,11 +43,14 @@ class WorkerCommand extends Command { /** - * @param \Cake\Core\ContainerInterface|null $container DI container instance + * @param \Cake\Console\CommandFactoryInterface|null $factory Command factory. + * @param \Cake\Container\ContainerInterface|null $container DI container instance */ public function __construct( + ?CommandFactoryInterface $factory = null, protected readonly ?ContainerInterface $container = null, ) { + parent::__construct($factory); } /** @@ -115,17 +117,16 @@ public function getOptionParser(): ConsoleOptionParser /** * Creates and returns a QueueExtension object * - * @param \Cake\Console\Arguments $args Arguments * @param \Psr\Log\LoggerInterface $logger Logger instance. * @return \Enqueue\Consumption\ExtensionInterface */ - protected function getQueueExtension(Arguments $args, LoggerInterface $logger): ExtensionInterface + protected function getQueueExtension(LoggerInterface $logger): ExtensionInterface { - $limitAttempsExtension = new LimitAttemptsExtension((int)$args->getOption('max-attempts') ?: null); + $limitAttempsExtension = new LimitAttemptsExtension((int)$this->args->getOption('max-attempts') ?: null); $limitAttempsExtension->getEventManager()->on(new FailedJobsListener()); - $configKey = (string)$args->getOption('config'); + $configKey = (string)$this->args->getOption('config'); $config = QueueManager::getConfig($configKey); $extensions = [ @@ -133,13 +134,13 @@ protected function getQueueExtension(Arguments $args, LoggerInterface $logger): $limitAttempsExtension, ]; - if ($args->getOption('max-jobs') !== null) { - $maxJobs = (int)$args->getOption('max-jobs'); + if ($this->args->getOption('max-jobs') !== null) { + $maxJobs = (int)$this->args->getOption('max-jobs'); $extensions[] = new LimitConsumedMessagesExtension($maxJobs); } - if ($args->getOption('max-runtime') !== null) { - $endTime = new DateTime(sprintf('+%d seconds', (int)$args->getOption('max-runtime'))); + if ($this->args->getOption('max-runtime') !== null) { + $endTime = new DateTime(sprintf('+%d seconds', (int)$this->args->getOption('max-runtime'))); $extensions[] = new LimitConsumptionTimeExtension($endTime); } @@ -153,14 +154,13 @@ protected function getQueueExtension(Arguments $args, LoggerInterface $logger): /** * Creates and returns a LoggerInterface object * - * @param \Cake\Console\Arguments $args Arguments * @return \Psr\Log\LoggerInterface */ - protected function getLogger(Arguments $args): LoggerInterface + protected function getLogger(): LoggerInterface { $logger = null; - if (!(in_array($args->getOption('verbose'), ['', '0'], true) || $args->getOption('verbose') === false || $args->getOption('verbose') === null)) { - $logger = Log::engine((string)$args->getOption('logger')); + if (!(in_array($this->args->getOption('verbose'), ['', '0'], true) || $this->args->getOption('verbose') === false || $this->args->getOption('verbose') === null)) { + $logger = Log::engine((string)$this->args->getOption('logger')); } return $logger ?? new NullLogger(); @@ -169,25 +169,23 @@ protected function getLogger(Arguments $args): LoggerInterface /** * Creates and returns a Processor object * - * @param \Cake\Console\Arguments $args Arguments - * @param \Cake\Console\ConsoleIo $io ConsoleIo * @param \Psr\Log\LoggerInterface $logger Logger instance * @return \Interop\Queue\Processor */ - protected function getProcessor(Arguments $args, ConsoleIo $io, LoggerInterface $logger): InteropProcessor + protected function getProcessor(LoggerInterface $logger): InteropProcessor { - $configKey = (string)$args->getOption('config'); + $configKey = (string)$this->args->getOption('config'); $config = QueueManager::getConfig($configKey); $processorClass = $config['processor'] ?? Processor::class; if (!class_exists($processorClass)) { - $io->error(sprintf('Processor class %s not found', $processorClass)); + $this->io->error(sprintf('Processor class %s not found', $processorClass)); $this->abort(); } if (!is_subclass_of($processorClass, InteropProcessor::class)) { - $io->error(sprintf('Processor class %s must implement Interop\Queue\Processor', $processorClass)); + $this->io->error(sprintf('Processor class %s must implement Interop\Queue\Processor', $processorClass)); $this->abort(); } @@ -195,27 +193,24 @@ protected function getProcessor(Arguments $args, ConsoleIo $io, LoggerInterface } /** - * @param \Cake\Console\Arguments $args Arguments - * @param \Cake\Console\ConsoleIo $io ConsoleIo * @return int */ - public function execute(Arguments $args, ConsoleIo $io): int + public function execute(): int { - $config = (string)$args->getOption('config'); + $config = (string)$this->args->getOption('config'); if (!Configure::check(sprintf('Queue.%s', $config))) { - $io->error(sprintf('Configuration key "%s" was not found', $config)); + $this->io->error(sprintf('Configuration key "%s" was not found', $config)); $this->abort(); } - $logger = $this->getLogger($args); - $processor = $this->getProcessor($args, $io, $logger); - $extension = $this->getQueueExtension($args, $logger); - + $logger = $this->getLogger(); + $processor = $this->getProcessor($logger); + $extension = $this->getQueueExtension($logger); $hasListener = Configure::check(sprintf('Queue.%s.listener', $config)); if ($hasListener) { $listenerClassName = Configure::read(sprintf('Queue.%s.listener', $config)); if (!class_exists($listenerClassName)) { - $io->error(sprintf('Listener class %s not found', $listenerClassName)); + $this->io->error(sprintf('Listener class %s not found', $listenerClassName)); $this->abort(); } @@ -228,11 +223,10 @@ public function execute(Arguments $args, ConsoleIo $io): int } $client = QueueManager::engine($config); - $queue = $args->getOption('queue') - ? (string)$args->getOption('queue') + $queue = $this->args->getOption('queue') + ? (string)$this->args->getOption('queue') : Configure::read(sprintf('Queue.%s.queue', $config), 'default'); - $processorName = $args->getOption('processor') ? (string)$args->getOption('processor') : 'default'; - + $processorName = $this->args->getOption('processor') ? (string)$this->args->getOption('processor') : 'default'; $client->bindTopic($queue, $processor, $processorName); $client->consume($extension); diff --git a/src/Job/Message.php b/src/Job/Message.php index 4b328d1..9fb4fc9 100644 --- a/src/Job/Message.php +++ b/src/Job/Message.php @@ -16,7 +16,7 @@ */ namespace Cake\Queue\Job; -use Cake\Core\ContainerInterface; +use Cake\Container\ContainerInterface; use Cake\Queue\Dto\DtoManager; use Cake\Utility\Hash; use Closure; @@ -45,7 +45,7 @@ class Message implements JsonSerializable /** * @param \Interop\Queue\Message $originalMessage Queue message. * @param \Interop\Queue\Context $context Context. - * @param \Cake\Core\ContainerInterface|null $container DI container instance + * @param \Cake\Container\ContainerInterface|null $container DI container instance */ public function __construct( protected readonly QueueMessage $originalMessage, diff --git a/src/Mailer/Transport/QueueTransport.php b/src/Mailer/Transport/QueueTransport.php index da45783..4af0bf9 100644 --- a/src/Mailer/Transport/QueueTransport.php +++ b/src/Mailer/Transport/QueueTransport.php @@ -29,7 +29,7 @@ class QueueTransport extends AbstractTransport * * @var array */ - protected array $_defaultConfig = [ + protected array $defaultConfig = [ 'options' => [], 'transport' => MailTransport::class, ]; diff --git a/src/Model/Entity/FailedJob.php b/src/Model/Entity/FailedJob.php index 8516bd6..2613227 100644 --- a/src/Model/Entity/FailedJob.php +++ b/src/Model/Entity/FailedJob.php @@ -33,7 +33,7 @@ class FailedJob extends Entity * * @var array */ - protected array $_accessible = [ + protected array $patchable = [ 'class' => true, 'method' => true, 'data' => true, diff --git a/src/Queue/Processor.php b/src/Queue/Processor.php index f4e7b07..16cd49b 100644 --- a/src/Queue/Processor.php +++ b/src/Queue/Processor.php @@ -16,7 +16,7 @@ */ namespace Cake\Queue\Queue; -use Cake\Core\ContainerInterface; +use Cake\Container\ContainerInterface; use Cake\Event\EventDispatcherTrait; use Cake\Queue\Job\Message; use Enqueue\Consumption\Result; @@ -35,7 +35,7 @@ class Processor implements InteropProcessor /** * @param \Psr\Log\LoggerInterface $logger Logger instance. - * @param \Cake\Core\ContainerInterface|null $container DI container instance + * @param \Cake\Container\ContainerInterface|null $container DI container instance */ public function __construct( protected readonly LoggerInterface $logger = new NullLogger(), diff --git a/src/QueuePlugin.php b/src/QueuePlugin.php index 9f7202b..84c95df 100644 --- a/src/QueuePlugin.php +++ b/src/QueuePlugin.php @@ -18,9 +18,9 @@ use Bake\Command\SimpleBakeCommand; use Cake\Console\CommandCollection; +use Cake\Container\ContainerInterface; use Cake\Core\BasePlugin; use Cake\Core\Configure; -use Cake\Core\ContainerInterface; use Cake\Core\PluginApplicationInterface; use Cake\Queue\Command\JobCommand; use Cake\Queue\Command\PurgeFailedCommand; @@ -87,7 +87,7 @@ public function console(CommandCollection $commands): CommandCollection /** * Add DI container to Worker command * - * @param \Cake\Core\ContainerInterface $container The DI container + * @param \Cake\Container\ContainerInterface $container The DI container * @return void */ public function services(ContainerInterface $container): void @@ -95,6 +95,6 @@ public function services(ContainerInterface $container): void $container->add(ContainerInterface::class, $container); $container ->add(WorkerCommand::class) - ->addArgument(ContainerInterface::class); + ->addArgument(ContainerInterface::class, 'container'); } } diff --git a/src/TestSuite/TestQueueClient.php b/src/TestSuite/TestQueueClient.php index d02f7ee..dc46a44 100644 --- a/src/TestSuite/TestQueueClient.php +++ b/src/TestSuite/TestQueueClient.php @@ -4,6 +4,8 @@ namespace Cake\Queue\TestSuite; use Cake\Queue\QueueManager; +use Cake\Queue\TestSuite\Transport\TestConnectionFactory; +use Cake\Queue\TestSuite\Transport\TestDriver; use Enqueue\Client\Resources as ClientResources; use Enqueue\Resources; use Interop\Queue\Destination; @@ -56,13 +58,13 @@ public static function replaceAllClients(): void { if (!static::$registered) { Resources::addConnection( - Transport\TestConnectionFactory::class, + TestConnectionFactory::class, ['test'], [], 'cakephp/queue-testsuite', ); ClientResources::addDriver( - Transport\TestDriver::class, + TestDriver::class, ['test'], [], ['cakephp/queue-testsuite'], diff --git a/tests/Fixture/FailedJobsFixture.php b/tests/Fixture/FailedJobsFixture.php index 7f5116a..5e2318c 100644 --- a/tests/Fixture/FailedJobsFixture.php +++ b/tests/Fixture/FailedJobsFixture.php @@ -64,7 +64,7 @@ public function init(): void ]; parent::init(); - $this->_schema->setColumnType('data', 'json'); - $this->_schema->setColumnType('metadata', 'json'); + $this->schema->setColumnType('data', 'json'); + $this->schema->setColumnType('metadata', 'json'); } } diff --git a/tests/test_app/src/Application.php b/tests/test_app/src/Application.php index e8119b2..6582f57 100644 --- a/tests/test_app/src/Application.php +++ b/tests/test_app/src/Application.php @@ -3,7 +3,7 @@ namespace TestApp; -use Cake\Core\ContainerInterface; +use Cake\Container\ContainerInterface; use Cake\Http\BaseApplication; use Cake\Http\MiddlewareQueue; use Cake\Queue\Test\test_app\src\Job\LogToDebugWithServiceJob; diff --git a/tests/test_app/src/Queue/TestCustomProcessor.php b/tests/test_app/src/Queue/TestCustomProcessor.php index a5f17cf..546e7b3 100644 --- a/tests/test_app/src/Queue/TestCustomProcessor.php +++ b/tests/test_app/src/Queue/TestCustomProcessor.php @@ -3,7 +3,7 @@ namespace Cake\Queue\Test\test_app\src\Queue; -use Cake\Core\ContainerInterface; +use Cake\Container\ContainerInterface; use Cake\Event\EventDispatcherTrait; use Cake\Queue\Job\Message; use Enqueue\Consumption\Result; @@ -34,7 +34,7 @@ class TestCustomProcessor implements InteropProcessor * Constructor * * @param \Psr\Log\LoggerInterface|null $logger Logger instance - * @param \Cake\Core\ContainerInterface|null $container DI container instance + * @param \Cake\Container\ContainerInterface|null $container DI container instance */ public function __construct(?LoggerInterface $logger = null, ?ContainerInterface $container = null) { From 127f4228eee284e0c28e2f7620594a5cc687c643 Mon Sep 17 00:00:00 2001 From: Yevgeny Tomenko Date: Wed, 21 Oct 2026 19:50:52 +0300 Subject: [PATCH 2/7] Update workflow to 6.x --- .github/workflows/ci.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5785bb9..4a0bea8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,9 +14,9 @@ permissions: jobs: testsuite: - uses: cakephp/.github/.github/workflows/testsuite-with-db.yml@5.x + uses: cakephp/.github/.github/workflows/testsuite-with-db.yml@6.x secrets: inherit cs-stan: - uses: cakephp/.github/.github/workflows/cs-stan.yml@5.x + uses: cakephp/.github/.github/workflows/cs-stan.yml@6.x secrets: inherit From 751d2a70363b880b3e31581b4da5f20594291302 Mon Sep 17 00:00:00 2001 From: Yevgeny Tomenko Date: Wed, 21 Oct 2026 19:54:02 +0300 Subject: [PATCH 3/7] Bump phpunit to 13.0 --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 177392b..ace5001 100644 --- a/composer.json +++ b/composer.json @@ -31,7 +31,7 @@ "cakephp/cakephp-codesniffer": "6.x-dev", "enqueue/enqueue": "^0.10.27", "enqueue/fs": "^0.10", - "phpunit/phpunit": "^11.5.3 || ^12.1.3 || ^13.0" + "phpunit/phpunit": "^13.0" }, "suggest": { "cakephp/bake": "Required if you want to generate jobs.", From 1e5f3aeb7ba6fa1f94486feccc7f543f906df151 Mon Sep 17 00:00:00 2001 From: Yevgeny Tomenko Date: Wed, 21 Oct 2026 20:09:45 +0300 Subject: [PATCH 4/7] Bump dependecies to resolve lowest build --- composer.json | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index ace5001..a23a3c7 100644 --- a/composer.json +++ b/composer.json @@ -22,15 +22,19 @@ "require": { "php": ">=8.5", "cakephp/cakephp": "6.x-dev", - "enqueue/simple-client": "^0.10", + "enqueue/simple-client": "^0.10.27", + "enqueue/dsn": "^0.10.27", + "enqueue/null": "^0.10.27", "psr/log": "^3.0", + "queue-interop/amqp-interop": "^0.8.2", + "queue-interop/queue-interop": "^0.8.2", "ramsey/uuid": "^4.7.0" }, "require-dev": { "cakephp/bake": "4.x-dev", "cakephp/cakephp-codesniffer": "6.x-dev", "enqueue/enqueue": "^0.10.27", - "enqueue/fs": "^0.10", + "enqueue/fs": "^0.10.27", "phpunit/phpunit": "^13.0" }, "suggest": { From 68896d109a5f843281042eb4cf7e4dfe892ecfeb Mon Sep 17 00:00:00 2001 From: Yevgeny Tomenko Date: Wed, 21 Oct 2026 20:15:11 +0300 Subject: [PATCH 5/7] Add symfony/config to fix lowest deprecations --- composer.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/composer.json b/composer.json index a23a3c7..2b36672 100644 --- a/composer.json +++ b/composer.json @@ -28,7 +28,8 @@ "psr/log": "^3.0", "queue-interop/amqp-interop": "^0.8.2", "queue-interop/queue-interop": "^0.8.2", - "ramsey/uuid": "^4.7.0" + "ramsey/uuid": "^4.7.0", + "symfony/config": "^6.4.3 || ^7.0.3 || ^8.0" }, "require-dev": { "cakephp/bake": "4.x-dev", From 509c1a6f2571e34809aad227a1a6ca0c76a8e945 Mon Sep 17 00:00:00 2001 From: Yevgeny Tomenko Date: Mon, 16 Nov 2026 01:05:23 +0300 Subject: [PATCH 6/7] Add additive job attributes for queue defaults Introduce Cake\Queue\Attribute set with native names: Queue, Config, Delay, Expires, Priority, MaxAttempts, ShouldBeUnique. Attributes act as class defaults, explicit push() options win over attributes and attributes win over static properties. Resolve hierarchy parent to child with instance cache in JobAttributeReader following core DtoMapper and AttributeRouteConnector patterns. --- src/Attribute/Config.php | 31 ++ src/Attribute/Delay.php | 31 ++ src/Attribute/Expires.php | 31 ++ src/Attribute/JobAttributeReader.php | 193 ++++++++++ src/Attribute/MaxAttempts.php | 31 ++ src/Attribute/Priority.php | 31 ++ src/Attribute/Queue.php | 31 ++ src/Attribute/ShouldBeUnique.php | 31 ++ .../RemoveUniqueJobIdFromCacheExtension.php | 3 +- src/Job/Message.php | 6 +- src/QueueManager.php | 45 ++- tests/TestCase/Attribute/JobAttributeTest.php | 356 ++++++++++++++++++ tests/test_app/src/Job/AttributeBaseJob.php | 16 + tests/test_app/src/Job/AttributeChildJob.php | 8 + tests/test_app/src/Job/AttributeFullJob.php | 30 ++ .../src/Job/AttributeOptOutUniqueJob.php | 20 + tests/test_app/src/Job/AttributeParentJob.php | 11 + tests/test_app/src/Job/AttributeQueueJob.php | 18 + .../src/Job/AttributeStaticMixJob.php | 20 + tests/test_app/src/Job/AttributeUniqueJob.php | 18 + 20 files changed, 942 insertions(+), 19 deletions(-) create mode 100644 src/Attribute/Config.php create mode 100644 src/Attribute/Delay.php create mode 100644 src/Attribute/Expires.php create mode 100644 src/Attribute/JobAttributeReader.php create mode 100644 src/Attribute/MaxAttempts.php create mode 100644 src/Attribute/Priority.php create mode 100644 src/Attribute/Queue.php create mode 100644 src/Attribute/ShouldBeUnique.php create mode 100644 tests/TestCase/Attribute/JobAttributeTest.php create mode 100644 tests/test_app/src/Job/AttributeBaseJob.php create mode 100644 tests/test_app/src/Job/AttributeChildJob.php create mode 100644 tests/test_app/src/Job/AttributeFullJob.php create mode 100644 tests/test_app/src/Job/AttributeOptOutUniqueJob.php create mode 100644 tests/test_app/src/Job/AttributeParentJob.php create mode 100644 tests/test_app/src/Job/AttributeQueueJob.php create mode 100644 tests/test_app/src/Job/AttributeStaticMixJob.php create mode 100644 tests/test_app/src/Job/AttributeUniqueJob.php diff --git a/src/Attribute/Config.php b/src/Attribute/Config.php new file mode 100644 index 0000000..1d081b5 --- /dev/null +++ b/src/Attribute/Config.php @@ -0,0 +1,31 @@ + attribute > static property > global default. + * Child class attributes win over parent class attributes. + */ +class JobAttributeReader +{ + /** + * Cached attribute instances per job class. + * + * @var array> + */ + protected static array $cache = []; + + /** + * Get attribute instance from class hierarchy, if present. + * + * Child class attributes win over parent class attributes. + * + * @param class-string|object $target Job class name or instance. + * @param class-string $attribute Attribute class name. + */ + public static function get(string|object $target, string $attribute): ?object + { + $class = is_object($target) ? $target::class : $target; + + if (array_key_exists($attribute, static::$cache[$class] ?? [])) { + return static::$cache[$class][$attribute]; + } + + $resolved = null; + foreach (static::hierarchy($class) as $candidate) { + $reflection = new ReflectionClass($candidate); + $attributes = $reflection->getAttributes($attribute); + if ($attributes !== []) { + $resolved = $attributes[0]->newInstance(); + } + } + + static::$cache[$class][$attribute] = $resolved; + + return $resolved; + } + + /** + * Get configured queue name for a job, if declared. + * + * @param class-string|object $target Job class name or instance. + */ + public static function getQueue(string|object $target): ?string + { + $attribute = static::get($target, Queue::class); + + return $attribute instanceof Queue ? $attribute->queue : null; + } + + /** + * Get configured config name for a job, if declared. + * + * @param class-string|object $target Job class name or instance. + */ + public static function getConfig(string|object $target): ?string + { + $attribute = static::get($target, Config::class); + + return $attribute instanceof Config ? $attribute->config : null; + } + + /** + * Get configured delay for a job, if declared. + * + * @param class-string|object $target Job class name or instance. + */ + public static function getDelay(string|object $target): ?int + { + $attribute = static::get($target, Delay::class); + + return $attribute instanceof Delay ? $attribute->delay : null; + } + + /** + * Get configured expiry for a job, if declared. + * + * @param class-string|object $target Job class name or instance. + */ + public static function getExpires(string|object $target): ?int + { + $attribute = static::get($target, Expires::class); + + return $attribute instanceof Expires ? $attribute->expires : null; + } + + /** + * Get configured priority for a job, if declared. + * + * @param class-string|object $target Job class name or instance. + */ + public static function getPriority(string|object $target): ?string + { + $attribute = static::get($target, Priority::class); + + return $attribute instanceof Priority ? $attribute->priority : null; + } + + /** + * Get configured max attempts for a job. + * + * Attribute wins over static property. Both remain supported. + * + * @param class-string|object $target Job class name or instance. + */ + public static function getMaxAttempts(string|object $target): ?int + { + $attribute = static::get($target, MaxAttempts::class); + if ($attribute instanceof MaxAttempts) { + return $attribute->maxAttempts; + } + + $class = is_object($target) ? $target::class : $target; + if (property_exists($class, 'maxAttempts') && isset($class::$maxAttempts)) { + /** @var int|null */ + return $class::$maxAttempts; + } + + return null; + } + + /** + * Check if a job should be treated as unique. + * + * Attribute wins over static property. Both remain supported. + * + * @param class-string|object $target Job class name or instance. + */ + public static function isUnique(string|object $target): bool + { + $attribute = static::get($target, ShouldBeUnique::class); + if ($attribute instanceof ShouldBeUnique) { + return $attribute->shouldBeUnique; + } + + $class = is_object($target) ? $target::class : $target; + + return property_exists($class, 'shouldBeUnique') && !empty($class::$shouldBeUnique); + } + + /** + * Clear the attribute instance cache. + * + * Useful for testing or when classes are reloaded. + * + * @return void + */ + public static function clearCache(): void + { + static::$cache = []; + } + + /** + * Parent-to-child class hierarchy, including the class itself. + * + * @param class-string $class Job class name. + * @return list + */ + protected static function hierarchy(string $class): array + { + $hierarchy = array_reverse(array_values(class_parents($class))); + $hierarchy[] = $class; + + return $hierarchy; + } +} diff --git a/src/Attribute/MaxAttempts.php b/src/Attribute/MaxAttempts.php new file mode 100644 index 0000000..88874c4 --- /dev/null +++ b/src/Attribute/MaxAttempts.php @@ -0,0 +1,31 @@ +getTarget(); - if (empty($class::$shouldBeUnique)) { + if (!JobAttributeReader::isUnique($class)) { return; } diff --git a/src/Job/Message.php b/src/Job/Message.php index 9fb4fc9..d7d0e9a 100644 --- a/src/Job/Message.php +++ b/src/Job/Message.php @@ -17,6 +17,7 @@ namespace Cake\Queue\Job; use Cake\Container\ContainerInterface; +use Cake\Queue\Attribute\JobAttributeReader; use Cake\Queue\Dto\DtoManager; use Cake\Utility\Hash; use Closure; @@ -221,6 +222,9 @@ public function getMetadata(): array /** * The maximum number of attempts allowed by the job. + * + * Resolves the `MaxAttempts` attribute first, then the static `$maxAttempts` + * property for backwards compatibility. */ public function getMaxAttempts(): ?int { @@ -228,7 +232,7 @@ public function getMaxAttempts(): ?int $class = $target[0]; - return $class::$maxAttempts ?? null; + return JobAttributeReader::getMaxAttempts($class); } /** diff --git a/src/QueueManager.php b/src/QueueManager.php index 6111c6c..43a5cd0 100644 --- a/src/QueueManager.php +++ b/src/QueueManager.php @@ -20,6 +20,7 @@ use Cake\Cache\Cache; use Cake\Core\App; use Cake\Log\Log; +use Cake\Queue\Attribute\JobAttributeReader; use Cake\Queue\Dto\DtoManager; use Enqueue\Client\Message as ClientMessage; use Enqueue\SimpleClient\SimpleClient; @@ -213,16 +214,19 @@ public static function engine(string $name): SimpleClient * name is stored as message metadata (uniqueness / debugging). Jobs must still * pass the expected class to `Message::getDto()`. * @param array $options An array of options for publishing the job: - * - `config` - A queue config name. Defaults to 'default'. + * - `config` - A queue config name. Defaults to the `Config` attribute value, + * then 'default'. * - `delay` - Time (in integer seconds) to delay message, after which it - * will be processed. Not all message brokers accept this. Default `null`. + * will be processed. Not all message brokers accept this. Defaults to the + * `Delay` attribute value, then `null`. * - `dtoClass` - Optional DTO class metadata recorded on the message body. * Only needed when `$data` is an array. Ignored when `$data` is already a DTO * object. Does not control hydration — the job passes the expected class to * `Message::getDto()`. Default `null`. * - `expires` - Time (in integer seconds) after which the message expires. * The message will be removed from the queue if this time is exceeded - * and it has not been consumed. Default `null`. + * and it has not been consumed. Defaults to the `Expires` attribute value, + * then `null`. * - `metadata` - Optional envelope data recorded on the message body next * to `data` (e.g. `tags`, `_uniqueId`, `batch_id`). Unlike `data` it is * never passed to the job or hydrated into a DTO. Omitted from the body @@ -233,8 +237,12 @@ public static function engine(string $name): SimpleClient * - `\Enqueue\Client\MessagePriority::NORMAL` * - `\Enqueue\Client\MessagePriority::HIGH` * - `\Enqueue\Client\MessagePriority::VERY_HIGH` - * - `queue` - The name of a queue to use, from queue `config` array or - * string 'default' if empty. + * Defaults to the `Priority` attribute value, then `null`. + * - `queue` - The name of a queue to use, from the `Queue` attribute value, + * then queue `config` array or string 'default' if empty. + * Job classes may declare additive defaults via `Cake\Queue\Attribute\*` + * attributes. Explicit `$options` values always win over attributes, and + * attributes win over static properties (`$maxAttempts`, `$shouldBeUnique`). */ public static function push(string|array $className, array|object $data = [], array $options = []): void { @@ -254,7 +262,7 @@ public static function push(string|array $className, array|object $data = [], ar $data = DtoManager::serialize($data); } - $name = $options['config'] ?? 'default'; + $name = $options['config'] ?? JobAttributeReader::getConfig($class) ?? 'default'; $config = static::getConfig($name) + [ 'logger' => null, @@ -262,10 +270,10 @@ public static function push(string|array $className, array|object $data = [], ar $logger = $config['logger'] ? Log::engine($config['logger']) : null; - if (!empty($class::$shouldBeUnique)) { + if (JobAttributeReader::isUnique($class)) { if (empty($config['uniqueCache'])) { throw new InvalidArgumentException( - $class . '::$shouldBeUnique is set to `true` but `uniqueCache` configuration is missing.', + $class . ' is marked as unique (`ShouldBeUnique` attribute or `$shouldBeUnique` property) but `uniqueCache` configuration is missing.', ); } @@ -285,7 +293,7 @@ public static function push(string|array $className, array|object $data = [], ar } } - $queue = $options['queue'] ?? $config['queue'] ?? 'default'; + $queue = $options['queue'] ?? JobAttributeReader::getQueue($class) ?? $config['queue'] ?? 'default'; $body = [ 'class' => [$class, $method], @@ -293,7 +301,7 @@ public static function push(string|array $className, array|object $data = [], ar 'data' => $data, 'requeueOptions' => [ 'config' => $name, - 'priority' => $options['priority'] ?? null, + 'priority' => $options['priority'] ?? JobAttributeReader::getPriority($class), 'queue' => $queue, ], ]; @@ -308,22 +316,25 @@ public static function push(string|array $className, array|object $data = [], ar $message = new ClientMessage($body); - if (isset($options['delay'])) { - $message->setDelay($options['delay']); + $delay = $options['delay'] ?? JobAttributeReader::getDelay($class); + if ($delay !== null) { + $message->setDelay($delay); } - if (isset($options['expires'])) { - $message->setExpire($options['expires']); + $expires = $options['expires'] ?? JobAttributeReader::getExpires($class); + if ($expires !== null) { + $message->setExpire($expires); } - if (isset($options['priority'])) { - $message->setPriority($options['priority']); + $priority = $options['priority'] ?? JobAttributeReader::getPriority($class); + if ($priority !== null) { + $message->setPriority($priority); } $client = static::engine($name); $client->sendEvent($queue, $message); - if (!empty($class::$shouldBeUnique)) { + if (JobAttributeReader::isUnique($class)) { $uniqueId = static::getUniqueId($class, $method, $data, $dtoClass); Cache::add($uniqueId, true, $config['uniqueCacheKey']); diff --git a/tests/TestCase/Attribute/JobAttributeTest.php b/tests/TestCase/Attribute/JobAttributeTest.php new file mode 100644 index 0000000..4840153 --- /dev/null +++ b/tests/TestCase/Attribute/JobAttributeTest.php @@ -0,0 +1,356 @@ +fsQueuePath = TMP . DS . 'queue-attr'; + if (!is_dir($this->fsQueuePath)) { + mkdir($this->fsQueuePath, 0777, true); + } + foreach (glob($this->fsQueuePath . DS . '*') ?: [] as $file) { + if (is_file($file)) { + @unlink($file); + } + } + $this->clearUniqueCache(); + JobAttributeReader::clearCache(); + } + + protected function tearDown(): void + { + foreach (glob($this->fsQueuePath . DS . '*') ?: [] as $file) { + if (is_file($file)) { + @unlink($file); + } + } + $this->clearUniqueCache(); + JobAttributeReader::clearCache(); + parent::tearDown(); + } + + private function clearUniqueCache(): void + { + $keys = ['Cake/Queue.queueUnique.test', 'Cake/Queue.queueUnique.other']; + foreach (['test', 'other'] as $name) { + $config = QueueManager::getConfig($name); + $cacheKey = is_array($config) ? ($config['uniqueCacheKey'] ?? null) : null; + if ($cacheKey && !in_array($cacheKey, $keys, true)) { + $keys[] = $cacheKey; + } + } + foreach ($keys as $cacheKey) { + try { + Cache::clear($cacheKey); + } catch (Throwable) { + } + } + } + + private function fsUrl(): string + { + return 'file:///' . $this->fsQueuePath; + } + + private function queueFileContents(string $suffix = 'enqueue.app.test'): string + { + $file = $this->fsQueuePath . DS . $suffix; + + $this->assertFileExists($file); + + return (string)file_get_contents($file); + } + + public function testReaderReturnsNullWhenNoAttribute(): void + { + $this->assertNull(JobAttributeReader::get(LogToDebugJob::class, Queue::class)); + $this->assertNull(JobAttributeReader::getQueue(LogToDebugJob::class)); + $this->assertNull(JobAttributeReader::getConfig(LogToDebugJob::class)); + $this->assertNull(JobAttributeReader::getDelay(LogToDebugJob::class)); + $this->assertNull(JobAttributeReader::getExpires(LogToDebugJob::class)); + $this->assertNull(JobAttributeReader::getPriority(LogToDebugJob::class)); + } + + public function testReaderResolvesFullJob(): void + { + $this->assertSame('attribute-queue', JobAttributeReader::getQueue(AttributeFullJob::class)); + $this->assertSame('test', JobAttributeReader::getConfig(AttributeFullJob::class)); + $this->assertSame(90, JobAttributeReader::getDelay(AttributeFullJob::class)); + $this->assertSame(3600, JobAttributeReader::getExpires(AttributeFullJob::class)); + $this->assertSame('high', JobAttributeReader::getPriority(AttributeFullJob::class)); + $this->assertSame(7, JobAttributeReader::getMaxAttempts(AttributeFullJob::class)); + $this->assertTrue(JobAttributeReader::isUnique(AttributeFullJob::class)); + + $queue = JobAttributeReader::get(AttributeFullJob::class, Queue::class); + $this->assertInstanceOf(Queue::class, $queue); + $this->assertInstanceOf(Config::class, JobAttributeReader::get(AttributeFullJob::class, Config::class)); + $this->assertInstanceOf(Delay::class, JobAttributeReader::get(AttributeFullJob::class, Delay::class)); + $this->assertInstanceOf(Expires::class, JobAttributeReader::get(AttributeFullJob::class, Expires::class)); + $this->assertInstanceOf(Priority::class, JobAttributeReader::get(AttributeFullJob::class, Priority::class)); + $this->assertInstanceOf(MaxAttempts::class, JobAttributeReader::get(AttributeFullJob::class, MaxAttempts::class)); + $this->assertInstanceOf(ShouldBeUnique::class, JobAttributeReader::get(AttributeFullJob::class, ShouldBeUnique::class)); + } + + public function testAttributeWinsOverStaticProperty(): void + { + $this->assertSame(3, MaxAttemptsIsThreeJob::$maxAttempts); + $this->assertSame(9, JobAttributeReader::getMaxAttempts(AttributeStaticMixJob::class)); + } + + public function testStaticPropertyUsedWhenNoAttribute(): void + { + $this->assertSame(3, JobAttributeReader::getMaxAttempts(MaxAttemptsIsThreeJob::class)); + $this->assertNull(JobAttributeReader::getMaxAttempts(LogToDebugJob::class)); + } + + public function testIsUniqueFallsBackToStatic(): void + { + $this->assertTrue(JobAttributeReader::isUnique(UniqueJob::class)); + $this->assertTrue(JobAttributeReader::isUnique(AttributeUniqueJob::class)); + $this->assertFalse(JobAttributeReader::isUnique(LogToDebugJob::class)); + } + + public function testAttributeCanOptOutOfStaticUnique(): void + { + $this->assertTrue((bool)AttributeOptOutUniqueJob::$shouldBeUnique); + $this->assertFalse(JobAttributeReader::isUnique(AttributeOptOutUniqueJob::class)); + } + + public function testAttributeInheritedFromParent(): void + { + $this->assertSame('parent-queue', JobAttributeReader::getQueue(AttributeParentJob::class)); + $this->assertSame('parent-queue', JobAttributeReader::getQueue(AttributeChildJob::class)); + } + + public function testMessageGetMaxAttemptsUsesAttribute(): void + { + $message = $this->messageFor(AttributeFullJob::class); + $this->assertSame(7, $message->getMaxAttempts()); + } + + public function testMessageGetMaxAttemptsPrefersAttributeOverStatic(): void + { + $message = $this->messageFor(AttributeStaticMixJob::class); + $this->assertSame(9, $message->getMaxAttempts()); + } + + public function testMessageGetMaxAttemptsFallsBackToStatic(): void + { + $message = $this->messageFor(MaxAttemptsIsThreeJob::class); + $this->assertSame(3, $message->getMaxAttempts()); + } + + public function testMessageGetMaxAttemptsNullWhenNothingDeclared(): void + { + $message = $this->messageFor(LogToDebugJob::class); + $this->assertNull($message->getMaxAttempts()); + } + + public function testPushUsesQueueAttributeWhenOptionMissing(): void + { + QueueManager::setConfig('test', [ + 'url' => $this->fsUrl(), + 'queue' => 'test', + ]); + + QueueManager::push(AttributeQueueJob::class, ['id' => 1], ['config' => 'test']); + + $contents = $this->queueFileContents(); + $this->assertStringContainsString('attribute-queue', $contents); + } + + public function testPushExplicitQueueOptionWinsOverAttribute(): void + { + QueueManager::setConfig('test', [ + 'url' => $this->fsUrl(), + 'queue' => 'test', + ]); + + QueueManager::push(AttributeQueueJob::class, ['id' => 1], ['config' => 'test', 'queue' => 'explicit-queue']); + + $contents = $this->queueFileContents(); + $this->assertStringContainsString('explicit-queue', $contents); + $this->assertStringNotContainsString('attribute-queue', $contents); + } + + public function testPushUsesConfigAttributeWhenOptionMissing(): void + { + QueueManager::setConfig('test', [ + 'url' => $this->fsUrl(), + 'queue' => 'test', + 'uniqueCache' => ['engine' => 'File'], + ]); + + QueueManager::push(AttributeFullJob::class, ['id' => 1]); + + $contents = $this->queueFileContents(); + $this->assertStringContainsString('AttributeFullJob', $contents); + } + + public function testPushExplicitConfigOptionWinsOverAttribute(): void + { + $otherPath = TMP . DS . 'queue-attr-other'; + if (!is_dir($otherPath)) { + mkdir($otherPath, 0777, true); + } + foreach (glob($otherPath . DS . '*') ?: [] as $file) { + if (is_file($file)) { + @unlink($file); + } + } + QueueManager::setConfig('test', [ + 'url' => $this->fsUrl(), + 'queue' => 'test', + 'uniqueCache' => ['engine' => 'File'], + ]); + QueueManager::setConfig('other', [ + 'url' => 'file:///' . $otherPath, + 'queue' => 'test', + 'uniqueCache' => ['engine' => 'File'], + ]); + + try { + QueueManager::push(AttributeFullJob::class, ['id' => 1], ['config' => 'other']); + + $otherFile = $otherPath . DS . 'enqueue.app.test'; + $this->assertFileExists($otherFile); + $this->assertStringContainsString('AttributeFullJob', (string)file_get_contents($otherFile)); + } finally { + foreach (glob($otherPath . DS . '*') ?: [] as $file) { + if (is_file($file)) { + @unlink($file); + } + } + @rmdir($otherPath); + } + } + + public function testPushAppliesDelayExpiresPriorityAttributes(): void + { + QueueManager::setConfig('test', [ + 'url' => $this->fsUrl(), + 'queue' => 'test', + 'uniqueCache' => ['engine' => 'File'], + ]); + + QueueManager::push(AttributeFullJob::class, ['id' => 1], ['config' => 'test']); + + $contents = $this->queueFileContents(); + $this->assertStringContainsString('enqueue.delay', $contents); + $this->assertStringContainsString('90', $contents); + $this->assertStringContainsString('enqueue.expire', $contents); + $this->assertStringContainsString('3600', $contents); + $this->assertStringContainsString('enqueue.priority', $contents); + $this->assertStringContainsString('high', $contents); + } + + public function testPushExplicitDelayWinsOverAttribute(): void + { + QueueManager::setConfig('test', [ + 'url' => $this->fsUrl(), + 'queue' => 'test', + 'uniqueCache' => ['engine' => 'File'], + ]); + + QueueManager::push(AttributeFullJob::class, ['id' => 1], ['config' => 'test', 'delay' => 5]); + + $contents = $this->queueFileContents(); + $this->assertStringContainsString('"enqueue.delay":5', $contents); + $this->assertStringNotContainsString('"enqueue.delay":90', $contents); + } + + public function testUniqueAttributeQueuesOnlyOnce(): void + { + QueueManager::setConfig('test', [ + 'url' => $this->fsUrl(), + 'queue' => 'test', + 'uniqueCache' => ['engine' => 'File'], + ]); + + QueueManager::push(AttributeUniqueJob::class, ['id' => 1], ['config' => 'test']); + QueueManager::push(AttributeUniqueJob::class, ['id' => 1], ['config' => 'test']); + + $contents = $this->queueFileContents(); + $this->assertSame(1, substr_count($contents, 'AttributeUniqueJob')); + } + + public function testOptOutAttributeDisablesStaticUnique(): void + { + QueueManager::setConfig('test', [ + 'url' => $this->fsUrl(), + 'queue' => 'test', + 'uniqueCache' => ['engine' => 'File'], + ]); + + QueueManager::push(AttributeOptOutUniqueJob::class, ['id' => 1], ['config' => 'test']); + QueueManager::push(AttributeOptOutUniqueJob::class, ['id' => 1], ['config' => 'test']); + + $contents = $this->queueFileContents(); + $this->assertSame(2, substr_count($contents, 'AttributeOptOutUniqueJob')); + } + + /** + * @param class-string $class + */ + private function messageFor(string $class): Message + { + $factory = new NullConnectionFactory(); + $context = $factory->createContext(); + + return new Message( + new NullMessage((string)json_encode([ + 'class' => [$class, 'execute'], + 'data' => ['id' => 1], + ])), + $context, + ); + } +} diff --git a/tests/test_app/src/Job/AttributeBaseJob.php b/tests/test_app/src/Job/AttributeBaseJob.php new file mode 100644 index 0000000..62580e3 --- /dev/null +++ b/tests/test_app/src/Job/AttributeBaseJob.php @@ -0,0 +1,16 @@ + Date: Mon, 16 Nov 2026 01:18:26 +0300 Subject: [PATCH 7/7] update phpstan and rector versions. fix code style --- .phive/phars.xml | 2 +- composer.json | 2 +- phpstan-baseline.neon | 2 +- src/Attribute/JobAttributeReader.php | 5 +++-- src/Job/Message.php | 5 ++--- tests/TestCase/Attribute/JobAttributeTest.php | 7 +++++++ 6 files changed, 15 insertions(+), 8 deletions(-) diff --git a/.phive/phars.xml b/.phive/phars.xml index 848f478..5f83d7e 100644 --- a/.phive/phars.xml +++ b/.phive/phars.xml @@ -1,4 +1,4 @@ - + diff --git a/composer.json b/composer.json index 2b36672..e14402b 100644 --- a/composer.json +++ b/composer.json @@ -74,7 +74,7 @@ "phpstan": "tools/phpstan analyse", "stan-baseline": "tools/phpstan --generate-baseline", "stan-setup": "phive install", - "rector-setup": "cp composer.json composer.backup && composer require --dev rector/rector:\"~2.7.0\" && mv composer.backup composer.json", + "rector-setup": "cp composer.json composer.backup && composer require --dev rector/rector:\"~2.8.0\" && mv composer.backup composer.json", "rector-check": "vendor/bin/rector process --dry-run", "rector-fix": "vendor/bin/rector process", "test": "phpunit", diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index b2d742e..b479a13 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -1,7 +1,7 @@ parameters: ignoreErrors: - - message: '#^Parameter \#1 \$callback of static method Closure\:\:fromCallable\(\) expects callable\(\)\: mixed, array\{mixed, string\} given\.$#' + message: '#^Parameter \#1 \$callback of static method Closure\:\:fromCallable\(\) expects callable\(\)\: mixed, array\{object, string\} given\.$#' identifier: argument.type count: 1 path: src/Job/Message.php diff --git a/src/Attribute/JobAttributeReader.php b/src/Attribute/JobAttributeReader.php index 2e566fb..3c1a7aa 100644 --- a/src/Attribute/JobAttributeReader.php +++ b/src/Attribute/JobAttributeReader.php @@ -139,8 +139,9 @@ public static function getMaxAttempts(string|object $target): ?int $class = is_object($target) ? $target::class : $target; if (property_exists($class, 'maxAttempts') && isset($class::$maxAttempts)) { - /** @var int|null */ - return $class::$maxAttempts; + $value = $class::$maxAttempts; + + return is_int($value) ? $value : null; } return null; diff --git a/src/Job/Message.php b/src/Job/Message.php index d7d0e9a..9bf961c 100644 --- a/src/Job/Message.php +++ b/src/Job/Message.php @@ -101,7 +101,7 @@ public function getCallable(): Closure } $target = $this->getTarget(); - if ($this->container && $this->container->has($target[0])) { + if ($this->container instanceof ContainerInterface && $this->container->has($target[0])) { $object = $this->container->get($target[0]); } else { $object = new $target[0](); @@ -115,8 +115,7 @@ public function getCallable(): Closure /** * Get the target class and method. * - * @return array{string, string} - * @phpstan-return array{class-string, string} + * @return array{class-string, string} */ public function getTarget(): array { diff --git a/tests/TestCase/Attribute/JobAttributeTest.php b/tests/TestCase/Attribute/JobAttributeTest.php index 4840153..de5fb25 100644 --- a/tests/TestCase/Attribute/JobAttributeTest.php +++ b/tests/TestCase/Attribute/JobAttributeTest.php @@ -56,11 +56,13 @@ protected function setUp(): void if (!is_dir($this->fsQueuePath)) { mkdir($this->fsQueuePath, 0777, true); } + foreach (glob($this->fsQueuePath . DS . '*') ?: [] as $file) { if (is_file($file)) { @unlink($file); } } + $this->clearUniqueCache(); JobAttributeReader::clearCache(); } @@ -72,6 +74,7 @@ protected function tearDown(): void @unlink($file); } } + $this->clearUniqueCache(); JobAttributeReader::clearCache(); parent::tearDown(); @@ -87,6 +90,7 @@ private function clearUniqueCache(): void $keys[] = $cacheKey; } } + foreach ($keys as $cacheKey) { try { Cache::clear($cacheKey); @@ -241,11 +245,13 @@ public function testPushExplicitConfigOptionWinsOverAttribute(): void if (!is_dir($otherPath)) { mkdir($otherPath, 0777, true); } + foreach (glob($otherPath . DS . '*') ?: [] as $file) { if (is_file($file)) { @unlink($file); } } + QueueManager::setConfig('test', [ 'url' => $this->fsUrl(), 'queue' => 'test', @@ -269,6 +275,7 @@ public function testPushExplicitConfigOptionWinsOverAttribute(): void @unlink($file); } } + @rmdir($otherPath); } }