Last active
October 20, 2021 10:02
-
-
Save marijoo/5f9ec32670c872ed5e8ea11d39a4a6e4 to your computer and use it in GitHub Desktop.
This allows to assert against the Laravel Gate by providing a simple array with policy methods.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Tests\Traits; | |
use App\User; | |
use Illuminate\Support\Facades\Gate; | |
use ReflectionMethod; | |
trait AssertsPolicy | |
{ | |
protected function assertGateMethod(string $name, bool $accessible = true, ...$params): void | |
{ | |
$assertion = $accessible ? 'assertTrue' : 'assertFalse'; | |
if (!$params) { | |
$method = new ReflectionMethod(Gate::getPolicyFor($this->model), $name); | |
$params = [$this->model]; | |
if ($method->getNumberOfParameters() === 2) { | |
$params[] = $this->model::factory()->create(); | |
} | |
} | |
$this->{$assertion}( | |
Gate::check($name, $params) | |
); | |
} | |
protected function assertGateMethods(array $methods, bool $accessible): void | |
{ | |
foreach ($methods as $name => $params) { | |
if (is_bool($params)) { | |
$this->assertGateMethod($name, $params); | |
continue; | |
} | |
if (!is_array($params)) { | |
$this->assertGateMethod($params, $accessible); | |
continue; | |
} | |
$this->assertGateMethod($name, $accessible, ...$params); | |
} | |
} | |
protected function assertUserCan(array $methods, ?User $user = null): void | |
{ | |
if ($user) { | |
$this->actingAs($user); | |
} | |
$this->assertGateMethods($methods, true); | |
} | |
protected function assertUserCannot(array $methods, ?User $user = null): void | |
{ | |
if ($user) { | |
$this->actingAs($user); | |
} | |
$this->assertGateMethods($methods, false); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment