diff --git a/CHANGELOG.md b/CHANGELOG.md index 83ca004..29c4857 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,15 @@ All Notable changes to `laravel-permission-mongodb` will be documented in this file. +## 4.0.0 - 2022-05-15 + +### Added +- Support of Laravel 9.x +- Added some return toward PHP 8 transitioning to require return types +- Use of DatabaseMigration and Seeder in tests +- Fix some tests (api guard is no more in auth.php by default) + + ## 3.1.0 - 2020-10-04 ### Added diff --git a/README.md b/README.md index b292851..78d6806 100644 --- a/README.md +++ b/README.md @@ -72,15 +72,24 @@ $user->can('edit articles'); 6.x | 2.x or 3.x 7.x | 3.x 8.x | 3.1.x + 9.x | 4.x ### Laravel You can install the package via composer: +For laravel 9.x use + ``` bash composer require mostafamaklad/laravel-permission-mongodb ``` +For laravel 8.x and older use + +``` bash +composer require mostafamaklad/laravel-permission-mongodb:"^3.1" +``` + You can publish [the migration](database/migrations/create_permission_collections.php.stub) with: ```bash diff --git a/composer.json b/composer.json index 11a28b6..aa523eb 100644 --- a/composer.json +++ b/composer.json @@ -30,17 +30,17 @@ } ], "require": { - "php": ">=7.2", - "illuminate/auth": "^6.0|^7.0|^8.0", - "illuminate/container": "^6.0|^7.0|^8.0", - "illuminate/contracts": "^6.0|^7.0|^8.0", - "jenssegers/mongodb": "^3.0" + "php": "^8.0", + "illuminate/auth": "^9.0", + "illuminate/container": "^9.0", + "illuminate/contracts": "^9.0", + "jenssegers/mongodb": "^3.9" }, "require-dev": { - "monolog/monolog": "^1.23|^2.0", - "orchestra/testbench": "^3.2|^4.0|^5.0", - "phpunit/phpunit": "^5.7|^6.0|^7.0|^8.0", - "squizlabs/php_codesniffer": "^3.1" + "monolog/monolog": "^2.3", + "orchestra/testbench": "^7.0", + "phpunit/phpunit": "^9.5", + "squizlabs/php_codesniffer": "^3.6" }, "autoload": { "psr-4": { diff --git a/database/migrations/create_permission_collections.php.stub b/database/migrations/create_permission_collections.php.stub index f2dc863..d2f8382 100644 --- a/database/migrations/create_permission_collections.php.stub +++ b/database/migrations/create_permission_collections.php.stub @@ -4,7 +4,7 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Support\Facades\Schema; use Jenssegers\Mongodb\Schema\Blueprint; -class CreatePermissionCollections extends Migration +return new class extends Migration { /** * Run the migrations. @@ -33,7 +33,7 @@ class CreatePermissionCollections extends Migration { $collectionNames = config('permission.collection_names'); - Schema::drop($collectionNames['roles']); - Schema::drop($collectionNames['permissions']); + Schema::dropIfExists($collectionNames['roles']); + Schema::dropIfExists($collectionNames['permissions']); } -} +}; diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 1f0d1c0..cc7ec4c 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -9,21 +9,22 @@ convertWarningsToExceptions="true" processIsolation="false" stopOnFailure="false"> - - - tests - - - - - src/ - - - - - - - - - + + + src/ + + + + + + + + + + tests + + + + + diff --git a/src/Commands/CreatePermission.php b/src/Commands/CreatePermission.php index 021f741..6cdf78d 100644 --- a/src/Commands/CreatePermission.php +++ b/src/Commands/CreatePermission.php @@ -11,13 +11,13 @@ */ class CreatePermission extends Command { - protected $signature = 'permission:create-permission - {name : The name of the permission} + protected $signature = 'permission:create-permission + {name : The name of the permission} {guard? : The name of the guard}'; protected $description = 'Create a permission'; - public function handle() + public function handle(): void { $permissionClass = \app(\config('permission.models.permission')); diff --git a/src/Commands/CreateRole.php b/src/Commands/CreateRole.php index fd4e8ce..110cdaa 100644 --- a/src/Commands/CreateRole.php +++ b/src/Commands/CreateRole.php @@ -18,7 +18,7 @@ class CreateRole extends Command protected $description = 'Create a role'; - public function handle() + public function handle(): void { $roleClass = \app(\config('permission.models.role')); diff --git a/src/Contracts/RoleInterface.php b/src/Contracts/RoleInterface.php index cb86572..d3d641b 100644 --- a/src/Contracts/RoleInterface.php +++ b/src/Contracts/RoleInterface.php @@ -27,7 +27,7 @@ public function permissions(): BelongsToMany; * * @throws RoleDoesNotExist */ - public static function findByName(string $name, $guardName): RoleInterface; + public static function findByName(string $name, ?string $guardName): RoleInterface; /** * Determine if the user may perform the given permission. @@ -36,5 +36,5 @@ public static function findByName(string $name, $guardName): RoleInterface; * * @return bool */ - public function hasPermissionTo($permission): bool; + public function hasPermissionTo(string|PermissionInterface $permission): bool; } diff --git a/src/Directives/PermissionDirectives.php b/src/Directives/PermissionDirectives.php index 63f05b3..d100a7a 100644 --- a/src/Directives/PermissionDirectives.php +++ b/src/Directives/PermissionDirectives.php @@ -10,7 +10,7 @@ */ class PermissionDirectives { - private $bladeCompiler; + private BladeCompiler $bladeCompiler; public function __construct(BladeCompiler $bladeCompiler) { @@ -20,7 +20,7 @@ public function __construct(BladeCompiler $bladeCompiler) /** * Declare role directive */ - public function roleDirective() + public function roleDirective(): void { $this->bladeCompiler->directive('role', function ($arguments) { list($role, $guard) = $this->extractRoleGuard($arguments); @@ -36,7 +36,7 @@ public function roleDirective() /** * Declare hasrole directive */ - public function hasroleDirective() + public function hasroleDirective(): void { $this->bladeCompiler->directive('hasrole', function ($arguments) { list($role, $guard) = $this->extractRoleGuard($arguments); @@ -51,7 +51,7 @@ public function hasroleDirective() /** * Declare hasanyrole directive */ - public function hasanyroleDirective() + public function hasanyroleDirective(): void { $this->bladeCompiler->directive('hasanyrole', function ($arguments) { list($roles, $guard) = $this->extractRoleGuard($arguments); @@ -66,7 +66,7 @@ public function hasanyroleDirective() /** * Declare hasallroles directive */ - public function hasallrolesDirective() + public function hasallrolesDirective(): void { $this->bladeCompiler->directive('hasallroles', function ($arguments) { list($roles, $guard) = $this->extractRoleGuard($arguments); diff --git a/src/Exceptions/MakladException.php b/src/Exceptions/MakladException.php index 312c04a..5e50d15 100644 --- a/src/Exceptions/MakladException.php +++ b/src/Exceptions/MakladException.php @@ -14,7 +14,7 @@ class MakladException extends InvalidArgumentException /** * MakladException constructor. * - * @param string $message + * @param string|null $message * @param int $code * @param Throwable|null $previous */ diff --git a/src/Exceptions/UnauthorizedException.php b/src/Exceptions/UnauthorizedException.php index 5f53901..04d9251 100644 --- a/src/Exceptions/UnauthorizedException.php +++ b/src/Exceptions/UnauthorizedException.php @@ -10,14 +10,14 @@ */ class UnauthorizedException extends HttpException { - private $requiredRoles = []; - private $requiredPermissions = []; + private array $requiredRoles = []; + private array $requiredPermissions = []; /** * UnauthorizedException constructor. * * @param $statusCode - * @param string $message + * @param string|null $message * @param array $requiredRoles * @param array $requiredPermissions */ diff --git a/src/Exceptions/UnauthorizedPermission.php b/src/Exceptions/UnauthorizedPermission.php index 9154c1b..69ae3e3 100644 --- a/src/Exceptions/UnauthorizedPermission.php +++ b/src/Exceptions/UnauthorizedPermission.php @@ -12,7 +12,7 @@ class UnauthorizedPermission extends UnauthorizedException * UnauthorizedPermission constructor. * * @param $statusCode - * @param string $message + * @param string|null $message * @param array $requiredPermissions */ public function __construct($statusCode, string $message = null, array $requiredPermissions = []) diff --git a/src/Exceptions/UnauthorizedRole.php b/src/Exceptions/UnauthorizedRole.php index b34a252..f899a20 100644 --- a/src/Exceptions/UnauthorizedRole.php +++ b/src/Exceptions/UnauthorizedRole.php @@ -12,7 +12,7 @@ class UnauthorizedRole extends UnauthorizedException * UnauthorizedPermission constructor. * * @param $statusCode - * @param string $message + * @param string|null $message * @param array $requiredRoles */ public function __construct($statusCode, string $message = null, array $requiredRoles = []) diff --git a/src/Helpers.php b/src/Helpers.php index 693c6be..6e118ed 100644 --- a/src/Helpers.php +++ b/src/Helpers.php @@ -15,7 +15,7 @@ class Helpers * * @return string|null */ - public function getModelForGuard(string $guard) + public function getModelForGuard(string $guard): ?string { return \collect(\config('auth.guards')) ->map(function ($guard) { diff --git a/src/Middlewares/PermissionMiddleware.php b/src/Middlewares/PermissionMiddleware.php index 98d8492..8b542c3 100644 --- a/src/Middlewares/PermissionMiddleware.php +++ b/src/Middlewares/PermissionMiddleware.php @@ -3,6 +3,8 @@ namespace Maklad\Permission\Middlewares; use Closure; +use Illuminate\Http\Request; +use Maklad\Permission\Exceptions\UnauthorizedException; use Maklad\Permission\Exceptions\UnauthorizedPermission; use Maklad\Permission\Exceptions\UserNotLoggedIn; use Maklad\Permission\Helpers; @@ -14,14 +16,14 @@ class PermissionMiddleware { /** - * @param $request + * @param Request $request * @param Closure $next - * @param $permission + * @param array|string $permission * * @return mixed - * @throws \Maklad\Permission\Exceptions\UnauthorizedException + * @throws UnauthorizedException */ - public function handle($request, Closure $next, $permission) + public function handle(Request $request, Closure $next, array|string $permission): mixed { if (app('auth')->guest()) { $helpers = new Helpers(); diff --git a/src/Middlewares/RoleMiddleware.php b/src/Middlewares/RoleMiddleware.php index d9a965c..d5cb492 100644 --- a/src/Middlewares/RoleMiddleware.php +++ b/src/Middlewares/RoleMiddleware.php @@ -3,6 +3,7 @@ namespace Maklad\Permission\Middlewares; use Closure; +use Illuminate\Http\Request; use Maklad\Permission\Exceptions\UnauthorizedRole; use Maklad\Permission\Exceptions\UserNotLoggedIn; use Maklad\Permission\Helpers; @@ -14,14 +15,14 @@ class RoleMiddleware { /** - * @param $request + * @param Request $request * @param Closure $next - * @param $role + * @param array|string $role * * @return mixed * @throws \Maklad\Permission\Exceptions\UnauthorizedException */ - public function handle($request, Closure $next, $role) + public function handle(Request $request, Closure $next, array|string $role): mixed { if (app('auth')->guest()) { $helpers = new Helpers(); diff --git a/src/Models/Permission.php b/src/Models/Permission.php index b491eab..62e877f 100644 --- a/src/Models/Permission.php +++ b/src/Models/Permission.php @@ -24,7 +24,7 @@ class Permission extends Model implements PermissionInterface use RefreshesPermissionCache; public $guarded = ['id']; - protected $helpers; + protected Helpers $helpers; /** * Permission constructor. @@ -49,7 +49,7 @@ public function __construct(array $attributes = []) * * @param array $attributes * - * @return $this|\Illuminate\Database\Eloquent\Model + * @return $this|mixed * @throws \Maklad\Permission\Exceptions\PermissionAlreadyExists * @throws \ReflectionException */ @@ -74,7 +74,7 @@ public static function create(array $attributes = []) * Find or create permission by its name (and optionally guardName). * * @param string $name - * @param string $guardName + * @param string|null $guardName * * @return PermissionInterface * @throws \Maklad\Permission\Exceptions\PermissionAlreadyExists @@ -117,7 +117,7 @@ public function users(): BelongsToMany * Find a permission by its name (and optionally guardName). * * @param string $name - * @param string $guardName + * @param string|null $guardName * * @return PermissionInterface * @throws PermissionDoesNotExist diff --git a/src/Models/Role.php b/src/Models/Role.php index e4197ea..7f7d4d2 100644 --- a/src/Models/Role.php +++ b/src/Models/Role.php @@ -4,6 +4,7 @@ use Jenssegers\Mongodb\Eloquent\Model; use Jenssegers\Mongodb\Relations\BelongsToMany; +use Maklad\Permission\Contracts\PermissionInterface; use Maklad\Permission\Contracts\RoleInterface; use Maklad\Permission\Exceptions\GuardDoesNotMatch; use Maklad\Permission\Exceptions\RoleAlreadyExists; @@ -24,7 +25,7 @@ class Role extends Model implements RoleInterface use RefreshesPermissionCache; public $guarded = ['id']; - protected $helpers; + protected Helpers $helpers; /** * Role constructor. @@ -35,7 +36,7 @@ class Role extends Model implements RoleInterface */ public function __construct(array $attributes = []) { - $attributes['guard_name'] = $attributes['guard_name'] ?? (new Guard())->getDefaultName(static::class); + $attributes['guard_name'] ??= (new Guard())->getDefaultName(static::class); parent::__construct($attributes); @@ -47,7 +48,7 @@ public function __construct(array $attributes = []) /** * @param array $attributes * - * @return $this|Model + * @return $this|mixed * @throws RoleAlreadyExists * @internal param array $attributesĀ§ * @@ -55,7 +56,7 @@ public function __construct(array $attributes = []) */ public static function create(array $attributes = []) { - $attributes['guard_name'] = $attributes['guard_name'] ?? (new Guard())->getDefaultName(static::class); + $attributes['guard_name'] ??= (new Guard())->getDefaultName(static::class); $helpers = new Helpers(); if (static::where('name', $attributes['name'])->where('guard_name', $attributes['guard_name'])->first()) { @@ -77,7 +78,7 @@ public static function create(array $attributes = []) * @throws \Maklad\Permission\Exceptions\RoleAlreadyExists * @throws \ReflectionException */ - public static function findOrCreate(string $name, $guardName = null): RoleInterface + public static function findOrCreate(string $name, string $guardName = null): RoleInterface { $guardName = $guardName ?? (new Guard())->getDefaultName(static::class); @@ -102,7 +103,7 @@ public static function findOrCreate(string $name, $guardName = null): RoleInterf * @throws RoleDoesNotExist * @throws \ReflectionException */ - public static function findByName(string $name, $guardName = null): RoleInterface + public static function findByName(string $name, string $guardName = null): RoleInterface { $guardName = $guardName ?? (new Guard())->getDefaultName(static::class); @@ -137,7 +138,7 @@ public function users(): BelongsToMany * @throws GuardDoesNotMatch * @throws ReflectionException */ - public function hasPermissionTo($permission): bool + public function hasPermissionTo(string|PermissionInterface $permission): bool { if (\is_string($permission)) { $permission = $this->getPermissionClass()->findByName($permission, $this->getDefaultGuardName()); diff --git a/src/PermissionRegistrar.php b/src/PermissionRegistrar.php index 5a990a0..cf4ee48 100644 --- a/src/PermissionRegistrar.php +++ b/src/PermissionRegistrar.php @@ -5,6 +5,7 @@ use Illuminate\Contracts\Auth\Access\Authorizable; use Illuminate\Contracts\Auth\Access\Gate; use Illuminate\Contracts\Cache\Repository; +use Illuminate\Foundation\Application; use Illuminate\Support\Collection; use Maklad\Permission\Contracts\PermissionInterface as Permission; @@ -14,20 +15,15 @@ */ class PermissionRegistrar { - /** @var \Illuminate\Contracts\Auth\Access\Gate */ - protected $gate; + protected Gate $gate; - /** @var \Illuminate\Contracts\Cache\Repository */ - protected $cache; + protected Repository $cache; - /** @var string */ - protected $cacheKey = 'maklad.permission.cache'; + protected string $cacheKey = 'maklad.permission.cache'; - /** @var string */ - protected $permissionClass; + protected mixed $permissionClass; - /** @var string */ - protected $roleClass; + protected mixed $roleClass; /** * PermissionRegistrar constructor. @@ -61,7 +57,7 @@ public function registerPermissions(): bool /** * Forget cached permission */ - public function forgetCachedPermissions() + public function forgetCachedPermissions(): void { $this->cache->forget($this->cacheKey); } @@ -81,9 +77,9 @@ public function getPermissions(): Collection /** * Get Permission class * - * @return \Illuminate\Foundation\Application|mixed + * @return Application|mixed */ - public function getPermissionClass() + public function getPermissionClass(): mixed { return app($this->permissionClass); } @@ -91,9 +87,9 @@ public function getPermissionClass() /** * Get Role class * - * @return \Illuminate\Foundation\Application|mixed + * @return Application|mixed */ - public function getRoleClass() + public function getRoleClass(): mixed { return app($this->roleClass); } diff --git a/src/Traits/HasPermissions.php b/src/Traits/HasPermissions.php index cba70ab..303bb23 100644 --- a/src/Traits/HasPermissions.php +++ b/src/Traits/HasPermissions.php @@ -12,6 +12,8 @@ use Maklad\Permission\Helpers; use Maklad\Permission\Models\Role; use Maklad\Permission\PermissionRegistrar; +use Monolog\Handler\StreamHandler; +use Monolog\Logger; /** * Trait HasPermissions @@ -121,7 +123,7 @@ public function revokePermissionTo(...$permissions): self * @return Permission * @throws \ReflectionException */ - protected function getStoredPermission($permission): Permission + protected function getStoredPermission(string|Permission $permission): Permission { if (\is_string($permission)) { return $this->getPermissionClass()->findByName($permission, $this->getDefaultGuardName()); @@ -136,7 +138,7 @@ protected function getStoredPermission($permission): Permission * @throws GuardDoesNotMatch * @throws \ReflectionException */ - protected function ensureModelSharesGuard(Model $roleOrPermission) + protected function ensureModelSharesGuard(Model $roleOrPermission): void { if (! $this->getGuardNames()->contains($roleOrPermission->guard_name)) { $expected = $this->getGuardNames(); @@ -168,7 +170,7 @@ protected function getDefaultGuardName(): string /** * Forget the cached permissions. */ - public function forgetCachedPermissions() + public function forgetCachedPermissions(): void { app(PermissionRegistrar::class)->forgetCachedPermissions(); } @@ -176,11 +178,11 @@ public function forgetCachedPermissions() /** * Convert to Permission Models * - * @param string|array|Collection $permissions + * @param mixed $permissions * * @return Collection */ - private function convertToPermissionModels($permissions): Collection + private function convertToPermissionModels(mixed $permissions): Collection { if (\is_array($permissions)) { $permissions = collect($permissions); @@ -190,11 +192,9 @@ private function convertToPermissionModels($permissions): Collection $permissions = collect([$permissions]); } - $permissions = $permissions->map(function ($permission) { + return $permissions->map(function ($permission) { return $this->getStoredPermission($permission); }); - - return $permissions; } /** @@ -238,7 +238,7 @@ public function getAllPermissions(): Collection * @return bool * @throws \ReflectionException */ - public function hasPermissionTo($permission, $guardName = null): bool + public function hasPermissionTo(string|Permission $permission, string $guardName = null): bool { if (\is_string($permission)) { $permission = $this->getPermissionClass()->findByName( @@ -314,7 +314,7 @@ protected function hasPermissionViaRole(Permission $permission): bool * @return bool * @throws \ReflectionException */ - public function hasDirectPermission($permission): bool + public function hasDirectPermission(string|Permission $permission): bool { if (\is_string($permission)) { $permission = $this->getPermissionClass()->findByName($permission, $this->getDefaultGuardName()); @@ -335,11 +335,11 @@ public function getDirectPermissions(): Collection * Scope the model query to certain permissions only. * * @param Builder $query - * @param string|array|\Maklad\Permission\Contracts\PermissionInterface|Collection $permissions + * @param array|string|\Maklad\Permission\Contracts\PermissionInterface|Collection $permissions * * @return Builder */ - public function scopePermission(Builder $query, $permissions): Builder + public function scopePermission(Builder $query, array|string|Collection|Permission $permissions): Builder { $permissions = $this->convertToPermissionModels($permissions); diff --git a/src/Traits/HasRoles.php b/src/Traits/HasRoles.php index 3837648..899e06f 100644 --- a/src/Traits/HasRoles.php +++ b/src/Traits/HasRoles.php @@ -51,11 +51,11 @@ public function roles() * Scope the model query to certain roles only. * * @param Builder $query - * @param string|array|Role|Collection $roles + * @param array|string|Collection|Role $roles * * @return Builder */ - public function scopeRole(Builder $query, $roles): Builder + public function scopeRole(Builder $query, Role|array|string|Collection $roles): Builder { $roles = $this->convertToRoleModels($roles); @@ -69,7 +69,7 @@ public function scopeRole(Builder $query, $roles): Builder * * @return array|Role|string */ - public function assignRole(...$roles) + public function assignRole(...$roles): array|Role|string { $roles = \collect($roles) ->flatten() @@ -95,7 +95,7 @@ public function assignRole(...$roles) * * @return array|Role|string */ - public function removeRole(...$roles) + public function removeRole(...$roles): array|Role|string { \collect($roles) ->flatten() @@ -118,7 +118,7 @@ public function removeRole(...$roles) * * @return array|Role|string */ - public function syncRoles(...$roles) + public function syncRoles(...$roles): array|Role|string { $this->roles()->sync([]); @@ -128,11 +128,11 @@ public function syncRoles(...$roles) /** * Determine if the model has (one of) the given role(s). * - * @param string|array|Role|\Illuminate\Support\Collection $roles + * @param array|string|Collection|Role $roles * * @return bool */ - public function hasRole($roles): bool + public function hasRole(Role|array|string|Collection $roles): bool { if (\is_string($roles) && false !== \strpos($roles, '|')) { $roles = \explode('|', $roles); @@ -152,11 +152,11 @@ public function hasRole($roles): bool /** * Determine if the model has any of the given role(s). * - * @param string|array|Role|\Illuminate\Support\Collection $roles + * @param array|string|Collection|Role $roles * * @return bool */ - public function hasAnyRole($roles): bool + public function hasAnyRole(Role|array|string|Collection $roles): bool { return $this->hasRole($roles); } @@ -189,7 +189,7 @@ public function hasAllRoles(...$roles): bool * @return Role * @throws ReflectionException */ - protected function getStoredRole($role): Role + protected function getStoredRole(Role|string $role): Role { if (\is_string($role)) { return $this->getRoleClass()->findByName($role, $this->getDefaultGuardName()); diff --git a/tests/CacheTest.php b/tests/CacheTest.php index 897cea3..67615ff 100644 --- a/tests/CacheTest.php +++ b/tests/CacheTest.php @@ -9,7 +9,7 @@ class CacheTest extends TestCase { - protected $registrar; + protected mixed $registrar; public function setUp(): void { diff --git a/tests/HasPermissionsTest.php b/tests/HasPermissionsTest.php index c1de8cc..6ace968 100644 --- a/tests/HasPermissionsTest.php +++ b/tests/HasPermissionsTest.php @@ -6,6 +6,7 @@ use Maklad\Permission\Exceptions\PermissionDoesNotExist; use Maklad\Permission\Models\Permission; use Maklad\Permission\Models\Role; +use Monolog\Handler\StreamHandler; use Monolog\Logger; class HasPermissionsTest extends TestCase @@ -52,7 +53,7 @@ public function it_throws_an_exception_when_assigning_a_permission_to_a_user_fro $this->testUser->givePermissionTo($this->testAdminPermission); } finally { - $message = $this->helpers->getGuardDoesNotMatchMessage(collect(['web', 'api']), 'admin'); + $message = $this->helpers->getGuardDoesNotMatchMessage(collect(['web']), 'admin'); $this->assertLogMessage($message, Logger::ALERT); } } diff --git a/tests/HasRolesTest.php b/tests/HasRolesTest.php index 3cb343f..1085b4a 100644 --- a/tests/HasRolesTest.php +++ b/tests/HasRolesTest.php @@ -110,7 +110,7 @@ public function it_throws_an_exception_when_assigning_a_role_from_a_different_gu $this->testUser->assignRole($this->testAdminRole); } finally { - $message = $this->helpers->getGuardDoesNotMatchMessage(collect(['web', 'api']), 'admin'); + $message = $this->helpers->getGuardDoesNotMatchMessage(collect(['web']), 'admin'); $this->assertLogMessage($message, Logger::ALERT); } } @@ -175,7 +175,7 @@ public function it_throws_an_exception_when_syncing_a_role_from_another_guard() $this->testUser->syncRoles('testRole', $this->testAdminRole); } finally { - $message = $this->helpers->getGuardDoesNotMatchMessage(collect(['web', 'api']), 'admin'); + $message = $this->helpers->getGuardDoesNotMatchMessage(collect(['web']), 'admin'); $this->assertLogMessage($message, Logger::ALERT); } } diff --git a/tests/MiddlewareTest.php b/tests/MiddlewareTest.php index 6e7320f..d46496a 100644 --- a/tests/MiddlewareTest.php +++ b/tests/MiddlewareTest.php @@ -12,8 +12,8 @@ class MiddlewareTest extends TestCase { - protected $roleMiddleware; - protected $permissionMiddleware; + protected RoleMiddleware $roleMiddleware; + protected PermissionMiddleware $permissionMiddleware; public function setUp(): void { diff --git a/tests/SoftDeletingUser.php b/tests/SoftDeletingUser.php index aec02c9..837b97c 100644 --- a/tests/SoftDeletingUser.php +++ b/tests/SoftDeletingUser.php @@ -8,5 +8,5 @@ class SoftDeletingUser extends User { use SoftDeletes; - protected $guard_name = 'web'; + protected string $guard_name = 'web'; } diff --git a/tests/TestCase.php b/tests/TestCase.php index a742fdb..0d528bf 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -2,63 +2,63 @@ namespace Maklad\Permission\Test; +use Illuminate\Foundation\Application; +use Illuminate\Foundation\Testing\DatabaseMigrations; use Jenssegers\Mongodb\MongodbServiceProvider; use Maklad\Permission\Helpers; use Maklad\Permission\Models\Permission; use Maklad\Permission\Models\Role; use Maklad\Permission\PermissionRegistrar; use Maklad\Permission\PermissionServiceProvider; +use Monolog\Handler\StreamHandler; use Monolog\Handler\TestHandler; use Orchestra\Testbench\TestCase as Orchestra; abstract class TestCase extends Orchestra { - protected $helpers; + use DatabaseMigrations; + protected Helpers $helpers; + + protected string $seeder = TestSeeder::class; /** * Flush the database after each test function */ public function tearDown(): void { - User::truncate(); - Admin::truncate(); + User::query()->truncate(); + Admin::query()->truncate(); $this->app[Role::class]::truncate(); $this->app[Permission::class]::truncate(); } - /** @var \Maklad\Permission\Test\User */ - protected $testUser; + protected User $testUser; - /** @var \Maklad\Permission\Test\Admin */ - protected $testAdmin; + protected Admin $testAdmin; - /** @var \Maklad\Permission\Models\Role */ - protected $testUserRole; + protected Role $testUserRole; - /** @var \Maklad\Permission\Models\Role */ - protected $testAdminRole; + protected Role $testAdminRole; - /** @var \Maklad\Permission\Models\Permission */ - protected $testUserPermission; + protected Permission $testUserPermission; - /** @var \Maklad\Permission\Models\Permission */ - protected $testAdminPermission; + protected Permission $testAdminPermission; public function setUp(): void { parent::setUp(); - $this->setUpDatabase($this->app); + // $this->setUpDatabase($this->app); $this->reloadPermissions(); $this->testUser = User::first(); - $this->testUserRole = \app(\config('permission.models.role'))->where('name', 'testRole')->first(); - $this->testUserPermission = \app(\config('permission.models.permission'))->where('name', 'edit-articles')->first(); + $this->testUserRole = app(config('permission.models.role'))->where('name', 'testRole')->first(); + $this->testUserPermission = app(config('permission.models.permission'))->where('name', 'edit-articles')->first(); $this->testAdmin = Admin::first(); - $this->testAdminRole = \app(\config('permission.models.role'))->where('name', 'testAdminRole')->first(); - $this->testAdminPermission = \app(\config('permission.models.permission'))->where('name', 'admin-permission')->first(); + $this->testAdminRole = app(config('permission.models.role'))->where('name', 'testAdminRole')->first(); + $this->testAdminPermission = app(config('permission.models.permission'))->where('name', 'admin-permission')->first(); $this->clearLogTestHandler(); @@ -66,11 +66,11 @@ public function setUp(): void } /** - * @param \Illuminate\Foundation\Application $app + * @param Application $app * * @return array */ - protected function getPackageProviders($app) + protected function getPackageProviders($app): array { return [ PermissionServiceProvider::class, @@ -81,7 +81,7 @@ protected function getPackageProviders($app) /** * Set up the environment. * - * @param \Illuminate\Foundation\Application $app + * @param Application $app */ protected function getEnvironmentSetUp($app) { @@ -106,37 +106,16 @@ protected function getEnvironmentSetUp($app) $app['log']->getLogger()->pushHandler(new TestHandler()); } - /** - * Set up the database. - * - * @param \Illuminate\Foundation\Application $app - */ - protected function setUpDatabase($app) - { - include_once __DIR__.'/../database/migrations/create_permission_collections.php.stub'; - (new \CreatePermissionCollections())->up(); - - User::create(['email' => 'test@user.com']); - Admin::create(['email' => 'admin@user.com']); - $app[Role::class]->create(['name' => 'testRole']); - $app[Role::class]->create(['name' => 'testRole2']); - $app[Role::class]->create(['name' => 'testAdminRole', 'guard_name' => 'admin']); - $app[Permission::class]->create(['name' => 'edit-articles']); - $app[Permission::class]->create(['name' => 'edit-news']); - $app[Permission::class]->create(['name' => 'edit-categories']); - $app[Permission::class]->create(['name' => 'admin-permission', 'guard_name' => 'admin']); - } - /** * Reload the permissions. * * @return bool */ - protected function reloadPermissions() + protected function reloadPermissions(): bool { - \app(PermissionRegistrar::class)->forgetCachedPermissions(); + app(PermissionRegistrar::class)->forgetCachedPermissions(); - return \app(PermissionRegistrar::class)->registerPermissions(); + return app(PermissionRegistrar::class)->registerPermissions(); } /** @@ -157,7 +136,7 @@ public function refreshTestAdmin() protected function clearLogTestHandler() { - \collect($this->app['log']->getLogger()->getHandlers())->filter(function ($handler) { + collect($this->app['log']->getLogger()->getHandlers())->filter(function ($handler) { return $handler instanceof TestHandler; })->first()->clear(); } @@ -178,22 +157,23 @@ protected function assertLogged($message, $level) * * @return bool */ - protected function hasLog($message, $level) + protected function hasLog($message, $level): bool { - return \collect($this->app['log']->getLogger()->getHandlers())->filter(function ($handler) use ( - $message, - $level - ) { + return collect($this->app['log']->getLogger()->getHandlers())->filter(function ($handler) use ( + $message, + $level + ) { return $handler instanceof TestHandler && $handler->hasRecordThatContains($message, $level); })->count() > 0; } /** * @param $message + * @param $level */ protected function assertLogMessage($message, $level) { - if (\config('permission.log_registration_exception')) { + if (config('permission.log_registration_exception')) { $this->assertLogged($message, $level); } else { $this->assertNotLogged($message, $level); @@ -202,10 +182,11 @@ protected function assertLogMessage($message, $level) /** * @param $message + * @param $role_permission */ protected function assertShowPermission($message, $role_permission) { - if (\config('permission.display_permission_in_exception')) { + if (config('permission.display_permission_in_exception')) { $this->assertContains($role_permission, $message); } else { $this->assertStringNotContainsString($role_permission, $message); diff --git a/tests/TestHelper.php b/tests/TestHelper.php index 3bd94ec..751b164 100644 --- a/tests/TestHelper.php +++ b/tests/TestHelper.php @@ -18,7 +18,7 @@ class TestHelper * * @return int */ - public function testMiddleware($middleware, $parameter) + public function testMiddleware(string $middleware, object $parameter): int { try { return $middleware->handle(new Request(), function () { diff --git a/tests/TestSeeder.php b/tests/TestSeeder.php new file mode 100644 index 0000000..21e965c --- /dev/null +++ b/tests/TestSeeder.php @@ -0,0 +1,35 @@ +app = $app; + } + + /** + * Run the database seeds. + */ + public function run() + { + User::create(['email' => 'test@user.com']); + Admin::create(['email' => 'admin@user.com']); + $this->app[Role::class]->create(['name' => 'testRole']); + $this->app[Role::class]->create(['name' => 'testRole2']); + $this->app[Role::class]->create(['name' => 'testAdminRole', 'guard_name' => 'admin']); + $this->app[Permission::class]->create(['name' => 'edit-articles']); + $this->app[Permission::class]->create(['name' => 'edit-news']); + $this->app[Permission::class]->create(['name' => 'edit-categories']); + $this->app[Permission::class]->create(['name' => 'admin-permission', 'guard_name' => 'admin']); + } +}