Browse Source

Allow FactoryLocatory to use Datasource\LocatorInterface instances.

ADmad 5 years ago
parent
commit
63b7b3787d

+ 5 - 5
src/Datasource/FactoryLocator.php

@@ -27,7 +27,7 @@ class FactoryLocator
     /**
      * A list of model factory functions.
      *
-     * @var callable[]
+     * @var (callable|\Cake\Datasource\LocatorInterface)[]
      */
     protected static $_modelFactories = [];
 
@@ -35,10 +35,10 @@ class FactoryLocator
      * Register a 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 static function add(string $type, callable $factory): void
+    public static function add(string $type, $factory): void
     {
         static::$_modelFactories[$type] = $factory;
     }
@@ -59,9 +59,9 @@ class FactoryLocator
      *
      * @param string $type The repository type to get the factory for.
      * @throws \InvalidArgumentException If the specified repository type has no factory.
-     * @return callable The factory for the repository type.
+     * @return callable|\Cake\Datasource\LocatorInterface The factory for the repository type.
      */
-    public static function get(string $type): callable
+    public static function get(string $type)
     {
         if (!isset(static::$_modelFactories['Table'])) {
             static::$_modelFactories['Table'] = [TableRegistry::getTableLocator(), 'get'];

+ 7 - 1
src/Datasource/ModelAwareTrait.php

@@ -125,7 +125,13 @@ trait ModelAwareTrait
         if (!isset($factory)) {
             $factory = FactoryLocator::get($modelType);
         }
-        $this->{$alias} = $factory($modelClass, $options);
+
+        if ($factory instanceof LocatorInterface) {
+            $this->{$alias} = $factory->get($modelClass, $options);
+        } else {
+            $this->{$alias} = $factory($modelClass, $options);
+        }
+
         if (!$this->{$alias}) {
             throw new MissingModelException([$modelClass, $modelType]);
         }

+ 3 - 1
tests/TestCase/Datasource/FactoryLocatorTest.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\Stub\Stub;
@@ -32,7 +33,8 @@ class FactoryLocatorTest extends TestCase
      */
     public function testGet()
     {
-        $this->assertIsCallable(FactoryLocator::get('Table'));
+        $factory = FactoryLocator::get('Table');
+        $this->assertTrue(is_callable($factory) || $factory instanceof LocatorInterface);
     }
 
     /**