Kaynağa Gözat

允许直接使用model

jqh 5 yıl önce
ebeveyn
işleme
9ee9f5f25a

+ 1 - 1
resources/views/helpers/scaffold.blade.php

@@ -16,7 +16,7 @@
         'controller' => ucfirst(trans('admin.scaffold.create_controller')),
         'migrate' => ucfirst(trans('admin.scaffold.run_migrate')),
         'lang' => ucfirst(trans('admin.scaffold.create_lang')),
-    ])->checkedAll(['migrate', 'migration']);
+    ])->checkedAll(['migrate', 'repository', 'migration']);
 @endphp
 <style>
     /*.table>thead>tr>th {*/

+ 13 - 26
src/Admin.php

@@ -11,11 +11,13 @@ use Dcat\Admin\Layout\Menu;
 use Dcat\Admin\Layout\Navbar;
 use Dcat\Admin\Layout\SectionManager;
 use Dcat\Admin\Models\HasPermissions;
+use Dcat\Admin\Repositories\EloquentRepository;
 use Dcat\Admin\Repositories\Proxy;
 use Dcat\Admin\Support\Helper;
 use Dcat\Admin\Traits\HasAssets;
 use Illuminate\Auth\GuardHelpers;
 use Illuminate\Contracts\Auth\Authenticatable;
+use Illuminate\Database\Eloquent\Builder;
 use Illuminate\Database\Eloquent\Model;
 use Illuminate\Support\Facades\Auth;
 use Illuminate\Support\Facades\Event;
@@ -135,7 +137,7 @@ class Admin
      *
      * @return Form
      */
-    public static function form(Repository $repository, Closure $callable = null)
+    public static function form($repository, Closure $callable = null)
     {
         return new Form($repository, $callable);
     }
@@ -159,12 +161,8 @@ class Admin
      * @example
      *     $show = Admin::show();
      *
-     *     $show = Admin::show($id);
      *     $show = Admin::show(new Repository);
-     *     $show = Admin::show(function (Show $show) {});
      *
-     *     $show = Admin::show($id, new Repository);
-     *     $show = Admin::show($id, function (Show $show) {});
      *     $show = Admin::show(new Repository, function (Show $show) {});
      *
      *     $show = Admin::show($id, new Repository, function (Show $show) {});
@@ -182,28 +180,12 @@ class Admin
 
                 break;
             case 1:
-                if ($id instanceof \Closure) {
-                    $show = new Show(null, $id);
-                } elseif ($id instanceof Repository) {
-                    $show = new Show($id);
-                } else {
-                    $show = new Show();
-                    $show->key($id);
-                }
+                $show = new Show($id);
 
                 break;
             case 2:
-                if ($id instanceof Repository && $repository instanceof \Closure) {
-                    $show = new Show($id, $repository);
-                } elseif ($repository instanceof \Closure) {
-                    $show = new Show(null, $repository);
-
-                    $show->key($id);
-                } elseif ($repository instanceof Repository) {
-                    $show = new Show($repository);
+                $show = new Show($id, $repository);
 
-                    $show->key($id);
-                }
                 break;
             case 3:
                 $show = new Show($repository, $callable);
@@ -344,8 +326,8 @@ class Admin
     /**
      * Create a repository instance.
      *
-     * @param string $class
-     * @param array  $args
+     * @param string|Repository|Model|Builder $class
+     * @param array                   $args
      *
      * @return Repository
      */
@@ -355,8 +337,13 @@ class Admin
         if (is_string($repository)) {
             $repository = new $class($args);
         }
