Browse Source

Allow ModelAwareTrait::modelFactory() to accept Datasource\LocatorInterface instance.

ADmad 5 years ago
parent
commit
259b17d2d3

+ 3 - 3
src/Datasource/ModelAwareTrait.php

@@ -46,7 +46,7 @@ trait ModelAwareTrait
     /**
      * A list of overridden model factory functions.
      *
-     * @var array
+     * @var (callable|\Cake\Datasource\LocatorInterface)[]
      */
     protected $_modelFactories = [];
 
@@ -143,10 +143,10 @@ trait ModelAwareTrait
      * Override a existing callable to generate repositories of a given type.
      *
      * @param string $type The name of the repository type the factory function is for.
-     * @param callable $factory The factory function used to create instances.
+     * @param callable|\Cake\Datasource\LocatorInterface $factory The factory function used to create instances.
      * @return void
      */
-    public function modelFactory(string $type, callable $factory): void
+    public function modelFactory(string $type, $factory): void
     {
         $this->_modelFactories[$type] = $factory;
     }

+ 13 - 0
tests/TestCase/Datasource/ModelAwareTraitTest.php

@@ -16,6 +16,7 @@ declare(strict_types=1);
 namespace Cake\Test\TestCase\Datasource;
 
 use Cake\Datasource\FactoryLocator;
+use Cake\Datasource\LocatorInterface;
 use Cake\Datasource\RepositoryInterface;
 use Cake\TestSuite\TestCase;
 use TestApp\Model\Table\PaginatorPostsTable;
@@ -127,6 +128,18 @@ class ModelAwareTraitTest extends TestCase
         $this->assertInstanceOf(RepositoryInterface::class, $result);
         $this->assertInstanceOf(RepositoryInterface::class, $stub->Magic);
         $this->assertSame('Magic', $stub->Magic->name);
+
+        $locator = $this->getMockBuilder(LocatorInterface::class)->getMock();
+        $mock2 = $this->getMockBuilder(RepositoryInterface::class)->getMock();
+        $mock2->alias = 'Foo';
+        $locator->expects($this->any())
+            ->method('get')
+            ->willReturn($mock2);
+
+        $stub->modelFactory('MyType', $locator);
+        $result = $stub->loadModel('Foo', 'MyType');
+        $this->assertInstanceOf(RepositoryInterface::class, $result);
+        $this->assertSame('Foo', $stub->Foo->alias);
     }
 
     /**