diff --git a/src/Illuminate/Auth/Access/Gate.php b/src/Illuminate/Auth/Access/Gate.php index 9397f05b7dcd..a70a8109282e 100644 --- a/src/Illuminate/Auth/Access/Gate.php +++ b/src/Illuminate/Auth/Access/Gate.php @@ -108,6 +108,30 @@ public function define($ability, $callback) return $this; } + /** + * Define abilities for a resource. + * + * @param string $name + * @param string $class + * @param array $abilities + * @return $this + */ + public function resource($name, $class, array $abilities = null) + { + $abilities = $abilities ?: [ + 'view' => 'view', + 'create' => 'create', + 'update' => 'update', + 'delete' => 'delete', + ]; + + foreach ($abilities as $ability => $method) { + $this->define($name . '.' . $ability, $class . '@' . $method); + } + + return $this; + } + /** * Create the ability callback for a callback string. * diff --git a/tests/Auth/AuthAccessGateTest.php b/tests/Auth/AuthAccessGateTest.php index 7be64e0f2549..ecf407e3c5ca 100644 --- a/tests/Auth/AuthAccessGateTest.php +++ b/tests/Auth/AuthAccessGateTest.php @@ -35,6 +35,35 @@ public function test_basic_closures_can_be_defined() $this->assertFalse($gate->check('bar')); } + public function test_resource_gates_can_be_defined() + { + $gate = $this->getBasicGate(); + + $gate->resource('test', AccessGateTestResource::class); + + $dummy = new AccessGateTestDummy; + + $this->assertTrue($gate->check('test.view')); + $this->assertTrue($gate->check('test.create')); + $this->assertTrue($gate->check('test.update', $dummy)); + $this->assertTrue($gate->check('test.delete', $dummy)); + } + + public function test_custom_resource_gates_can_be_defined() + { + $gate = $this->getBasicGate(); + + $abilities = [ + 'ability1' => 'foo', + 'ability2' => 'bar', + ]; + + $gate->resource('test', AccessGateTestCustomResource::class, $abilities); + + $this->assertTrue($gate->check('test.ability1')); + $this->assertTrue($gate->check('test.ability2')); + } + public function test_before_callbacks_can_override_result_if_necessary() { $gate = $this->getBasicGate(); @@ -343,3 +372,39 @@ public function update($user, AccessGateTestDummy $dummy) return false; } } + +class AccessGateTestResource +{ + public function view($user) + { + return true; + } + + public function create($user) + { + return true; + } + + public function update($user, AccessGateTestDummy $dummy) + { + return true; + } + + public function delete($user, AccessGateTestDummy $dummy) + { + return true; + } +} + +class AccessGateTestCustomResource +{ + public function foo($user) + { + return true; + } + + public function bar($user) + { + return true; + } +}