From d971436120b3dec44272c27620bd0303e7ef3d43 Mon Sep 17 00:00:00 2001 From: mrshaharb Date: Fri, 5 Aug 2022 18:11:37 +0300 Subject: [PATCH] Adding the option to execute task:run by class name (#46) --- Command/RunCommand.php | 18 ++++++++++++++++-- Tests/Command/RunCommandTest.php | 29 +++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/Command/RunCommand.php b/Command/RunCommand.php index 20d8ac9..6ed91fb 100644 --- a/Command/RunCommand.php +++ b/Command/RunCommand.php @@ -1,4 +1,5 @@ setName("ts:run") ->setDescription("Run due tasks") ->setHelp("This command actually run the tasks that are due at the moment the command is called.\nThis command should not be called manually. Check the documentation to learn how to set CRON jobs.") - ->addArgument("id", InputArgument::OPTIONAL, "The ID of the task. Check ts:list for IDs"); + ->addArgument("id", InputArgument::OPTIONAL, "The ID of the task. Check ts:list for IDs") + ->addOption("class", "c", InputOption::VALUE_OPTIONAL, "the class name of the task (without namespace)"); } protected function execute(InputInterface $input, OutputInterface $output): int { $id = $input->getArgument("id"); + $class = $input->getOption("class"); + - if (!$id) { + if (!$id && !$class) { $this->scheduler->run(); + } elseif ($class) { + $tasks = $this->scheduler->getTasks(); + foreach ($tasks as $task) { + if (strpos(get_class($task), "\\$class")) { + $this->scheduler->runTask($task); + return 0; + } + } + throw new \Exception("There are no tasks corresponding to this class name"); } else { $tasks = $this->scheduler->getTasks(); $id = (int)$id; diff --git a/Tests/Command/RunCommandTest.php b/Tests/Command/RunCommandTest.php index 6e74601..33164b6 100644 --- a/Tests/Command/RunCommandTest.php +++ b/Tests/Command/RunCommandTest.php @@ -64,6 +64,35 @@ public function testRunCommandWithId(): void "id" => 1, ]); + $this->assertEquals(1, TaskMock::$runCount); + $this->assertEquals(1, $t1->localCount); + $this->assertEquals(0, $t2->localCount); + } + + public function testRunCommandWithClassName(): void + { + $container = $this->loadContainer(); + + /** @var Scheduler $scheduler */ + $scheduler = $container->get("ts.scheduler"); + + $t1 = new TaskMock(); + $t2 = new TaskMock(); + + $scheduler->addTask($t1); + $scheduler->addTask($t2); + + $application = new Application(); + $application->add(new RunCommand($scheduler)); + $command = $application->find("ts:run"); + + $commandTester = new CommandTester($command); + $commandTester->execute([ + "command" => $command->getName(), + "--class" => "TaskMock", + ]); + + $this->assertEquals(1, TaskMock::$runCount); $this->assertEquals(1, $t1->localCount); $this->assertEquals(0, $t2->localCount);