From 89b296b58b1fd8cd4a1c0e3993f091b5322caaf8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20HULARD?= Date: Sun, 12 Feb 2017 11:27:04 +0100 Subject: [PATCH] Handle model instance in Authorize middleware. This will help extending Middleware capabilities by giving it directly the Model to check. Implementation example : ```php route('command')) && $command instanceof Model ) { return parent::handle($request, $next, 'access', $command); } return $next($request); } } ``` --- src/Illuminate/Auth/Middleware/Authorize.php | 5 ++++- tests/Auth/AuthorizeMiddlewareTest.php | 22 ++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/Illuminate/Auth/Middleware/Authorize.php b/src/Illuminate/Auth/Middleware/Authorize.php index 0cc0f7d6bc17..b7ffb883c156 100644 --- a/src/Illuminate/Auth/Middleware/Authorize.php +++ b/src/Illuminate/Auth/Middleware/Authorize.php @@ -4,6 +4,7 @@ use Closure; use Illuminate\Contracts\Auth\Access\Gate; +use Illuminate\Database\Eloquent\Model; use Illuminate\Contracts\Auth\Factory as Auth; class Authorize @@ -70,7 +71,9 @@ protected function getGateArguments($request, $models) } return collect($models)->map(function ($model) use ($request) { - return $this->getModel($request, $model); + return $model instanceof Model + ?$model + :$this->getModel($request, $model); })->all(); } diff --git a/tests/Auth/AuthorizeMiddlewareTest.php b/tests/Auth/AuthorizeMiddlewareTest.php index 511a17e3fdb7..9d803b0faea9 100644 --- a/tests/Auth/AuthorizeMiddlewareTest.php +++ b/tests/Auth/AuthorizeMiddlewareTest.php @@ -187,6 +187,28 @@ public function testModelAuthorized() $this->assertEquals($response->content(), 'success'); } + public function testModelInstanceAsParameter() + { + $instance = m::mock(\Illuminate\Database\Eloquent\Model::class); + + $this->gate()->define('success', function ($user, $model) use ($instance) { + $this->assertSame($model, $instance); + + return true; + }); + + $request = m::mock(Request::class); + + $nextParam = null; + + $next = function ($param) use (&$nextParam) { + $nextParam = $param; + }; + + (new Authorize($this->container->make(Auth::class), $this->gate())) + ->handle($request, $next, 'success', $instance); + } + /** * Get the Gate instance from the container. *