Browse Source

Allow for table locator injection into Shell.

Robert Pustułka 8 years ago
parent
commit
186041be01
2 changed files with 22 additions and 4 deletions
  1. 5 3
      src/Console/Shell.php
  2. 17 1
      tests/TestCase/Console/ShellTest.php

+ 5 - 3
src/Console/Shell.php

@@ -21,7 +21,7 @@ use Cake\Datasource\ModelAwareTrait;
 use Cake\Filesystem\File;
 use Cake\Log\LogTrait;
 use Cake\ORM\Locator\LocatorAwareTrait;
-use Cake\ORM\Locator\TableLocator;
+use Cake\ORM\Locator\LocatorInterface;
 use Cake\Utility\Inflector;
 use Cake\Utility\MergeVariablesTrait;
 use Cake\Utility\Text;
@@ -175,17 +175,19 @@ class Shell
      * Constructs this Shell instance.
      *
      * @param \Cake\Console\ConsoleIo|null $io An io instance.
+     * @param \Cake\ORM\Locator\LocatorInterface|null $locator Table locator instance.
      * @link https://book.cakephp.org/3.0/en/console-and-shells.html#Shell
      */
-    public function __construct(ConsoleIo $io = null)
+    public function __construct(ConsoleIo $io = null, LocatorInterface $locator = null)
     {
         if (!$this->name) {
             list(, $class) = namespaceSplit(get_class($this));
             $this->name = str_replace(['Shell', 'Task'], '', $class);
         }
         $this->_io = $io ?: new ConsoleIo();
+        $this->_tableLocator = $locator;
 
-        $this->modelFactory('Table', [$this->getTableLocator() ?: new TableLocator(), 'get']);
+        $this->modelFactory('Table', [$this->getTableLocator(), 'get']);
         $this->Tasks = new TaskRegistry($this);
 
         $this->_mergeVars(

+ 17 - 1
tests/TestCase/Console/ShellTest.php

@@ -141,7 +141,7 @@ class ShellTest extends TestCase
         $this->io = $this->getMockBuilder('Cake\Console\ConsoleIo')
             ->disableOriginalConstructor()
             ->getMock();
-        $this->Shell = new ShellTestShell($this->io);
+        $this->Shell = new ShellTestShell($this->io, $this->getTableLocator());
 
         if (is_dir(TMP . 'shell_test')) {
             $Folder = new Folder(TMP . 'shell_test');
@@ -158,6 +158,22 @@ class ShellTest extends TestCase
     {
         $this->assertEquals('ShellTestShell', $this->Shell->name);
         $this->assertInstanceOf('Cake\Console\ConsoleIo', $this->Shell->io());
+        $this->assertInstanceOf('Cake\ORM\Locator\LocatorInterface', $this->Shell->getTableLocator());
+        $this->assertSame($this->io, $this->Shell->io());
+        $this->assertSame($this->getTableLocator(), $this->Shell->getTableLocator());
+    }
+
+    /**
+     * testConstruct method without args
+     *
+     * @return void
+     */
+    public function testConstructWithoutArgs()
+    {
+        $shell = new Shell();
+
+        $this->assertInstanceOf('Cake\Console\ConsoleIo', $shell->io());
+        $this->assertInstanceOf('Cake\ORM\Locator\LocatorInterface', $shell->getTableLocator());
     }
 
     /**