Browse Source

Allow using FQCN with ModelAwareTrait::loadModel().

Refs #13069.
ADmad 7 years ago
parent
commit
1db77de391

+ 16 - 3
src/Datasource/ModelAwareTrait.php

@@ -77,7 +77,8 @@ trait ModelAwareTrait
      * If a repository provider does not return an object a MissingModelException will
      * be thrown.
      *
-     * @param string|null $modelClass Name of model class to load. Defaults to $this->modelClass
+     * @param string|null $modelClass Name of model class to load. Defaults to $this->modelClass.
+     *  The name can be an alias like `'Post'` or FQCN like `App\Model\Table\PostsTable::class`.
      * @param string|null $modelType The type of repository to load. Defaults to the modelType() value.
      * @return \Cake\Datasource\RepositoryInterface The model instance created.
      * @throws \Cake\Datasource\Exception\MissingModelException If the model class cannot be found.
@@ -97,7 +98,19 @@ trait ModelAwareTrait
             }
         }
 
-        list(, $alias) = pluginSplit($modelClass, true);
+        $alias = null;
+        $options = [];
+        if (strpos($modelClass, '\\') === false) {
+            list(, $alias) = pluginSplit($modelClass, true);
+        } else {
+            $options['className'] = $modelClass;
+            $alias = substr(
+                $modelClass,
+                strrpos($modelClass, '\\') + 1,
+                -strlen($modelType)
+            );
+            $modelClass = $alias;
+        }
 
         if (isset($this->{$alias})) {
             return $this->{$alias};
@@ -109,7 +122,7 @@ trait ModelAwareTrait
         if (!isset($factory)) {
             $factory = FactoryLocator::get($modelType);
         }
-        $this->{$alias} = $factory($modelClass);
+        $this->{$alias} = $factory($modelClass, $options);
         if (!$this->{$alias}) {
             throw new MissingModelException([$modelClass, $modelType]);
         }

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

@@ -16,6 +16,7 @@ namespace Cake\Test\TestCase\Datasource;
 use Cake\Datasource\FactoryLocator;
 use Cake\Datasource\ModelAwareTrait;
 use Cake\TestSuite\TestCase;
+use TestApp\Model\Table\PaginatorPostsTable;
 
 /**
  * Testing stub.
@@ -69,6 +70,11 @@ class ModelAwareTraitTest extends TestCase
         $result = $stub->loadModel('Comments');
         $this->assertInstanceOf('Cake\ORM\Table', $result);
         $this->assertInstanceOf('Cake\ORM\Table', $stub->Comments);
+
+        $result = $stub->loadModel(PaginatorPostsTable::class);
+        $this->assertInstanceOf(PaginatorPostsTable::class, $result);
+        $this->assertInstanceOf(PaginatorPostsTable::class, $stub->PaginatorPosts);
+        $this->assertSame('PaginatorPosts', $result->getAlias());
     }
 
     /**