Skip to content

Commit

Permalink
- Added actingAsApiAdmin to test helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
dash8x committed Mar 18, 2024
1 parent 4e02b45 commit 21c03b2
Showing 1 changed file with 53 additions and 15 deletions.
68 changes: 53 additions & 15 deletions src/Testing/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -186,29 +186,53 @@ protected function actingAsAdmin(
$this->seedDatabase();

//find the user
$user = is_object($email) ? $email : $this->getActiveAdminUser($email, $role);

if ($permissions) {
// If input permission starts with *, then get all permissions for the model
if (is_string($permissions) && str($permissions)->startsWith('*')) {
$filter = str($permissions)->afterLast('*');
$permissions = Permission::query()
->where('model', $filter)
->pluck('name')
->toArray();
if (is_object($email)) {
$user = $email;

if ($permissions) {
$this->givePermissionTo($user, $permissions);
}

$this->givePermissionTo($user, $permissions);
} else {
$user = $this->getActiveAdminUser($email, $role, $permissions);
}

$this->actingAs($user, $guard);
}

/**
* Acting as a api admin user
*
* @param $email
* @param string $guard
*/
protected function actingAsApiAdmin(
$permissions = [],
$email = 'demo-admin@javaabu.com',
$role = 'test_role',
string $guard = 'api_admin',
$scopes = ['read', 'write']
)
{
$this->seedDatabase();

//find the user
if (is_object($email)) {
$user = $email;

if ($permissions) {
$this->givePermissionTo($user, $permissions);
}
} else {
$user = $this->getActiveAdminUser($email, $role, $permissions);
}

$this->actingAsApiUser($user, $scopes, $guard);
}

/**
* Get active user
*/
protected function getActiveAdminUser($email, $role = 'test_role'): User
protected function getActiveAdminUser($email, $role = 'test_role', $permissions = []): User
{
// find the user
$user = User::whereEmail($email)->first();
Expand All @@ -229,6 +253,10 @@ protected function getActiveAdminUser($email, $role = 'test_role'): User
$user->assignRole($role);
}

if ($permissions) {
$this->givePermissionTo($user, $permissions);
}

return $user;
}

Expand Down Expand Up @@ -273,11 +301,21 @@ protected function revokePermissionTo($user, $permission)
* @param $user
* @param $permission
*/
protected function givePermissionTo($user, $permission)
protected function givePermissionTo($user, $permissions)
{
// If input permission starts with *, then get all permissions for the model
if (is_string($permissions) && str($permissions)->startsWith('*')) {
$filter = str($permissions)->afterLast('*');
$permissions = Permission::query()
->where('model', $filter)
->pluck('name')
->toArray();

}

$user->roles()
->first()
->givePermissionTo($permission);
->givePermissionTo($permissions);
}

protected function getFactory($class): Factory
Expand Down

0 comments on commit 21c03b2

Please sign in to comment.