Browse Source

Add abort() to Command.

Messages can be handled in the command via the `$io` object. I thought
it was a bit silly to pass in ConsoleIo so that a message could be printed using it.
Mark Story 8 years ago
parent
commit
f7b3619838
2 changed files with 38 additions and 0 deletions
  1. 12 0
      src/Console/Command.php
  2. 26 0
      tests/TestCase/Console/CommandTest.php

+ 12 - 0
src/Console/Command.php

@@ -15,6 +15,7 @@
 namespace Cake\Console;
 
 use Cake\Console\Exception\ConsoleException;
+use Cake\Console\Exception\StopException;
 use Cake\Datasource\ModelAwareTrait;
 use Cake\Log\LogTrait;
 use Cake\ORM\Locator\LocatorAwareTrait;
@@ -233,4 +234,15 @@ class Command
     {
         return null;
     }
+
+    /**
+     * Halt the the current process with a StopException.
+     *
+     * @param int $code The exit code to use.
+     * @throws \Cake\Console\Exception\ConsoleException
+     */
+    public function abort($code = self::CODE_ERROR)
+    {
+        throw new StopException('Command aborted', $code);
+    }
 }

+ 26 - 0
tests/TestCase/Console/CommandTest.php

@@ -235,6 +235,32 @@ class CommandTest extends TestCase
         $this->assertContains('Error: Missing required arguments. name is required', $messages);
     }
 
+    /**
+     * Test abort()
+     *
+     * @expectedException \Cake\Console\Exception\StopException
+     * @expectedExceptionCode 1
+     * @return void
+     */
+    public function testAbort()
+    {
+        $command = new Command();
+        $command->abort();
+    }
+
+    /**
+     * Test abort()
+     *
+     * @expectedException \Cake\Console\Exception\StopException
+     * @expectedExceptionCode 99
+     * @return void
+     */
+    public function testAbortCustomCode()
+    {
+        $command = new Command();
+        $command->abort(99);
+    }
+
     protected function getMockIo($output)
     {
         $io = $this->getMockBuilder(ConsoleIo::class)