+
+        if ($repository instanceof Model || $repository instanceof Builder) {
+            $repository = EloquentRepository::make($repository);
+        }
+
         if (! $repository instanceof Repository) {
-            throw new \InvalidArgumentException("[$class] must be a valid repository class.");
+            throw new \InvalidArgumentException("The class [{$class}] must be a type of [".Repository::class.'].');
         }
 
         if ($repository instanceof Proxy) {

+ 0 - 1
src/Console/stubs/AuthController.stub

@@ -6,5 +6,4 @@ use Dcat\Admin\Controllers\AuthController as BaseAuthController;
 
 class AuthController extends BaseAuthController
 {
-
 }

+ 0 - 1
src/Console/stubs/extension/service-provider.stub

@@ -43,5 +43,4 @@ class :class_nameServiceProvider extends ServiceProvider
     public function register()
     {
     }
-
 }

+ 1 - 1
src/Controllers/ScaffoldController.php

@@ -109,7 +109,7 @@ class ScaffoldController extends Controller
             // 2. Create controller.
             if (in_array('controller', $creates)) {
                 $paths['controller'] = (new ControllerCreator($request->get('controller_name')))
-                    ->create($request->get('model_name'));
+                    ->create(in_array('repository', $creates) ? null : $request->get('model_name'));
             }
 
             // 3. Create migration.

+ 4 - 3
src/Form.php

@@ -15,6 +15,7 @@ use Dcat\Admin\Traits\HasFormResponse;
 use Dcat\Admin\Widgets\ModalForm;
 use Illuminate\Contracts\Support\MessageProvider;
 use Illuminate\Contracts\Support\Renderable;
+use Illuminate\Database\Eloquent\Model;
 use Illuminate\Http\Request;
 use Illuminate\Support\Arr;
 use Illuminate\Support\Collection;
@@ -272,10 +273,10 @@ class Form implements Renderable
     /**
      * Create a new form instance.
      *
-     * @param Repository $model
-     * @param \Closure   $callback
+     * @param Repository|Model|\Illuminate\Database\Eloquent\Builder|string $model
+     * @param \Closure                                                      $callback
      */
-    public function __construct(?Repository $repository = null, ?Closure $callback = null, Request $request = null)
+    public function __construct($repository = null, ?Closure $callback = null, Request $request = null)
     {
         $this->repository = $repository ? Admin::repository($repository) : null;
         $this->callback = $callback;

+ 4 - 3
src/Grid.php

@@ -15,6 +15,7 @@ use Dcat\Admin\Support\Helper;
 use Dcat\Admin\Traits\HasBuilderEvents;
 use Illuminate\Contracts\Support\Htmlable;
 use Illuminate\Contracts\Support\Renderable;
+use Illuminate\Database\Eloquent\Builder;
 use Illuminate\Support\Collection;
 use Illuminate\Support\Str;
 use Illuminate\Support\Traits\Macroable;
@@ -177,10 +178,10 @@ class Grid
      *
      * Grid constructor.
      *
-     * @param Repository|null $repository
-     * @param null|\Closure   $builder
+     * @param Repository|\Illuminate\Database\Eloquent\Model|Builder|null $repository
+     * @param null|\Closure                                       $builder
      */
-    public function __construct(?Repository $repository = null, ?\Closure $builder = null)
+    public function __construct($repository = null, ?\Closure $builder = null)
     {
         if ($repository) {
             $this->keyName($repository->getKeyName());

+ 3 - 3
src/Grid/Model.php

@@ -123,10 +123,10 @@ class Model
     /**
      * Create a new grid model instance.
      *
-     * @param Repository $repository
-     * @param Request    $request
+     * @param Repository|\Illuminate\Database\Eloquent\Model $repository
+     * @param Request                                        $request
      */
-    public function __construct(Request $request, ?Repository $repository = null)
+    public function __construct(Request $request, $repository = null)
     {
         if ($repository) {
             $this->repository = Admin::repository($repository);

+ 69 - 25
src/Repositories/EloquentRepository.php

@@ -15,7 +15,7 @@ use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Str;
 use Spatie\EloquentSortable\Sortable;
 
-abstract class EloquentRepository extends Repository
+class EloquentRepository extends Repository
 {
     /**
      * @var string
@@ -27,17 +27,51 @@ abstract class EloquentRepository extends Repository
      */
     protected $model;
 
-    protected $relations;
+    /**
+     * @var Builder
+     */
+    protected $queryBuilder;
 
-    public function __construct($relations = [])
+    /**
+     * @var array
+     */
+    protected $relations = [];
+
+    /**
+     * EloquentRepository constructor.
+     *
+     * @param EloquentModel|array|string $modelOrRelations $modelOrRelations
+     */
+    public function __construct($modelOrRelations = [])
+    {
+        $this->initModel($modelOrRelations);
+    }
+
+    /**
+     * Init model.
+     *
+     * @param EloquentModel|Builder|array|string $modelOrRelations
+     */
+    protected function initModel($modelOrRelations)
     {
+        if (is_string($modelOrRelations) && class_exists($modelOrRelations)) {
+            $this->eloquentClass = $modelOrRelations;
+        } elseif ($modelOrRelations instanceof EloquentModel) {
+            $this->eloquentClass = get_class($modelOrRelations);
+            $this->model = $modelOrRelations;
+        } elseif ($modelOrRelations instanceof Builder) {
+            $this->model = $modelOrRelations->getModel();
+            $this->eloquentClass = get_class($this->model);
+            $this->queryBuilder = $modelOrRelations;
+        } else {
+            $this->with($modelOrRelations);
+        }
+
         $this->setKeyName($this->eloquent()->getKeyName());
 
         $this->setIsSoftDeletes(
             in_array(SoftDeletes::class, class_uses($this->eloquent()))
         );
-
-        $this->with($relations);
     }
 
     /**
@@ -109,23 +143,23 @@ abstract class EloquentRepository extends Repository
      */
     public function get(Grid\Model $model)
     {
-        $eloquent = $this->eloquent();
+        $query = $this->newQuery();
 
         if ($this->relations) {
-            $eloquent = $eloquent->with($this->relations);
+            $query->with($this->relations);
         }
 
-        $model->getQueries()->unique()->each(function ($query) use (&$eloquent) {
-            if ($query['method'] == 'paginate') {
-                $query['arguments'][1] = $this->getGridColumns();
-            } elseif ($query['method'] == 'get') {
-                $query['arguments'] = $this->getGridColumns();
+        $model->getQueries()->unique()->each(function ($value) use (&$query) {
+            if ($value['method'] == 'paginate') {
+                $value['arguments'][1] = $this->getGridColumns();
+            } elseif ($value['method'] == 'get') {
+                $value['arguments'] = $this->getGridColumns();
             }
 
-            $eloquent = call_user_func_array([$eloquent, $query['method']], $query['arguments'] ?? []);
+            $query = call_user_func_array([$query, $value['method']], $value['arguments'] ?? []);
         });
 
-        return $eloquent;
+        return $query;
     }
 
     /**
@@ -137,13 +171,13 @@ abstract class EloquentRepository extends Repository
      */
     public function edit(Form $form): array
     {
-        $eloquent = $this->eloquent();
+        $query = $this->newQuery();
 
         if ($this->isSoftDeletes) {
-            $eloquent = $eloquent->withTrashed();
+            $query->withTrashed();
         }
 
-        $this->model = $eloquent
+        $this->model = $query
             ->with($this->getRelations($form))
             ->findOrFail($form->key(), $this->getFormColumns());
 
@@ -159,13 +193,13 @@ abstract class EloquentRepository extends Repository
      */
     public function detail(Show $show): array
     {
-        $eloquent = $this->eloquent();
+        $query = $this->newQuery();
 
         if ($this->isSoftDeletes) {
-            $eloquent = $eloquent->withTrashed();
+            $query->withTrashed();
         }
 
-        $this->model = $eloquent
+        $this->model = $query
             ->with($this->getRelations($show))
             ->findOrFail($show->key(), $this->getDetailColumns());
 
@@ -337,17 +371,15 @@ abstract class EloquentRepository extends Repository
      */
     public function getDataWhenDeleting(Form $form): array
     {
-        $model = $this->eloquent();
+        $query = $this->newQuery();
 
         if ($this->isSoftDeletes) {
-            $model = $model->withTrashed();
+            $query->withTrashed();
         }
 
-        $builder = $model->newQuery();
-
         $id = $form->key();
 
-        return $builder
+        return $query
             ->with($this->getRelations($form))
             ->findOrFail(
                 collect(explode(',', $id))->filter()->toArray(),
@@ -356,6 +388,18 @@ abstract class EloquentRepository extends Repository
             ->toArray();
     }
 
+    /**
+     * @return Builder
+     */
+    protected function newQuery()
+    {
+        if ($this->queryBuilder) {
+            return clone $this->queryBuilder;
+        }
+
+        return $this->eloquent()->newQuery();
+    }
+
     /**
      * Get the eloquent model.
      *

+ 1 - 1
src/Scaffold/ControllerCreator.php

@@ -59,7 +59,7 @@ class ControllerCreator
 
         $slug = str_replace('Controller', '', class_basename($this->name));
 
-        $model = 'App\Admin\Repositories\\'.$slug;
+        $model = $model ?: 'App\Admin\Repositories\\'.$slug;
 
         $this->files->put($path, $this->replace($stub, $this->name, $model, $slug));
 

+ 2 - 2
src/Scaffold/stubs/controller.stub

@@ -3,11 +3,11 @@
 namespace DummyNamespace;
 
 use DummyModelNamespace;
-use Dcat\Admin\Controllers\AdminController;
 use Dcat\Admin\Form;
 use Dcat\Admin\Grid;
 use Dcat\Admin\Show;
 use Dcat\Admin\Admin;
+use Dcat\Admin\Controllers\AdminController;
 
 class DummyClass extends AdminController
 {
@@ -34,6 +34,7 @@ class DummyClass extends AdminController
      * Make a show builder.
      *
      * @param mixed $id
+     *
      * @return Show
      */
     protected function detail($id)
@@ -54,5 +55,4 @@ class DummyClass extends AdminController
             {form}
         });
     }
-
 }

+ 0 - 1
src/Scaffold/stubs/repository.stub

@@ -13,5 +13,4 @@ class {controller} extends EloquentRepository
      * @var string
      */
     protected $eloquentClass = {model}Model::class;
-
 }

+ 12 - 2
src/Show.php

@@ -11,6 +11,7 @@ use Dcat\Admin\Show\Relation;
 use Dcat\Admin\Traits\HasBuilderEvents;
 use Illuminate\Contracts\Support\Arrayable;
 use Illuminate\Contracts\Support\Renderable;
+use Illuminate\Database\Eloquent\Builder;
 use Illuminate\Database\Eloquent\Model;
 use Illuminate\Support\Arr;
 use Illuminate\Support\Collection;
@@ -85,7 +86,7 @@ class Show implements Renderable
     /**
      * Show constructor.
      *
-     * @param Model|Repository|array|Arrayable $model
+     * @param Model|Builder|Repository|array|Arrayable $model
      * @param \Closure                         $builder
      */
     public function __construct($model = null, ?\Closure $builder = null)
@@ -102,8 +103,17 @@ class Show implements Renderable
 
     protected function initModel($model)
     {
-        if ($model instanceof Repository) {
+        if ($model instanceof Repository || $model instanceof Builder) {
             $this->repository = Admin::repository($model);
+        } elseif ($model instanceof Model) {
+            if ($key = $model->getKey()) {
+                $this->key = $model->getKey();
+                $this->keyName = $model->getKeyName();
+
+                $this->model(new Fluent($model->toArray()));
+            } else {
+                $this->repository = Admin::repository($model);
+            }
         } elseif ($model instanceof Arrayable) {
             $this->model(new Fluent($model->toArray()));
         } elseif (is_array($model)) {