repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/Exceptions/WildcardPermissionNotProperlyFormatted.php | src/Exceptions/WildcardPermissionNotProperlyFormatted.php | <?php
namespace Spatie\Permission\Exceptions;
use InvalidArgumentException;
class WildcardPermissionNotProperlyFormatted extends InvalidArgumentException
{
public static function create(string $permission)
{
return new static(__('Wildcard permission `:permission` is not properly formatted.', [
'permission' => $permission,
]));
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/Exceptions/PermissionAlreadyExists.php | src/Exceptions/PermissionAlreadyExists.php | <?php
namespace Spatie\Permission\Exceptions;
use InvalidArgumentException;
class PermissionAlreadyExists extends InvalidArgumentException
{
public static function create(string $permissionName, string $guardName)
{
return new static(__('A `:permission` permission already exists for guard `:guard`.', [
'permission' => $permissionName,
'guard' => $guardName,
]));
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/Exceptions/RoleAlreadyExists.php | src/Exceptions/RoleAlreadyExists.php | <?php
namespace Spatie\Permission\Exceptions;
use InvalidArgumentException;
class RoleAlreadyExists extends InvalidArgumentException
{
public static function create(string $roleName, string $guardName)
{
return new static(__('A role `:role` already exists for guard `:guard`.', [
'role' => $roleName,
'guard' => $guardName,
]));
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/Traits/HasRoles.php | src/Traits/HasRoles.php | <?php
namespace Spatie\Permission\Traits;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Spatie\Permission\Contracts\Permission;
use Spatie\Permission\Contracts\Role;
use Spatie\Permission\Events\RoleAttached;
use Spatie\Permission\Events\RoleDetached;
use Spatie\Permission\PermissionRegistrar;
trait HasRoles
{
use HasPermissions;
private ?string $roleClass = null;
public static function bootHasRoles()
{
static::deleting(function ($model) {
if (method_exists($model, 'isForceDeleting') && ! $model->isForceDeleting()) {
return;
}
$teams = app(PermissionRegistrar::class)->teams;
app(PermissionRegistrar::class)->teams = false;
$model->roles()->detach();
if (is_a($model, Permission::class)) {
$model->users()->detach();
}
app(PermissionRegistrar::class)->teams = $teams;
});
}
public function getRoleClass(): string
{
if (! $this->roleClass) {
$this->roleClass = app(PermissionRegistrar::class)->getRoleClass();
}
return $this->roleClass;
}
/**
* A model may have multiple roles.
*/
public function roles(): BelongsToMany
{
$relation = $this->morphToMany(
config('permission.models.role'),
'model',
config('permission.table_names.model_has_roles'),
config('permission.column_names.model_morph_key'),
app(PermissionRegistrar::class)->pivotRole
);
if (! app(PermissionRegistrar::class)->teams) {
return $relation;
}
$teamsKey = app(PermissionRegistrar::class)->teamsKey;
$relation->withPivot($teamsKey);
$teamField = config('permission.table_names.roles').'.'.$teamsKey;
return $relation->wherePivot($teamsKey, getPermissionsTeamId())
->where(fn ($q) => $q->whereNull($teamField)->orWhere($teamField, getPermissionsTeamId()));
}
/**
* Scope the model query to certain roles only.
*
* @param string|int|array|Role|Collection|\BackedEnum $roles
* @param string $guard
* @param bool $without
*/
public function scopeRole(Builder $query, $roles, $guard = null, $without = false): Builder
{
if ($roles instanceof Collection) {
$roles = $roles->all();
}
$roles = array_map(function ($role) use ($guard) {
if ($role instanceof Role) {
return $role;
}
if ($role instanceof \BackedEnum) {
$role = $role->value;
}
$method = is_int($role) || PermissionRegistrar::isUid($role) ? 'findById' : 'findByName';
return $this->getRoleClass()::{$method}($role, $guard ?: $this->getDefaultGuardName());
}, Arr::wrap($roles));
$key = (new ($this->getRoleClass())())->getKeyName();
return $query->{! $without ? 'whereHas' : 'whereDoesntHave'}('roles', fn (Builder $subQuery) => $subQuery
->whereIn(config('permission.table_names.roles').".$key", \array_column($roles, $key))
);
}
/**
* Scope the model query to only those without certain roles.
*
* @param string|int|array|Role|Collection|\BackedEnum $roles
* @param string $guard
*/
public function scopeWithoutRole(Builder $query, $roles, $guard = null): Builder
{
return $this->scopeRole($query, $roles, $guard, true);
}
/**
* Returns array of role ids
*
* @param string|int|array|Role|Collection|\BackedEnum $roles
*/
private function collectRoles(...$roles): array
{
return collect($roles)
->flatten()
->reduce(function ($array, $role) {
if (empty($role)) {
return $array;
}
$role = $this->getStoredRole($role);
if (! in_array($role->getKey(), $array)) {
$this->ensureModelSharesGuard($role);
$array[] = $role->getKey();
}
return $array;
}, []);
}
/**
* Assign the given role to the model.
*
* @param string|int|array|Role|Collection|\BackedEnum ...$roles
* @return $this
*/
public function assignRole(...$roles)
{
$roles = $this->collectRoles($roles);
$model = $this->getModel();
$teamPivot = app(PermissionRegistrar::class)->teams && ! is_a($this, Permission::class) ?
[app(PermissionRegistrar::class)->teamsKey => getPermissionsTeamId()] : [];
if ($model->exists) {
if (app(PermissionRegistrar::class)->teams) {
// explicit reload in case team has been changed since last load
$this->load('roles');
}
$currentRoles = $this->roles->map(fn ($role) => $role->getKey())->toArray();
$this->roles()->attach(array_diff($roles, $currentRoles), $teamPivot);
$model->unsetRelation('roles');
} else {
$class = \get_class($model);
$saved = false;
$class::saved(
function ($object) use ($roles, $model, $teamPivot, &$saved) {
if ($saved || $model->getKey() != $object->getKey()) {
return;
}
$model->roles()->attach($roles, $teamPivot);
$model->unsetRelation('roles');
$saved = true;
}
);
}
if (is_a($this, Permission::class)) {
$this->forgetCachedPermissions();
}
if (config('permission.events_enabled')) {
event(new RoleAttached($this->getModel(), $roles));
}
return $this;
}
/**
* Revoke the given role from the model.
*
* @param string|int|array|Role|Collection|\BackedEnum ...$role
* @return $this
*/
public function removeRole(...$role)
{
$roles = $this->collectRoles($role);
$this->roles()->detach($roles);
$this->unsetRelation('roles');
if (is_a($this, Permission::class)) {
$this->forgetCachedPermissions();
}
if (config('permission.events_enabled')) {
event(new RoleDetached($this->getModel(), $roles));
}
return $this;
}
/**
* Remove all current roles and set the given ones.
*
* @param string|int|array|Role|Collection|\BackedEnum ...$roles
* @return $this
*/
public function syncRoles(...$roles)
{
if ($this->getModel()->exists) {
$this->collectRoles($roles);
if (config('permission.events_enabled')) {
$currentRoles = $this->roles()->get();
if ($currentRoles->isNotEmpty()) {
$this->removeRole($currentRoles);
}
} else {
$this->roles()->detach();
$this->setRelation('roles', collect());
}
}
return $this->assignRole($roles);
}
/**
* Determine if the model has (one of) the given role(s).
*
* @param string|int|array|Role|Collection|\BackedEnum $roles
*/
public function hasRole($roles, ?string $guard = null): bool
{
$this->loadMissing('roles');
if (is_string($roles) && strpos($roles, '|') !== false) {
$roles = $this->convertPipeToArray($roles);
}
if ($roles instanceof \BackedEnum) {
$roles = $roles->value;
return $this->roles
->when($guard, fn ($q) => $q->where('guard_name', $guard))
->pluck('name')
->contains(function ($name) use ($roles) {
/** @var string|\BackedEnum $name */
if ($name instanceof \BackedEnum) {
return $name->value == $roles;
}
return $name == $roles;
});
}
if (is_int($roles) || PermissionRegistrar::isUid($roles)) {
$key = (new ($this->getRoleClass())())->getKeyName();
return $guard
? $this->roles->where('guard_name', $guard)->contains($key, $roles)
: $this->roles->contains($key, $roles);
}
if (is_string($roles)) {
return $guard
? $this->roles->where('guard_name', $guard)->contains('name', $roles)
: $this->roles->contains('name', $roles);
}
if ($roles instanceof Role) {
return $this->roles->contains($roles->getKeyName(), $roles->getKey());
}
if (is_array($roles)) {
foreach ($roles as $role) {
if ($this->hasRole($role, $guard)) {
return true;
}
}
return false;
}
if ($roles instanceof Collection) {
return $roles->intersect($guard ? $this->roles->where('guard_name', $guard) : $this->roles)->isNotEmpty();
}
throw new \TypeError('Unsupported type for $roles parameter to hasRole().');
}
/**
* Determine if the model has any of the given role(s).
*
* Alias to hasRole() but without Guard controls
*
* @param string|int|array|Role|Collection|\BackedEnum $roles
*/
public function hasAnyRole(...$roles): bool
{
return $this->hasRole($roles);
}
/**
* Determine if the model has all of the given role(s).
*
* @param string|array|Role|Collection|\BackedEnum $roles
*/
public function hasAllRoles($roles, ?string $guard = null): bool
{
$this->loadMissing('roles');
if ($roles instanceof \BackedEnum) {
$roles = $roles->value;
}
if (is_string($roles) && strpos($roles, '|') !== false) {
$roles = $this->convertPipeToArray($roles);
}
if (is_string($roles)) {
return $this->hasRole($roles, $guard);
}
if ($roles instanceof Role) {
return $this->roles->contains($roles->getKeyName(), $roles->getKey());
}
$roles = collect()->make($roles)->map(function ($role) {
if ($role instanceof \BackedEnum) {
return $role->value;
}
return $role instanceof Role ? $role->name : $role;
});
$roleNames = $guard
? $this->roles->where('guard_name', $guard)->pluck('name')
: $this->getRoleNames();
$roleNames = $roleNames->transform(function ($roleName) {
if ($roleName instanceof \BackedEnum) {
return $roleName->value;
}
return $roleName;
});
return $roles->intersect($roleNames) == $roles;
}
/**
* Determine if the model has exactly all of the given role(s).
*
* @param string|array|Role|Collection|\BackedEnum $roles
*/
public function hasExactRoles($roles, ?string $guard = null): bool
{
$this->loadMissing('roles');
if (is_string($roles) && strpos($roles, '|') !== false) {
$roles = $this->convertPipeToArray($roles);
}
if (is_string($roles)) {
$roles = [$roles];
}
if ($roles instanceof Role) {
$roles = [$roles->name];
}
$roles = collect()->make($roles)->map(fn ($role) => $role instanceof Role ? $role->name : $role
);
return $this->roles->count() == $roles->count() && $this->hasAllRoles($roles, $guard);
}
/**
* Return all permissions directly coupled to the model.
*/
public function getDirectPermissions(): Collection
{
return $this->permissions;
}
public function getRoleNames(): Collection
{
$this->loadMissing('roles');
return $this->roles->pluck('name');
}
protected function getStoredRole($role): Role
{
if ($role instanceof \BackedEnum) {
$role = $role->value;
}
if (is_int($role) || PermissionRegistrar::isUid($role)) {
return $this->getRoleClass()::findById($role, $this->getDefaultGuardName());
}
if (is_string($role)) {
return $this->getRoleClass()::findByName($role, $this->getDefaultGuardName());
}
return $role;
}
protected function convertPipeToArray(string $pipeString)
{
$pipeString = trim($pipeString);
if (strlen($pipeString) <= 2) {
return [str_replace('|', '', $pipeString)];
}
$quoteCharacter = substr($pipeString, 0, 1);
$endCharacter = substr($quoteCharacter, -1, 1);
if ($quoteCharacter !== $endCharacter) {
return explode('|', $pipeString);
}
if (! in_array($quoteCharacter, ["'", '"'])) {
return explode('|', $pipeString);
}
return explode('|', trim($pipeString, $quoteCharacter));
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/Traits/HasPermissions.php | src/Traits/HasPermissions.php | <?php
namespace Spatie\Permission\Traits;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Spatie\Permission\Contracts\Permission;
use Spatie\Permission\Contracts\Role;
use Spatie\Permission\Contracts\Wildcard;
use Spatie\Permission\Events\PermissionAttached;
use Spatie\Permission\Events\PermissionDetached;
use Spatie\Permission\Exceptions\GuardDoesNotMatch;
use Spatie\Permission\Exceptions\PermissionDoesNotExist;
use Spatie\Permission\Exceptions\WildcardPermissionInvalidArgument;
use Spatie\Permission\Exceptions\WildcardPermissionNotImplementsContract;
use Spatie\Permission\Guard;
use Spatie\Permission\PermissionRegistrar;
use Spatie\Permission\WildcardPermission;
trait HasPermissions
{
private ?string $permissionClass = null;
private ?string $wildcardClass = null;
private array $wildcardPermissionsIndex;
public static function bootHasPermissions()
{
static::deleting(function ($model) {
if (method_exists($model, 'isForceDeleting') && ! $model->isForceDeleting()) {
return;
}
$teams = app(PermissionRegistrar::class)->teams;
app(PermissionRegistrar::class)->teams = false;
if (! is_a($model, Permission::class)) {
$model->permissions()->detach();
}
if (is_a($model, Role::class)) {
$model->users()->detach();
}
app(PermissionRegistrar::class)->teams = $teams;
});
}
public function getPermissionClass(): string
{
if (! $this->permissionClass) {
$this->permissionClass = app(PermissionRegistrar::class)->getPermissionClass();
}
return $this->permissionClass;
}
public function getWildcardClass()
{
if (! is_null($this->wildcardClass)) {
return $this->wildcardClass;
}
$this->wildcardClass = '';
if (config('permission.enable_wildcard_permission')) {
$this->wildcardClass = config('permission.wildcard_permission', WildcardPermission::class);
if (! is_subclass_of($this->wildcardClass, Wildcard::class)) {
throw WildcardPermissionNotImplementsContract::create();
}
}
return $this->wildcardClass;
}
/**
* A model may have multiple direct permissions.
*/
public function permissions(): BelongsToMany
{
$relation = $this->morphToMany(
config('permission.models.permission'),
'model',
config('permission.table_names.model_has_permissions'),
config('permission.column_names.model_morph_key'),
app(PermissionRegistrar::class)->pivotPermission
);
if (! app(PermissionRegistrar::class)->teams) {
return $relation;
}
$teamsKey = app(PermissionRegistrar::class)->teamsKey;
$relation->withPivot($teamsKey);
return $relation->wherePivot($teamsKey, getPermissionsTeamId());
}
/**
* Scope the model query to certain permissions only.
*
* @param string|int|array|Permission|Collection|\BackedEnum $permissions
* @param bool $without
*/
public function scopePermission(Builder $query, $permissions, $without = false): Builder
{
$permissions = $this->convertToPermissionModels($permissions);
$permissionKey = (new ($this->getPermissionClass())())->getKeyName();
$roleKey = (new (is_a($this, Role::class) ? static::class : $this->getRoleClass())())->getKeyName();
$rolesWithPermissions = is_a($this, Role::class) ? [] : array_unique(
array_reduce($permissions, fn ($result, $permission) => array_merge($result, $permission->roles->all()), [])
);
return $query->where(fn (Builder $query) => $query
->{! $without ? 'whereHas' : 'whereDoesntHave'}('permissions', fn (Builder $subQuery) => $subQuery
->whereIn(config('permission.table_names.permissions').".$permissionKey", \array_column($permissions, $permissionKey))
)
->when(count($rolesWithPermissions), fn ($whenQuery) => $whenQuery
->{! $without ? 'orWhereHas' : 'whereDoesntHave'}('roles', fn (Builder $subQuery) => $subQuery
->whereIn(config('permission.table_names.roles').".$roleKey", \array_column($rolesWithPermissions, $roleKey))
)
)
);
}
/**
* Scope the model query to only those without certain permissions,
* whether indirectly by role or by direct permission.
*
* @param string|int|array|Permission|Collection|\BackedEnum $permissions
*/
public function scopeWithoutPermission(Builder $query, $permissions): Builder
{
return $this->scopePermission($query, $permissions, true);
}
/**
* @param string|int|array|Permission|Collection|\BackedEnum $permissions
*
* @throws PermissionDoesNotExist
*/
protected function convertToPermissionModels($permissions): array
{
if ($permissions instanceof Collection) {
$permissions = $permissions->all();
}
return array_map(function ($permission) {
if ($permission instanceof Permission) {
return $permission;
}
if ($permission instanceof \BackedEnum) {
$permission = $permission->value;
}
$method = is_int($permission) || PermissionRegistrar::isUid($permission) ? 'findById' : 'findByName';
return $this->getPermissionClass()::{$method}($permission, $this->getDefaultGuardName());
}, Arr::wrap($permissions));
}
/**
* Find a permission.
*
* @param string|int|Permission|\BackedEnum $permission
* @return Permission
*
* @throws PermissionDoesNotExist
*/
public function filterPermission($permission, $guardName = null)
{
if ($permission instanceof \BackedEnum) {
$permission = $permission->value;
}
if (is_int($permission) || PermissionRegistrar::isUid($permission)) {
$permission = $this->getPermissionClass()::findById(
$permission,
$guardName ?? $this->getDefaultGuardName()
);
}
if (is_string($permission)) {
$permission = $this->getPermissionClass()::findByName(
$permission,
$guardName ?? $this->getDefaultGuardName()
);
}
if (! $permission instanceof Permission) {
throw new PermissionDoesNotExist;
}
return $permission;
}
/**
* Determine if the model may perform the given permission.
*
* @param string|int|Permission|\BackedEnum $permission
* @param string|null $guardName
*
* @throws PermissionDoesNotExist
*/
public function hasPermissionTo($permission, $guardName = null): bool
{
if ($this->getWildcardClass()) {
return $this->hasWildcardPermission($permission, $guardName);
}
$permission = $this->filterPermission($permission, $guardName);
return $this->hasDirectPermission($permission) || $this->hasPermissionViaRole($permission);
}
/**
* Validates a wildcard permission against all permissions of a user.
*
* @param string|int|Permission|\BackedEnum $permission
* @param string|null $guardName
*/
protected function hasWildcardPermission($permission, $guardName = null): bool
{
$guardName = $guardName ?? $this->getDefaultGuardName();
if ($permission instanceof \BackedEnum) {
$permission = $permission->value;
}
if (is_int($permission) || PermissionRegistrar::isUid($permission)) {
$permission = $this->getPermissionClass()::findById($permission, $guardName);
}
if ($permission instanceof Permission) {
$guardName = $permission->guard_name ?? $guardName;
$permission = $permission->name;
}
if (! is_string($permission)) {
throw WildcardPermissionInvalidArgument::create();
}
return app($this->getWildcardClass(), ['record' => $this])->implies(
$permission,
$guardName,
app(PermissionRegistrar::class)->getWildcardPermissionIndex($this),
);
}
/**
* An alias to hasPermissionTo(), but avoids throwing an exception.
*
* @param string|int|Permission|\BackedEnum $permission
* @param string|null $guardName
*/
public function checkPermissionTo($permission, $guardName = null): bool
{
try {
return $this->hasPermissionTo($permission, $guardName);
} catch (PermissionDoesNotExist $e) {
return false;
}
}
/**
* Determine if the model has any of the given permissions.
*
* @param string|int|array|Permission|Collection|\BackedEnum ...$permissions
*/
public function hasAnyPermission(...$permissions): bool
{
$permissions = collect($permissions)->flatten();
foreach ($permissions as $permission) {
if ($this->checkPermissionTo($permission)) {
return true;
}
}
return false;
}
/**
* Determine if the model has all of the given permissions.
*
* @param string|int|array|Permission|Collection|\BackedEnum ...$permissions
*/
public function hasAllPermissions(...$permissions): bool
{
$permissions = collect($permissions)->flatten();
foreach ($permissions as $permission) {
if (! $this->checkPermissionTo($permission)) {
return false;
}
}
return true;
}
/**
* Determine if the model has, via roles, the given permission.
*/
protected function hasPermissionViaRole(Permission $permission): bool
{
if (is_a($this, Role::class)) {
return false;
}
return $this->hasRole($permission->roles);
}
/**
* Determine if the model has the given permission.
*
* @param string|int|Permission|\BackedEnum $permission
*
* @throws PermissionDoesNotExist
*/
public function hasDirectPermission($permission): bool
{
$permission = $this->filterPermission($permission);
return $this->loadMissing('permissions')->permissions
->contains($permission->getKeyName(), $permission->getKey());
}
/**
* Return all the permissions the model has via roles.
*/
public function getPermissionsViaRoles(): Collection
{
if (is_a($this, Role::class) || is_a($this, Permission::class)) {
return collect();
}
return $this->loadMissing('roles', 'roles.permissions')
->roles->flatMap(fn ($role) => $role->permissions)
->sort()->values();
}
/**
* Return all the permissions the model has, both directly and via roles.
*/
public function getAllPermissions(): Collection
{
/** @var Collection $permissions */
$permissions = $this->permissions;
if (! is_a($this, Permission::class)) {
$permissions = $permissions->merge($this->getPermissionsViaRoles());
}
return $permissions->sort()->values();
}
/**
* Returns array of permissions ids
*
* @param string|int|array|Permission|Collection|\BackedEnum $permissions
*/
private function collectPermissions(...$permissions): array
{
return collect($permissions)
->flatten()
->reduce(function ($array, $permission) {
if (empty($permission)) {
return $array;
}
$permission = $this->getStoredPermission($permission);
if (! $permission instanceof Permission) {
return $array;
}
if (! in_array($permission->getKey(), $array)) {
$this->ensureModelSharesGuard($permission);
$array[] = $permission->getKey();
}
return $array;
}, []);
}
/**
* Grant the given permission(s) to a role.
*
* @param string|int|array|Permission|Collection|\BackedEnum $permissions
* @return $this
*/
public function givePermissionTo(...$permissions)
{
$permissions = $this->collectPermissions($permissions);
$model = $this->getModel();
$teamPivot = app(PermissionRegistrar::class)->teams && ! is_a($this, Role::class) ?
[app(PermissionRegistrar::class)->teamsKey => getPermissionsTeamId()] : [];
if ($model->exists) {
$currentPermissions = $this->permissions->map(fn ($permission) => $permission->getKey())->toArray();
$this->permissions()->attach(array_diff($permissions, $currentPermissions), $teamPivot);
$model->unsetRelation('permissions');
} else {
$class = \get_class($model);
$saved = false;
$class::saved(
function ($object) use ($permissions, $model, $teamPivot, &$saved) {
if ($saved || $model->getKey() != $object->getKey()) {
return;
}
$model->permissions()->attach($permissions, $teamPivot);
$model->unsetRelation('permissions');
$saved = true;
}
);
}
if (is_a($this, Role::class)) {
$this->forgetCachedPermissions();
}
if (config('permission.events_enabled')) {
event(new PermissionAttached($this->getModel(), $permissions));
}
$this->forgetWildcardPermissionIndex();
return $this;
}
public function forgetWildcardPermissionIndex(): void
{
app(PermissionRegistrar::class)->forgetWildcardPermissionIndex(
is_a($this, Role::class) ? null : $this,
);
}
/**
* Remove all current permissions and set the given ones.
*
* @param string|int|array|Permission|Collection|\BackedEnum $permissions
* @return $this
*/
public function syncPermissions(...$permissions)
{
if ($this->getModel()->exists) {
$this->collectPermissions($permissions);
$this->permissions()->detach();
$this->setRelation('permissions', collect());
}
return $this->givePermissionTo($permissions);
}
/**
* Revoke the given permission(s).
*
* @param Permission|Permission[]|string|string[]|\BackedEnum $permission
* @return $this
*/
public function revokePermissionTo($permission)
{
$storedPermission = $this->getStoredPermission($permission);
$this->permissions()->detach($storedPermission);
if (is_a($this, Role::class)) {
$this->forgetCachedPermissions();
}
if (config('permission.events_enabled')) {
event(new PermissionDetached($this->getModel(), $storedPermission));
}
$this->forgetWildcardPermissionIndex();
$this->unsetRelation('permissions');
return $this;
}
public function getPermissionNames(): Collection
{
return $this->permissions->pluck('name');
}
/**
* @param string|int|array|Permission|Collection|\BackedEnum $permissions
* @return Permission|Permission[]|Collection
*/
protected function getStoredPermission($permissions)
{
if ($permissions instanceof \BackedEnum) {
$permissions = $permissions->value;
}
if (is_int($permissions) || PermissionRegistrar::isUid($permissions)) {
return $this->getPermissionClass()::findById($permissions, $this->getDefaultGuardName());
}
if (is_string($permissions)) {
return $this->getPermissionClass()::findByName($permissions, $this->getDefaultGuardName());
}
if (is_array($permissions)) {
$permissions = array_map(function ($permission) {
if ($permission instanceof \BackedEnum) {
return $permission->value;
}
return is_a($permission, Permission::class) ? $permission->name : $permission;
}, $permissions);
return $this->getPermissionClass()::whereIn('name', $permissions)
->whereIn('guard_name', $this->getGuardNames())
->get();
}
return $permissions;
}
/**
* @param Permission|Role $roleOrPermission
*
* @throws GuardDoesNotMatch
*/
protected function ensureModelSharesGuard($roleOrPermission)
{
if (! $this->getGuardNames()->contains($roleOrPermission->guard_name)) {
throw GuardDoesNotMatch::create($roleOrPermission->guard_name, $this->getGuardNames());
}
}
protected function getGuardNames(): Collection
{
return Guard::getNames($this);
}
protected function getDefaultGuardName(): string
{
return Guard::getDefaultName($this);
}
/**
* Forget the cached permissions.
*/
public function forgetCachedPermissions()
{
app(PermissionRegistrar::class)->forgetCachedPermissions();
}
/**
* Check if the model has All of the requested Direct permissions.
*
* @param string|int|array|Permission|Collection|\BackedEnum ...$permissions
*/
public function hasAllDirectPermissions(...$permissions): bool
{
$permissions = collect($permissions)->flatten();
foreach ($permissions as $permission) {
if (! $this->hasDirectPermission($permission)) {
return false;
}
}
return true;
}
/**
* Check if the model has Any of the requested Direct permissions.
*
* @param string|int|array|Permission|Collection|\BackedEnum ...$permissions
*/
public function hasAnyDirectPermission(...$permissions): bool
{
$permissions = collect($permissions)->flatten();
foreach ($permissions as $permission) {
if ($this->hasDirectPermission($permission)) {
return true;
}
}
return false;
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/Traits/RefreshesPermissionCache.php | src/Traits/RefreshesPermissionCache.php | <?php
namespace Spatie\Permission\Traits;
use Spatie\Permission\PermissionRegistrar;
trait RefreshesPermissionCache
{
public static function bootRefreshesPermissionCache()
{
static::saved(function () {
app(PermissionRegistrar::class)->forgetCachedPermissions();
});
static::deleted(function () {
app(PermissionRegistrar::class)->forgetCachedPermissions();
});
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/Contracts/Wildcard.php | src/Contracts/Wildcard.php | <?php
namespace Spatie\Permission\Contracts;
use Illuminate\Database\Eloquent\Model;
interface Wildcard
{
public function __construct(Model $record);
public function getIndex(): array;
public function implies(string $permission, string $guardName, array $index): bool;
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/Contracts/Role.php | src/Contracts/Role.php | <?php
namespace Spatie\Permission\Contracts;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
/**
* @property int|string $id
* @property string $name
* @property string|null $guard_name
*
* @mixin \Spatie\Permission\Models\Role
*
* @phpstan-require-extends \Spatie\Permission\Models\Role
*/
interface Role
{
/**
* A role may be given various permissions.
*/
public function permissions(): BelongsToMany;
/**
* Find a role by its name and guard name.
*
*
* @throws \Spatie\Permission\Exceptions\RoleDoesNotExist
*/
public static function findByName(string $name, ?string $guardName): self;
/**
* Find a role by its id and guard name.
*
*
* @throws \Spatie\Permission\Exceptions\RoleDoesNotExist
*/
public static function findById(int|string $id, ?string $guardName): self;
/**
* Find or create a role by its name and guard name.
*/
public static function findOrCreate(string $name, ?string $guardName): self;
/**
* Determine if the user may perform the given permission.
*
* @param string|int|\Spatie\Permission\Contracts\Permission|\BackedEnum $permission
*/
public function hasPermissionTo($permission, ?string $guardName): bool;
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/Contracts/PermissionsTeamResolver.php | src/Contracts/PermissionsTeamResolver.php | <?php
namespace Spatie\Permission\Contracts;
interface PermissionsTeamResolver
{
public function getPermissionsTeamId(): int|string|null;
/**
* Set the team id for teams/groups support, this id is used when querying permissions/roles
*
* @param int|string|\Illuminate\Database\Eloquent\Model|null $id
*/
public function setPermissionsTeamId($id): void;
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/Contracts/Permission.php | src/Contracts/Permission.php | <?php
namespace Spatie\Permission\Contracts;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
/**
* @property int|string $id
* @property string $name
* @property string|null $guard_name
*
* @mixin \Spatie\Permission\Models\Permission
*
* @phpstan-require-extends \Spatie\Permission\Models\Permission
*/
interface Permission
{
/**
* A permission can be applied to roles.
*/
public function roles(): BelongsToMany;
/**
* Find a permission by its name.
*
*
* @throws \Spatie\Permission\Exceptions\PermissionDoesNotExist
*/
public static function findByName(string $name, ?string $guardName): self;
/**
* Find a permission by its id.
*
*
* @throws \Spatie\Permission\Exceptions\PermissionDoesNotExist
*/
public static function findById(int|string $id, ?string $guardName): self;
/**
* Find or Create a permission by its name and guard name.
*/
public static function findOrCreate(string $name, ?string $guardName): self;
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/Middleware/RoleMiddleware.php | src/Middleware/RoleMiddleware.php | <?php
namespace Spatie\Permission\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
use Spatie\Permission\Exceptions\UnauthorizedException;
use Spatie\Permission\Guard;
class RoleMiddleware
{
public function handle($request, Closure $next, $role, $guard = null)
{
$authGuard = Auth::guard($guard);
$user = $authGuard->user();
// For machine-to-machine Passport clients
if (! $user && $request->bearerToken() && config('permission.use_passport_client_credentials')) {
$user = Guard::getPassportClient($guard);
}
if (! $user) {
throw UnauthorizedException::notLoggedIn();
}
if (! method_exists($user, 'hasAnyRole')) {
throw UnauthorizedException::missingTraitHasRoles($user);
}
$roles = explode('|', self::parseRolesToString($role));
if (! $user->hasAnyRole($roles)) {
throw UnauthorizedException::forRoles($roles);
}
return $next($request);
}
/**
* Specify the role and guard for the middleware.
*
* @param array|string|\BackedEnum $role
* @param string|null $guard
* @return string
*/
public static function using($role, $guard = null)
{
$roleString = self::parseRolesToString($role);
$args = is_null($guard) ? $roleString : "$roleString,$guard";
return static::class.':'.$args;
}
/**
* Convert array or string of roles to string representation.
*
* @return string
*/
protected static function parseRolesToString(array|string|\BackedEnum $role)
{
// Convert Enum to its value if an Enum is passed
if ($role instanceof \BackedEnum) {
$role = $role->value;
}
if (is_array($role)) {
$role = array_map(fn ($r) => $r instanceof \BackedEnum ? $r->value : $r, $role);
return implode('|', $role);
}
return (string) $role;
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/Middleware/RoleOrPermissionMiddleware.php | src/Middleware/RoleOrPermissionMiddleware.php | <?php
namespace Spatie\Permission\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
use Spatie\Permission\Exceptions\UnauthorizedException;
use Spatie\Permission\Guard;
class RoleOrPermissionMiddleware
{
public function handle($request, Closure $next, $roleOrPermission, $guard = null)
{
$authGuard = Auth::guard($guard);
$user = $authGuard->user();
// For machine-to-machine Passport clients
if (! $user && $request->bearerToken() && config('permission.use_passport_client_credentials')) {
$user = Guard::getPassportClient($guard);
}
if (! $user) {
throw UnauthorizedException::notLoggedIn();
}
if (! method_exists($user, 'hasAnyRole') || ! method_exists($user, 'hasAnyPermission')) {
throw UnauthorizedException::missingTraitHasRoles($user);
}
$rolesOrPermissions = explode('|', self::parseRoleOrPermissionToString($roleOrPermission));
if (! $user->canAny($rolesOrPermissions) && ! $user->hasAnyRole($rolesOrPermissions)) {
throw UnauthorizedException::forRolesOrPermissions($rolesOrPermissions);
}
return $next($request);
}
/**
* Specify the role or permission and guard for the middleware.
*
* @param array|string|\BackedEnum $roleOrPermission
* @param string|null $guard
* @return string
*/
public static function using($roleOrPermission, $guard = null)
{
$roleOrPermissionString = self::parseRoleOrPermissionToString($roleOrPermission);
$args = is_null($guard) ? $roleOrPermissionString : "$roleOrPermissionString,$guard";
return static::class.':'.$args;
}
/**
* Convert array or string of roles/permissions to string representation.
*
* @return string
*/
protected static function parseRoleOrPermissionToString(array|string|\BackedEnum $roleOrPermission)
{
// Convert Enum to its value if an Enum is passed
if ($roleOrPermission instanceof \BackedEnum) {
$roleOrPermission = $roleOrPermission->value;
}
if (is_array($roleOrPermission)) {
$roleOrPermission = array_map(fn ($r) => $r instanceof \BackedEnum ? $r->value : $r, $roleOrPermission);
return implode('|', $roleOrPermission);
}
return (string) $roleOrPermission;
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/Middleware/PermissionMiddleware.php | src/Middleware/PermissionMiddleware.php | <?php
namespace Spatie\Permission\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
use Spatie\Permission\Exceptions\UnauthorizedException;
use Spatie\Permission\Guard;
class PermissionMiddleware
{
public function handle($request, Closure $next, $permission, $guard = null)
{
$authGuard = Auth::guard($guard);
$user = $authGuard->user();
// For machine-to-machine Passport clients
if (! $user && $request->bearerToken() && config('permission.use_passport_client_credentials')) {
$user = Guard::getPassportClient($guard);
}
if (! $user) {
throw UnauthorizedException::notLoggedIn();
}
if (! method_exists($user, 'hasAnyPermission')) {
throw UnauthorizedException::missingTraitHasRoles($user);
}
$permissions = explode('|', self::parsePermissionsToString($permission));
if (! $user->canAny($permissions)) {
throw UnauthorizedException::forPermissions($permissions);
}
return $next($request);
}
/**
* Specify the permission and guard for the middleware.
*
* @param array|string|\BackedEnum $permission
* @param string|null $guard
* @return string
*/
public static function using($permission, $guard = null)
{
// Convert Enum to its value if an Enum is passed
if ($permission instanceof \BackedEnum) {
$permission = $permission->value;
}
$permissionString = self::parsePermissionsToString($permission);
$args = is_null($guard) ? $permissionString : "$permissionString,$guard";
return static::class.':'.$args;
}
/**
* Convert array or string of permissions to string representation.
*
* @return string
*/
protected static function parsePermissionsToString(array|string|\BackedEnum $permission)
{
// Convert Enum to its value if an Enum is passed
if ($permission instanceof \BackedEnum) {
$permission = $permission->value;
}
if (is_array($permission)) {
$permission = array_map(fn ($r) => $r instanceof \BackedEnum ? $r->value : $r, $permission);
return implode('|', $permission);
}
return (string) $permission;
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/Models/Role.php | src/Models/Role.php | <?php
namespace Spatie\Permission\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Spatie\Permission\Contracts\Role as RoleContract;
use Spatie\Permission\Exceptions\GuardDoesNotMatch;
use Spatie\Permission\Exceptions\PermissionDoesNotExist;
use Spatie\Permission\Exceptions\RoleAlreadyExists;
use Spatie\Permission\Exceptions\RoleDoesNotExist;
use Spatie\Permission\Guard;
use Spatie\Permission\PermissionRegistrar;
use Spatie\Permission\Traits\HasPermissions;
use Spatie\Permission\Traits\RefreshesPermissionCache;
/**
* @property ?\Illuminate\Support\Carbon $created_at
* @property ?\Illuminate\Support\Carbon $updated_at
*/
class Role extends Model implements RoleContract
{
use HasPermissions;
use RefreshesPermissionCache;
protected $guarded = [];
public function __construct(array $attributes = [])
{
$attributes['guard_name'] ??= Guard::getDefaultName(static::class);
parent::__construct($attributes);
$this->guarded[] = $this->primaryKey;
$this->table = config('permission.table_names.roles') ?: parent::getTable();
}
/**
* @return RoleContract|Role
*
* @throws RoleAlreadyExists
*/
public static function create(array $attributes = [])
{
$attributes['guard_name'] ??= Guard::getDefaultName(static::class);
$params = ['name' => $attributes['name'], 'guard_name' => $attributes['guard_name']];
$registrar = app(PermissionRegistrar::class);
if ($registrar->teams) {
$teamsKey = $registrar->teamsKey;
if (array_key_exists($teamsKey, $attributes)) {
$params[$teamsKey] = $attributes[$teamsKey];
} else {
$attributes[$teamsKey] = getPermissionsTeamId();
}
}
if (static::findByParam($params)) {
throw RoleAlreadyExists::create($attributes['name'], $attributes['guard_name']);
}
return static::query()->create($attributes);
}
/**
* A role may be given various permissions.
*/
public function permissions(): BelongsToMany
{
$registrar = app(PermissionRegistrar::class);
return $this->belongsToMany(
config('permission.models.permission'),
config('permission.table_names.role_has_permissions'),
$registrar->pivotRole,
$registrar->pivotPermission
);
}
/**
* A role belongs to some users of the model associated with its guard.
*/
public function users(): BelongsToMany
{
return $this->morphedByMany(
getModelForGuard($this->attributes['guard_name'] ?? config('auth.defaults.guard')),
'model',
config('permission.table_names.model_has_roles'),
app(PermissionRegistrar::class)->pivotRole,
config('permission.column_names.model_morph_key')
);
}
/**
* Find a role by its name and guard name.
*
* @return RoleContract|Role
*
* @throws RoleDoesNotExist
*/
public static function findByName(string $name, ?string $guardName = null): RoleContract
{
$guardName ??= Guard::getDefaultName(static::class);
$role = static::findByParam(['name' => $name, 'guard_name' => $guardName]);
if (! $role) {
throw RoleDoesNotExist::named($name, $guardName);
}
return $role;
}
/**
* Find a role by its id (and optionally guardName).
*
* @return RoleContract|Role
*/
public static function findById(int|string $id, ?string $guardName = null): RoleContract
{
$guardName ??= Guard::getDefaultName(static::class);
$role = static::findByParam([(new static)->getKeyName() => $id, 'guard_name' => $guardName]);
if (! $role) {
throw RoleDoesNotExist::withId($id, $guardName);
}
return $role;
}
/**
* Find or create role by its name (and optionally guardName).
*
* @return RoleContract|Role
*/
public static function findOrCreate(string $name, ?string $guardName = null): RoleContract
{
$guardName ??= Guard::getDefaultName(static::class);
$attributes = ['name' => $name, 'guard_name' => $guardName];
$role = static::findByParam($attributes);
if (! $role) {
$registrar = app(PermissionRegistrar::class);
if ($registrar->teams) {
$teamsKey = $registrar->teamsKey;
$attributes[$teamsKey] = getPermissionsTeamId();
}
return static::query()->create($attributes);
}
return $role;
}
/**
* Finds a role based on an array of parameters.
*
* @return RoleContract|Role|null
*/
protected static function findByParam(array $params = []): ?RoleContract
{
$query = static::query();
$registrar = app(PermissionRegistrar::class);
if ($registrar->teams) {
$teamsKey = $registrar->teamsKey;
$query->where(fn ($q) => $q->whereNull($teamsKey)
->orWhere($teamsKey, $params[$teamsKey] ?? getPermissionsTeamId())
);
unset($params[$teamsKey]);
}
foreach ($params as $key => $value) {
$query->where($key, $value);
}
return $query->first();
}
/**
* Determine if the role may perform the given permission.
*
* @param string|int|\Spatie\Permission\Contracts\Permission|\BackedEnum $permission
*
* @throws PermissionDoesNotExist|GuardDoesNotMatch
*/
public function hasPermissionTo($permission, ?string $guardName = null): bool
{
if ($this->getWildcardClass()) {
return $this->hasWildcardPermission($permission, $guardName);
}
$permission = $this->filterPermission($permission, $guardName);
if (! $this->getGuardNames()->contains($permission->guard_name)) {
throw GuardDoesNotMatch::create($permission->guard_name, $guardName ? collect([$guardName]) : $this->getGuardNames());
}
return $this->loadMissing('permissions')->permissions
->contains($permission->getKeyName(), $permission->getKey());
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/Models/Permission.php | src/Models/Permission.php | <?php
namespace Spatie\Permission\Models;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Spatie\Permission\Contracts\Permission as PermissionContract;
use Spatie\Permission\Exceptions\PermissionAlreadyExists;
use Spatie\Permission\Exceptions\PermissionDoesNotExist;
use Spatie\Permission\Guard;
use Spatie\Permission\PermissionRegistrar;
use Spatie\Permission\Traits\HasRoles;
use Spatie\Permission\Traits\RefreshesPermissionCache;
/**
* @property ?\Illuminate\Support\Carbon $created_at
* @property ?\Illuminate\Support\Carbon $updated_at
*/
class Permission extends Model implements PermissionContract
{
use HasRoles;
use RefreshesPermissionCache;
protected $guarded = [];
public function __construct(array $attributes = [])
{
$attributes['guard_name'] ??= Guard::getDefaultName(static::class);
parent::__construct($attributes);
$this->guarded[] = $this->primaryKey;
$this->table = config('permission.table_names.permissions') ?: parent::getTable();
}
/**
* @return PermissionContract|Permission
*
* @throws PermissionAlreadyExists
*/
public static function create(array $attributes = [])
{
$attributes['guard_name'] ??= Guard::getDefaultName(static::class);
$permission = static::getPermission(['name' => $attributes['name'], 'guard_name' => $attributes['guard_name']]);
if ($permission) {
throw PermissionAlreadyExists::create($attributes['name'], $attributes['guard_name']);
}
return static::query()->create($attributes);
}
/**
* A permission can be applied to roles.
*/
public function roles(): BelongsToMany
{
$registrar = app(PermissionRegistrar::class);
return $this->belongsToMany(
config('permission.models.role'),
config('permission.table_names.role_has_permissions'),
$registrar->pivotPermission,
$registrar->pivotRole
);
}
/**
* A permission belongs to some users of the model associated with its guard.
*/
public function users(): BelongsToMany
{
return $this->morphedByMany(
getModelForGuard($this->attributes['guard_name'] ?? config('auth.defaults.guard')),
'model',
config('permission.table_names.model_has_permissions'),
app(PermissionRegistrar::class)->pivotPermission,
config('permission.column_names.model_morph_key')
);
}
/**
* Find a permission by its name (and optionally guardName).
*
* @return PermissionContract|Permission
*
* @throws PermissionDoesNotExist
*/
public static function findByName(string $name, ?string $guardName = null): PermissionContract
{
$guardName ??= Guard::getDefaultName(static::class);
$permission = static::getPermission(['name' => $name, 'guard_name' => $guardName]);
if (! $permission) {
throw PermissionDoesNotExist::create($name, $guardName);
}
return $permission;
}
/**
* Find a permission by its id (and optionally guardName).
*
* @return PermissionContract|Permission
*
* @throws PermissionDoesNotExist
*/
public static function findById(int|string $id, ?string $guardName = null): PermissionContract
{
$guardName ??= Guard::getDefaultName(static::class);
$permission = static::getPermission([(new static)->getKeyName() => $id, 'guard_name' => $guardName]);
if (! $permission) {
throw PermissionDoesNotExist::withId($id, $guardName);
}
return $permission;
}
/**
* Find or create permission by its name (and optionally guardName).
*
* @return PermissionContract|Permission
*/
public static function findOrCreate(string $name, ?string $guardName = null): PermissionContract
{
$guardName ??= Guard::getDefaultName(static::class);
$permission = static::getPermission(['name' => $name, 'guard_name' => $guardName]);
if (! $permission) {
return static::query()->create(['name' => $name, 'guard_name' => $guardName]);
}
return $permission;
}
/**
* Get the current cached permissions.
*/
protected static function getPermissions(array $params = [], bool $onlyOne = false): Collection
{
return app(PermissionRegistrar::class)
->setPermissionClass(static::class)
->getPermissions($params, $onlyOne);
}
/**
* Get the current cached first permission.
*
* @return PermissionContract|Permission|null
*/
protected static function getPermission(array $params = []): ?PermissionContract
{
/** @var PermissionContract|null */
return static::getPermissions($params, true)->first();
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/Commands/CreatePermission.php | src/Commands/CreatePermission.php | <?php
namespace Spatie\Permission\Commands;
use Illuminate\Console\Command;
use Spatie\Permission\Contracts\Permission as PermissionContract;
class CreatePermission extends Command
{
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()
{
$permissionClass = app(PermissionContract::class);
$permission = $permissionClass::findOrCreate($this->argument('name'), $this->argument('guard'));
$this->info("Permission `{$permission->name}` ".($permission->wasRecentlyCreated ? 'created' : 'already exists'));
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/Commands/CacheReset.php | src/Commands/CacheReset.php | <?php
namespace Spatie\Permission\Commands;
use Illuminate\Console\Command;
use Spatie\Permission\PermissionRegistrar;
class CacheReset extends Command
{
protected $signature = 'permission:cache-reset';
protected $description = 'Reset the permission cache';
public function handle()
{
$permissionRegistrar = app(PermissionRegistrar::class);
$cacheExists = $permissionRegistrar->getCacheRepository()->has($permissionRegistrar->cacheKey);
if ($permissionRegistrar->forgetCachedPermissions()) {
$this->info('Permission cache flushed.');
} elseif ($cacheExists) {
$this->error('Unable to flush cache.');
}
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/Commands/AssignRole.php | src/Commands/AssignRole.php | <?php
namespace Spatie\Permission\Commands;
use Illuminate\Console\Command;
use Spatie\Permission\Contracts\Role as RoleContract;
class AssignRole extends Command
{
protected $signature = 'permission:assign-role
{name : The name of the role}
{userId : The ID of the user to assign the role to}
{guard? : The name of the guard}
{userModelNamespace=App\Models\User : The fully qualified class name of the user model}';
protected $description = 'Assign a role to a user. (Note: does not support Teams.)';
public function handle()
{
$roleName = $this->argument('name');
$userId = $this->argument('userId');
$guardName = $this->argument('guard');
$userModelClass = $this->argument('userModelNamespace');
// Validate that the model class exists and is instantiable
if (! class_exists($userModelClass)) {
$this->error("User model class [{$userModelClass}] does not exist.");
return Command::FAILURE;
}
$user = (new $userModelClass)::find($userId);
if (! $user) {
$this->error("User with ID {$userId} not found.");
return Command::FAILURE;
}
/** @var \Spatie\Permission\Contracts\Role $roleClass */
$roleClass = app(RoleContract::class);
$role = $roleClass::findOrCreate($roleName, $guardName);
$user->assignRole($role);
$this->info("Role `{$role->name}` assigned to user ID {$userId} successfully.");
return Command::SUCCESS;
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/Commands/Show.php | src/Commands/Show.php | <?php
namespace Spatie\Permission\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Spatie\Permission\Contracts\Permission as PermissionContract;
use Spatie\Permission\Contracts\Role as RoleContract;
use Symfony\Component\Console\Helper\TableCell;
class Show extends Command
{
protected $signature = 'permission:show
{guard? : The name of the guard}
{style? : The display style (default|borderless|compact|box)}';
protected $description = 'Show a table of roles and permissions per guard';
public function handle()
{
$permissionClass = app(PermissionContract::class);
$roleClass = app(RoleContract::class);
$teamsEnabled = config('permission.teams');
$team_key = config('permission.column_names.team_foreign_key');
$style = $this->argument('style') ?? 'default';
$guard = $this->argument('guard');
if ($guard) {
$guards = Collection::make([$guard]);
} else {
$guards = $permissionClass::pluck('guard_name')->merge($roleClass::pluck('guard_name'))->unique();
}
foreach ($guards as $guard) {
$this->info("Guard: $guard");
$roles = $roleClass::whereGuardName($guard)
->with('permissions')
->when($teamsEnabled, fn ($q) => $q->orderBy($team_key))
->orderBy('name')->get()->mapWithKeys(fn ($role) => [
$role->name.'_'.($teamsEnabled ? ($role->$team_key ?: '') : '') => [
'permissions' => $role->permissions->pluck($permissionClass->getKeyName()),
$team_key => $teamsEnabled ? $role->$team_key : null,
],
]);
$permissions = $permissionClass::whereGuardName($guard)->orderBy('name')->pluck('name', $permissionClass->getKeyName());
$body = $permissions->map(fn ($permission, $id) => $roles->map(
fn (array $role_data) => $role_data['permissions']->contains($id) ? ' ✔' : ' ·'
)->prepend($permission)
);
if ($teamsEnabled) {
$teams = $roles->groupBy($team_key)->values()->map(
fn ($group, $id) => new TableCell('Team ID: '.($id ?: 'NULL'), ['colspan' => $group->count()])
);
}
$this->table(
array_merge(
isset($teams) ? $teams->prepend(new TableCell(''))->toArray() : [],
$roles->keys()->map(function ($val) {
$name = explode('_', $val);
array_pop($name);
return implode('_', $name);
})
->prepend(new TableCell(''))->toArray(),
),
$body->toArray(),
$style
);
}
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/Commands/UpgradeForTeams.php | src/Commands/UpgradeForTeams.php | <?php
namespace Spatie\Permission\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Config;
class UpgradeForTeams extends Command
{
protected $signature = 'permission:setup-teams';
protected $description = 'Setup the teams feature by generating the associated migration.';
protected $migrationSuffix = 'add_teams_fields.php';
public function handle()
{
if (! Config::get('permission.teams')) {
$this->error('Teams feature is disabled in your permission.php file.');
$this->warn('Please enable the teams setting in your configuration.');
return;
}
$this->line('');
$this->info('The teams feature setup is going to add a migration and a model');
$existingMigrations = $this->alreadyExistingMigrations();
if ($existingMigrations) {
$this->line('');
$this->warn($this->getExistingMigrationsWarning($existingMigrations));
}
$this->line('');
if (! $this->confirm('Proceed with the migration creation?', true)) {
return;
}
$this->line('');
$this->line('Creating migration');
if ($this->createMigration()) {
$this->info('Migration created successfully.');
} else {
$this->error(
"Couldn't create migration.\n".
'Check the write permissions within the database/migrations directory.'
);
}
$this->line('');
}
/**
* Create the migration.
*
* @return bool
*/
protected function createMigration()
{
try {
$migrationStub = __DIR__."/../../database/migrations/{$this->migrationSuffix}.stub";
copy($migrationStub, $this->getMigrationPath());
return true;
} catch (\Throwable $e) {
$this->error($e->getMessage());
return false;
}
}
/**
* Build a warning regarding possible duplication
* due to already existing migrations.
*
* @return string
*/
protected function getExistingMigrationsWarning(array $existingMigrations)
{
if (count($existingMigrations) > 1) {
$base = "Setup teams migrations already exist.\nFollowing files were found: ";
} else {
$base = "Setup teams migration already exists.\nFollowing file was found: ";
}
return $base.array_reduce($existingMigrations, fn ($carry, $fileName) => $carry."\n - ".$fileName);
}
/**
* Check if there is another migration
* with the same suffix.
*
* @return array
*/
protected function alreadyExistingMigrations()
{
$matchingFiles = glob($this->getMigrationPath('*'));
return array_map(fn ($path) => basename($path), $matchingFiles);
}
/**
* Get the migration path.
*
* The date parameter is optional for ability
* to provide a custom value or a wildcard.
*
* @param string|null $date
* @return string
*/
protected function getMigrationPath($date = null)
{
$date = $date ?: date('Y_m_d_His');
return database_path("migrations/{$date}_{$this->migrationSuffix}");
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/Commands/CreateRole.php | src/Commands/CreateRole.php | <?php
namespace Spatie\Permission\Commands;
use Illuminate\Console\Command;
use Spatie\Permission\Contracts\Permission as PermissionContract;
use Spatie\Permission\Contracts\Role as RoleContract;
use Spatie\Permission\PermissionRegistrar;
class CreateRole extends Command
{
protected $signature = 'permission:create-role
{name : The name of the role}
{guard? : The name of the guard}
{permissions? : A list of permissions to assign to the role, separated by | }
{--team-id=}';
protected $description = 'Create a role';
public function handle(PermissionRegistrar $permissionRegistrar)
{
$roleClass = app(RoleContract::class);
$teamIdAux = getPermissionsTeamId();
setPermissionsTeamId($this->option('team-id') ?: null);
if (! $permissionRegistrar->teams && $this->option('team-id')) {
$this->warn('Teams feature disabled, argument --team-id has no effect. Either enable it in permissions config file or remove --team-id parameter');
return;
}
$role = $roleClass::findOrCreate($this->argument('name'), $this->argument('guard'));
setPermissionsTeamId($teamIdAux);
$teams_key = $permissionRegistrar->teamsKey;
if ($permissionRegistrar->teams && $this->option('team-id') && is_null($role->$teams_key)) {
$this->warn("Role `{$role->name}` already exists on the global team; argument --team-id has no effect");
}
$role->givePermissionTo($this->makePermissions($this->argument('permissions')));
$this->info("Role `{$role->name}` ".($role->wasRecentlyCreated ? 'created' : 'updated'));
}
/**
* @param array|null|string $string
*/
protected function makePermissions($string = null)
{
if (empty($string)) {
return;
}
$permissionClass = app(PermissionContract::class);
$permissions = explode('|', $string);
$models = [];
foreach ($permissions as $permission) {
$models[] = $permissionClass::findOrCreate(trim($permission), $this->argument('guard'));
}
return collect($models);
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/Events/PermissionAttached.php | src/Events/PermissionAttached.php | <?php
declare(strict_types=1);
namespace Spatie\Permission\Events;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Collection;
use Spatie\Permission\Contracts\Permission;
class PermissionAttached
{
use Dispatchable;
use InteractsWithSockets;
use SerializesModels;
/**
* Internally the HasPermissions trait passes an array of permission ids (eg: int's or uuid's)
* Theoretically one could register the event to other places and pass an Eloquent record.
* So a Listener should inspect the type of $permissionsOrIds received before using.
*
* @param array|int[]|string[]|Permission|Permission[]|Collection $permissionsOrIds
*/
public function __construct(public Model $model, public mixed $permissionsOrIds) {}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/Events/RoleAttached.php | src/Events/RoleAttached.php | <?php
declare(strict_types=1);
namespace Spatie\Permission\Events;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Collection;
use Spatie\Permission\Contracts\Role;
class RoleAttached
{
use Dispatchable;
use InteractsWithSockets;
use SerializesModels;
/**
* Internally the HasRoles trait passes an array of role ids (eg: int's or uuid's)
* Theoretically one could register the event to other places passing other types
* So a Listener should inspect the type of $rolesOrIds received before using.
*
* @param array|int[]|string[]|Role|Role[]|Collection $rolesOrIds
*/
public function __construct(public Model $model, public mixed $rolesOrIds) {}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/Events/RoleDetached.php | src/Events/RoleDetached.php | <?php
declare(strict_types=1);
namespace Spatie\Permission\Events;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Collection;
use Spatie\Permission\Contracts\Role;
class RoleDetached
{
use Dispatchable;
use InteractsWithSockets;
use SerializesModels;
/**
* Internally the HasRoles trait passes an array of role ids (eg: int's or uuid's)
* Theoretically one could register the event to other places passing other types
* So a Listener should inspect the type of $rolesOrIds received before using.
*
* @param array|int[]|string[]|Role|Role[]|Collection $rolesOrIds
*/
public function __construct(public Model $model, public mixed $rolesOrIds) {}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/Events/PermissionDetached.php | src/Events/PermissionDetached.php | <?php
declare(strict_types=1);
namespace Spatie\Permission\Events;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Collection;
use Spatie\Permission\Contracts\Permission;
class PermissionDetached
{
use Dispatchable;
use InteractsWithSockets;
use SerializesModels;
/**
* Internally the HasPermissions trait passes $permissionsOrIds as an Eloquent record.
* Theoretically one could register the event to other places and pass an array etc.
* So a Listener should inspect the type of $permissionsOrIds received before using.
*
* @param array|int[]|string[]|Permission|Permission[]|Collection $permissionsOrIds
*/
public function __construct(public Model $model, public mixed $permissionsOrIds) {}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/HasRolesTest.php | tests/HasRolesTest.php | <?php
namespace Spatie\Permission\Tests;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Event;
use PHPUnit\Framework\Attributes\RequiresPhp;
use PHPUnit\Framework\Attributes\Test;
use Spatie\Permission\Contracts\Permission;
use Spatie\Permission\Contracts\Role;
use Spatie\Permission\Events\RoleAttached;
use Spatie\Permission\Events\RoleDetached;
use Spatie\Permission\Exceptions\GuardDoesNotMatch;
use Spatie\Permission\Exceptions\RoleDoesNotExist;
use Spatie\Permission\PermissionRegistrar;
use Spatie\Permission\Tests\TestModels\Admin;
use Spatie\Permission\Tests\TestModels\SoftDeletingUser;
use Spatie\Permission\Tests\TestModels\User;
class HasRolesTest extends TestCase
{
/** @test */
#[Test]
public function it_can_determine_that_the_user_does_not_have_a_role()
{
$this->assertFalse($this->testUser->hasRole('testRole'));
$role = app(Role::class)->findOrCreate('testRoleInWebGuard', 'web');
$this->assertFalse($this->testUser->hasRole($role));
$this->testUser->assignRole($role);
$this->assertTrue($this->testUser->hasRole($role));
$this->assertTrue($this->testUser->hasRole($role->name));
$this->assertTrue($this->testUser->hasRole($role->name, $role->guard_name));
$this->assertTrue($this->testUser->hasRole([$role->name, 'fakeRole'], $role->guard_name));
$this->assertTrue($this->testUser->hasRole($role->getKey(), $role->guard_name));
$this->assertTrue($this->testUser->hasRole([$role->getKey(), 'fakeRole'], $role->guard_name));
$this->assertFalse($this->testUser->hasRole($role->name, 'fakeGuard'));
$this->assertFalse($this->testUser->hasRole([$role->name, 'fakeRole'], 'fakeGuard'));
$this->assertFalse($this->testUser->hasRole($role->getKey(), 'fakeGuard'));
$this->assertFalse($this->testUser->hasRole([$role->getKey(), 'fakeRole'], 'fakeGuard'));
$role = app(Role::class)->findOrCreate('testRoleInWebGuard2', 'web');
$this->assertFalse($this->testUser->hasRole($role));
}
/**
* @test
*
* @requires PHP >= 8.1
*/
#[RequiresPhp('>= 8.1')]
#[Test]
public function it_can_assign_and_remove_a_role_using_enums()
{
$enum1 = TestModels\TestRolePermissionsEnum::USERMANAGER;
$enum2 = TestModels\TestRolePermissionsEnum::WRITER;
$enum3 = TestModels\TestRolePermissionsEnum::CASTED_ENUM_1;
$enum4 = TestModels\TestRolePermissionsEnum::CASTED_ENUM_2;
app(Role::class)->findOrCreate($enum1->value, 'web');
app(Role::class)->findOrCreate($enum2->value, 'web');
app(Role::class)->findOrCreate($enum3->value, 'web');
app(Role::class)->findOrCreate($enum4->value, 'web');
$this->assertFalse($this->testUser->hasRole($enum1));
$this->assertFalse($this->testUser->hasRole($enum2));
$this->assertFalse($this->testUser->hasRole($enum3));
$this->assertFalse($this->testUser->hasRole($enum4));
$this->assertFalse($this->testUser->hasRole('user-manager'));
$this->assertFalse($this->testUser->hasRole('writer'));
$this->assertFalse($this->testUser->hasRole('casted_enum-1'));
$this->assertFalse($this->testUser->hasRole('casted_enum-2'));
$this->testUser->assignRole($enum1);
$this->testUser->assignRole($enum2);
$this->testUser->assignRole($enum3);
$this->testUser->assignRole($enum4);
$this->assertTrue($this->testUser->hasRole($enum1));
$this->assertTrue($this->testUser->hasRole($enum2));
$this->assertTrue($this->testUser->hasRole($enum3));
$this->assertTrue($this->testUser->hasRole($enum4));
$this->assertTrue($this->testUser->hasRole([$enum1, 'writer']));
$this->assertTrue($this->testUser->hasRole([$enum3, 'casted_enum-2']));
$this->assertTrue($this->testUser->hasAllRoles([$enum1, $enum2, $enum3, $enum4]));
$this->assertTrue($this->testUser->hasAllRoles(['user-manager', 'writer', 'casted_enum-1', 'casted_enum-2']));
$this->assertFalse($this->testUser->hasAllRoles([$enum1, $enum2, $enum3, $enum4, 'not exist']));
$this->assertFalse($this->testUser->hasAllRoles(['user-manager', 'writer', 'casted_enum-1', 'casted_enum-2', 'not exist']));
$this->assertTrue($this->testUser->hasExactRoles([$enum4, $enum3, $enum2, $enum1]));
$this->assertTrue($this->testUser->hasExactRoles(['user-manager', 'writer', 'casted_enum-1', 'casted_enum-2']));
$this->testUser->removeRole($enum1);
$this->assertFalse($this->testUser->hasRole($enum1));
}
/**
* @test
*
* @requires PHP >= 8.1
*/
#[RequiresPhp('>= 8.1')]
#[Test]
public function it_can_scope_a_role_using_enums()
{
$enum1 = TestModels\TestRolePermissionsEnum::USERMANAGER;
$enum2 = TestModels\TestRolePermissionsEnum::WRITER;
$role1 = app(Role::class)->findOrCreate($enum1->value, 'web');
$role2 = app(Role::class)->findOrCreate($enum2->value, 'web');
User::all()->each(fn ($item) => $item->delete());
$user1 = User::create(['email' => 'user1@test.com']);
$user2 = User::create(['email' => 'user2@test.com']);
$user3 = User::create(['email' => 'user3@test.com']);
// assign only one user to a role
$user2->assignRole($enum1);
$this->assertTrue($user2->hasRole($enum1));
$this->assertFalse($user2->hasRole($enum2));
$scopedUsers1 = User::role($enum1)->get();
$scopedUsers2 = User::role($enum2)->get();
$scopedUsers3 = User::withoutRole($enum2)->get();
$this->assertEquals(1, $scopedUsers1->count());
$this->assertEquals(0, $scopedUsers2->count());
$this->assertEquals(3, $scopedUsers3->count());
}
/** @test */
#[Test]
public function it_can_assign_and_remove_a_role()
{
$this->assertFalse($this->testUser->hasRole('testRole'));
$this->testUser->assignRole('testRole');
$this->assertTrue($this->testUser->hasRole('testRole'));
$this->testUser->removeRole('testRole');
$this->assertFalse($this->testUser->hasRole('testRole'));
}
/** @test */
#[Test]
public function it_removes_a_role_and_returns_roles()
{
$this->testUser->assignRole('testRole');
$this->testUser->assignRole('testRole2');
$this->assertTrue($this->testUser->hasRole(['testRole', 'testRole2']));
$roles = $this->testUser->removeRole('testRole');
$this->assertFalse($roles->hasRole('testRole'));
$this->assertTrue($roles->hasRole('testRole2'));
}
/** @test */
#[Test]
public function it_can_assign_and_remove_a_role_on_a_permission()
{
$this->testUserPermission->assignRole('testRole');
$this->assertTrue($this->testUserPermission->hasRole('testRole'));
$this->testUserPermission->removeRole('testRole');
$this->assertFalse($this->testUserPermission->hasRole('testRole'));
}
/** @test */
#[Test]
public function it_can_assign_and_remove_a_role_using_an_object()
{
$this->testUser->assignRole($this->testUserRole);
$this->assertTrue($this->testUser->hasRole($this->testUserRole));
$this->testUser->removeRole($this->testUserRole);
$this->assertFalse($this->testUser->hasRole($this->testUserRole));
}
/** @test */
#[Test]
public function it_can_assign_and_remove_a_role_using_an_id()
{
$this->testUser->assignRole($this->testUserRole->getKey());
$this->assertTrue($this->testUser->hasRole($this->testUserRole));
$this->testUser->removeRole($this->testUserRole->getKey());
$this->assertFalse($this->testUser->hasRole($this->testUserRole));
}
/** @test */
#[Test]
public function it_can_assign_and_remove_multiple_roles_at_once()
{
$this->testUser->assignRole($this->testUserRole->getKey(), 'testRole2');
$this->assertTrue($this->testUser->hasRole('testRole'));
$this->assertTrue($this->testUser->hasRole('testRole2'));
$this->testUser->removeRole($this->testUserRole->getKey(), 'testRole2');
$this->assertFalse($this->testUser->hasRole('testRole'));
$this->assertFalse($this->testUser->hasRole('testRole2'));
}
/** @test */
#[Test]
public function it_can_assign_and_remove_multiple_roles_using_an_array()
{
$this->testUser->assignRole([$this->testUserRole->getKey(), 'testRole2']);
$this->assertTrue($this->testUser->hasRole('testRole'));
$this->assertTrue($this->testUser->hasRole('testRole2'));
$this->testUser->removeRole([$this->testUserRole->getKey(), 'testRole2']);
$this->assertFalse($this->testUser->hasRole('testRole'));
$this->assertFalse($this->testUser->hasRole('testRole2'));
}
/** @test */
#[Test]
public function it_does_not_remove_already_associated_roles_when_assigning_new_roles()
{
$this->testUser->assignRole($this->testUserRole->getKey());
$this->testUser->assignRole('testRole2');
$this->assertTrue($this->testUser->fresh()->hasRole('testRole'));
}
/** @test */
#[Test]
public function it_does_not_throw_an_exception_when_assigning_a_role_that_is_already_assigned()
{
$this->testUser->assignRole($this->testUserRole->getKey());
$this->testUser->assignRole($this->testUserRole->getKey());
$this->assertTrue($this->testUser->fresh()->hasRole('testRole'));
}
/** @test */
#[Test]
public function it_throws_an_exception_when_assigning_a_role_that_does_not_exist()
{
$this->expectException(RoleDoesNotExist::class);
$this->testUser->assignRole('evil-emperor');
}
/** @test */
#[Test]
public function it_can_only_assign_roles_from_the_correct_guard()
{
$this->expectException(RoleDoesNotExist::class);
$this->testUser->assignRole('testAdminRole');
}
/** @test */
#[Test]
public function it_throws_an_exception_when_assigning_a_role_from_a_different_guard()
{
$this->expectException(GuardDoesNotMatch::class);
$this->testUser->assignRole($this->testAdminRole);
}
/** @test */
#[Test]
public function it_ignores_null_roles_when_syncing()
{
$this->testUser->assignRole('testRole');
$this->testUser->syncRoles('testRole2', null);
$this->assertFalse($this->testUser->hasRole('testRole'));
$this->assertTrue($this->testUser->hasRole('testRole2'));
}
/** @test */
#[Test]
public function it_can_sync_roles_from_a_string()
{
$this->testUser->assignRole('testRole');
$this->testUser->syncRoles('testRole2');
$this->assertFalse($this->testUser->hasRole('testRole'));
$this->assertTrue($this->testUser->hasRole('testRole2'));
}
/** @test */
#[Test]
public function it_can_sync_roles_from_a_string_on_a_permission()
{
$this->testUserPermission->assignRole('testRole');
$this->testUserPermission->syncRoles('testRole2');
$this->assertFalse($this->testUserPermission->hasRole('testRole'));
$this->assertTrue($this->testUserPermission->hasRole('testRole2'));
}
/** @test */
#[Test]
public function it_can_avoid_sync_duplicated_roles()
{
$this->testUser->syncRoles('testRole', 'testRole', 'testRole2');
$this->assertTrue($this->testUser->hasRole('testRole'));
$this->assertTrue($this->testUser->hasRole('testRole2'));
}
/** @test */
#[Test]
public function it_can_avoid_detach_on_role_that_does_not_exist_sync()
{
$this->testUser->syncRoles('testRole');
try {
$this->testUser->syncRoles('role-does-not-exist');
$this->fail('Expected RoleDoesNotExist exception was not thrown.');
} catch (RoleDoesNotExist $e) {
//
}
$this->assertTrue($this->testUser->hasRole('testRole'));
$this->assertFalse($this->testUser->hasRole('role-does-not-exist'));
}
/** @test */
#[Test]
public function it_can_sync_multiple_roles()
{
$this->testUser->syncRoles('testRole', 'testRole2');
$this->assertTrue($this->testUser->hasRole('testRole'));
$this->assertTrue($this->testUser->hasRole('testRole2'));
}
/** @test */
#[Test]
public function it_can_sync_multiple_roles_from_an_array()
{
$this->testUser->syncRoles(['testRole', 'testRole2']);
$this->assertTrue($this->testUser->hasRole('testRole'));
$this->assertTrue($this->testUser->hasRole('testRole2'));
}
/** @test */
#[Test]
public function it_will_remove_all_roles_when_an_empty_array_is_passed_to_sync_roles()
{
$this->testUser->assignRole('testRole');
$this->testUser->assignRole('testRole2');
$this->testUser->syncRoles([]);
$this->assertFalse($this->testUser->hasRole('testRole'));
$this->assertFalse($this->testUser->hasRole('testRole2'));
}
/** @test */
#[Test]
public function sync_roles_error_does_not_detach_roles()
{
$this->testUser->assignRole('testRole');
$this->expectException(RoleDoesNotExist::class);
$this->testUser->syncRoles('testRole2', 'role-that-does-not-exist');
$this->assertTrue($this->testUser->fresh()->hasRole('testRole'));
}
/** @test */
#[Test]
public function it_will_sync_roles_to_a_model_that_is_not_persisted()
{
$user = new User(['email' => 'test@user.com']);
$user->syncRoles([$this->testUserRole]);
$user->save();
$user->save(); // test save same model twice
$this->assertTrue($user->hasRole($this->testUserRole));
$user->syncRoles([$this->testUserRole]);
$this->assertTrue($user->hasRole($this->testUserRole));
$this->assertTrue($user->fresh()->hasRole($this->testUserRole));
}
/** @test */
#[Test]
public function it_does_not_run_unnecessary_sqls_when_assigning_new_roles()
{
$role2 = app(Role::class)->where('name', ['testRole2'])->first();
DB::enableQueryLog();
$this->testUser->syncRoles($this->testUserRole, $role2);
DB::disableQueryLog();
$necessaryQueriesCount = 2;
// Teams reloads relation, adding an extra query
if (app(PermissionRegistrar::class)->teams) {
$necessaryQueriesCount++;
}
$this->assertCount($necessaryQueriesCount, DB::getQueryLog());
}
/** @test */
#[Test]
public function calling_syncRoles_before_saving_object_doesnt_interfere_with_other_objects()
{
$user = new User(['email' => 'test@user.com']);
$user->syncRoles('testRole');
$user->save();
$user2 = new User(['email' => 'admin@user.com']);
$user2->syncRoles('testRole2');
DB::enableQueryLog();
$user2->save();
DB::disableQueryLog();
$this->assertTrue($user->fresh()->hasRole('testRole'));
$this->assertFalse($user->fresh()->hasRole('testRole2'));
$this->assertTrue($user2->fresh()->hasRole('testRole2'));
$this->assertFalse($user2->fresh()->hasRole('testRole'));
$this->assertSame(2, count(DB::getQueryLog())); // avoid unnecessary sync
}
/** @test */
#[Test]
public function calling_assignRole_before_saving_object_doesnt_interfere_with_other_objects()
{
$user = new User(['email' => 'test@user.com']);
$user->assignRole('testRole');
$user->save();
$admin_user = new User(['email' => 'admin@user.com']);
$admin_user->assignRole('testRole2');
DB::enableQueryLog();
$admin_user->save();
DB::disableQueryLog();
$this->assertTrue($user->fresh()->hasRole('testRole'));
$this->assertFalse($user->fresh()->hasRole('testRole2'));
$this->assertTrue($admin_user->fresh()->hasRole('testRole2'));
$this->assertFalse($admin_user->fresh()->hasRole('testRole'));
$this->assertSame(2, count(DB::getQueryLog())); // avoid unnecessary sync
}
/** @test */
#[Test]
public function it_throws_an_exception_when_syncing_a_role_from_another_guard()
{
$this->expectException(RoleDoesNotExist::class);
$this->testUser->syncRoles('testRole', 'testAdminRole');
$this->expectException(GuardDoesNotMatch::class);
$this->testUser->syncRoles('testRole', $this->testAdminRole);
}
/** @test */
#[Test]
public function it_deletes_pivot_table_entries_when_deleting_models()
{
$user = User::create(['email' => 'user@test.com']);
$user->assignRole('testRole');
$user->givePermissionTo('edit-articles');
$this->assertDatabaseHas('model_has_permissions', [config('permission.column_names.model_morph_key') => $user->id]);
$this->assertDatabaseHas('model_has_roles', [config('permission.column_names.model_morph_key') => $user->id]);
$user->delete();
$this->assertDatabaseMissing('model_has_permissions', [config('permission.column_names.model_morph_key') => $user->id]);
$this->assertDatabaseMissing('model_has_roles', [config('permission.column_names.model_morph_key') => $user->id]);
}
/** @test */
#[Test]
public function it_can_scope_users_using_a_string()
{
$user1 = User::create(['email' => 'user1@test.com']);
$user2 = User::create(['email' => 'user2@test.com']);
$user1->assignRole('testRole');
$user2->assignRole('testRole2');
$scopedUsers = User::role('testRole')->get();
$this->assertEquals(1, $scopedUsers->count());
}
/** @test */
#[Test]
public function it_can_withoutscope_users_using_a_string()
{
User::all()->each(fn ($item) => $item->delete());
$user1 = User::create(['email' => 'user1@test.com']);
$user2 = User::create(['email' => 'user2@test.com']);
$user3 = User::create(['email' => 'user3@test.com']);
$user1->assignRole('testRole');
$user2->assignRole('testRole2');
$user3->assignRole('testRole2');
$scopedUsers = User::withoutRole('testRole2')->get();
$this->assertEquals(1, $scopedUsers->count());
}
/** @test */
#[Test]
public function it_can_scope_users_using_an_array()
{
$user1 = User::create(['email' => 'user1@test.com']);
$user2 = User::create(['email' => 'user2@test.com']);
$user1->assignRole($this->testUserRole);
$user2->assignRole('testRole2');
$scopedUsers1 = User::role([$this->testUserRole])->get();
$scopedUsers2 = User::role(['testRole', 'testRole2'])->get();
$this->assertEquals(1, $scopedUsers1->count());
$this->assertEquals(2, $scopedUsers2->count());
}
/** @test */
#[Test]
public function it_can_withoutscope_users_using_an_array()
{
User::all()->each(fn ($item) => $item->delete());
$user1 = User::create(['email' => 'user1@test.com']);
$user2 = User::create(['email' => 'user2@test.com']);
$user3 = User::create(['email' => 'user3@test.com']);
$user1->assignRole($this->testUserRole);
$user2->assignRole('testRole2');
$user3->assignRole('testRole2');
$scopedUsers1 = User::withoutRole([$this->testUserRole])->get();
$scopedUsers2 = User::withoutRole([$this->testUserRole->name, 'testRole2'])->get();
$this->assertEquals(2, $scopedUsers1->count());
$this->assertEquals(0, $scopedUsers2->count());
}
/** @test */
#[Test]
public function it_can_scope_users_using_an_array_of_ids_and_names()
{
$user1 = User::create(['email' => 'user1@test.com']);
$user2 = User::create(['email' => 'user2@test.com']);
$user1->assignRole($this->testUserRole);
$user2->assignRole('testRole2');
$firstAssignedRoleName = $this->testUserRole->name;
$secondAssignedRoleId = app(Role::class)->findByName('testRole2')->getKey();
$scopedUsers = User::role([$firstAssignedRoleName, $secondAssignedRoleId])->get();
$this->assertEquals(2, $scopedUsers->count());
}
/** @test */
#[Test]
public function it_can_withoutscope_users_using_an_array_of_ids_and_names()
{
app(Role::class)->create(['name' => 'testRole3']);
User::all()->each(fn ($item) => $item->delete());
$user1 = User::create(['email' => 'user1@test.com']);
$user2 = User::create(['email' => 'user2@test.com']);
$user3 = User::create(['email' => 'user3@test.com']);
$user1->assignRole($this->testUserRole);
$user2->assignRole('testRole2');
$user3->assignRole('testRole2');
$firstAssignedRoleName = $this->testUserRole->name;
$unassignedRoleId = app(Role::class)->findByName('testRole3')->getKey();
$scopedUsers = User::withoutRole([$firstAssignedRoleName, $unassignedRoleId])->get();
$this->assertEquals(2, $scopedUsers->count());
}
/** @test */
#[Test]
public function it_can_scope_users_using_a_collection()
{
$user1 = User::create(['email' => 'user1@test.com']);
$user2 = User::create(['email' => 'user2@test.com']);
$user1->assignRole($this->testUserRole);
$user2->assignRole('testRole2');
$scopedUsers1 = User::role([$this->testUserRole])->get();
$scopedUsers2 = User::role(collect(['testRole', 'testRole2']))->get();
$this->assertEquals(1, $scopedUsers1->count());
$this->assertEquals(2, $scopedUsers2->count());
}
/** @test */
#[Test]
public function it_can_withoutscope_users_using_a_collection()
{
app(Role::class)->create(['name' => 'testRole3']);
User::all()->each(fn ($item) => $item->delete());
$user1 = User::create(['email' => 'user1@test.com']);
$user2 = User::create(['email' => 'user2@test.com']);
$user3 = User::create(['email' => 'user3@test.com']);
$user1->assignRole($this->testUserRole);
$user2->assignRole('testRole');
$user3->assignRole('testRole2');
$scopedUsers1 = User::withoutRole([$this->testUserRole])->get();
$scopedUsers2 = User::withoutRole(collect(['testRole', 'testRole3']))->get();
$this->assertEquals(1, $scopedUsers1->count());
$this->assertEquals(1, $scopedUsers2->count());
}
/** @test */
#[Test]
public function it_can_scope_users_using_an_object()
{
$user1 = User::create(['email' => 'user1@test.com']);
$user2 = User::create(['email' => 'user2@test.com']);
$user1->assignRole($this->testUserRole);
$user2->assignRole('testRole2');
$scopedUsers1 = User::role($this->testUserRole)->get();
$scopedUsers2 = User::role([$this->testUserRole])->get();
$scopedUsers3 = User::role(collect([$this->testUserRole]))->get();
$this->assertEquals(1, $scopedUsers1->count());
$this->assertEquals(1, $scopedUsers2->count());
$this->assertEquals(1, $scopedUsers3->count());
}
/** @test */
#[Test]
public function it_can_withoutscope_users_using_an_object()
{
User::all()->each(fn ($item) => $item->delete());
$user1 = User::create(['email' => 'user1@test.com']);
$user2 = User::create(['email' => 'user2@test.com']);
$user3 = User::create(['email' => 'user3@test.com']);
$user1->assignRole($this->testUserRole);
$user2->assignRole('testRole2');
$user3->assignRole('testRole2');
$scopedUsers1 = User::withoutRole($this->testUserRole)->get();
$scopedUsers2 = User::withoutRole([$this->testUserRole])->get();
$scopedUsers3 = User::withoutRole(collect([$this->testUserRole]))->get();
$this->assertEquals(2, $scopedUsers1->count());
$this->assertEquals(2, $scopedUsers2->count());
$this->assertEquals(2, $scopedUsers3->count());
}
/** @test */
#[Test]
public function it_can_scope_against_a_specific_guard()
{
$user1 = User::create(['email' => 'user1@test.com']);
$user2 = User::create(['email' => 'user2@test.com']);
$user1->assignRole('testRole');
$user2->assignRole('testRole2');
$scopedUsers1 = User::role('testRole', 'web')->get();
$this->assertEquals(1, $scopedUsers1->count());
$user3 = Admin::create(['email' => 'user3@test.com']);
$user4 = Admin::create(['email' => 'user4@test.com']);
$user5 = Admin::create(['email' => 'user5@test.com']);
$testAdminRole2 = app(Role::class)->create(['name' => 'testAdminRole2', 'guard_name' => 'admin']);
$user3->assignRole($this->testAdminRole);
$user4->assignRole($this->testAdminRole);
$user5->assignRole($testAdminRole2);
$scopedUsers2 = Admin::role('testAdminRole', 'admin')->get();
$scopedUsers3 = Admin::role('testAdminRole2', 'admin')->get();
$this->assertEquals(2, $scopedUsers2->count());
$this->assertEquals(1, $scopedUsers3->count());
}
/** @test */
#[Test]
public function it_can_withoutscope_against_a_specific_guard()
{
User::all()->each(fn ($item) => $item->delete());
$user1 = User::create(['email' => 'user1@test.com']);
$user2 = User::create(['email' => 'user2@test.com']);
$user3 = User::create(['email' => 'user3@test.com']);
$user1->assignRole('testRole');
$user2->assignRole('testRole2');
$user3->assignRole('testRole2');
$scopedUsers1 = User::withoutRole('testRole', 'web')->get();
$this->assertEquals(2, $scopedUsers1->count());
Admin::all()->each(fn ($item) => $item->delete());
$user4 = Admin::create(['email' => 'user4@test.com']);
$user5 = Admin::create(['email' => 'user5@test.com']);
$user6 = Admin::create(['email' => 'user6@test.com']);
$testAdminRole2 = app(Role::class)->create(['name' => 'testAdminRole2', 'guard_name' => 'admin']);
$user4->assignRole($this->testAdminRole);
$user5->assignRole($this->testAdminRole);
$user6->assignRole($testAdminRole2);
$scopedUsers2 = Admin::withoutRole('testAdminRole', 'admin')->get();
$scopedUsers3 = Admin::withoutRole('testAdminRole2', 'admin')->get();
$this->assertEquals(1, $scopedUsers2->count());
$this->assertEquals(2, $scopedUsers3->count());
}
/** @test */
#[Test]
public function it_throws_an_exception_when_trying_to_scope_a_role_from_another_guard()
{
$this->expectException(RoleDoesNotExist::class);
User::role('testAdminRole')->get();
$this->expectException(GuardDoesNotMatch::class);
User::role($this->testAdminRole)->get();
}
/** @test */
#[Test]
public function it_throws_an_exception_when_trying_to_call_withoutscope_on_a_role_from_another_guard()
{
$this->expectException(RoleDoesNotExist::class);
User::withoutRole('testAdminRole')->get();
$this->expectException(GuardDoesNotMatch::class);
User::withoutRole($this->testAdminRole)->get();
}
/** @test */
#[Test]
public function it_throws_an_exception_when_trying_to_scope_a_non_existing_role()
{
$this->expectException(RoleDoesNotExist::class);
User::role('role not defined')->get();
}
/** @test */
#[Test]
public function it_throws_an_exception_when_trying_to_use_withoutscope_on_a_non_existing_role()
{
$this->expectException(RoleDoesNotExist::class);
User::withoutRole('role not defined')->get();
}
/** @test */
#[Test]
public function it_can_determine_that_a_user_has_one_of_the_given_roles()
{
$roleModel = app(Role::class);
$roleModel->create(['name' => 'second role']);
$this->assertFalse($this->testUser->hasRole($roleModel->all()));
$this->testUser->assignRole($this->testUserRole);
$this->assertTrue($this->testUser->hasRole($roleModel->all()));
$this->assertTrue($this->testUser->hasAnyRole($roleModel->all()));
$this->assertTrue($this->testUser->hasAnyRole('testRole'));
$this->assertFalse($this->testUser->hasAnyRole('role does not exist'));
$this->assertTrue($this->testUser->hasAnyRole(['testRole']));
$this->assertTrue($this->testUser->hasAnyRole(['testRole', 'role does not exist']));
$this->assertFalse($this->testUser->hasAnyRole(['role does not exist']));
$this->assertTrue($this->testUser->hasAnyRole('testRole', 'role does not exist'));
}
/** @test */
#[Test]
public function it_can_determine_that_a_user_has_all_of_the_given_roles()
{
$roleModel = app(Role::class);
$this->assertFalse($this->testUser->hasAllRoles($roleModel->first()));
$this->assertFalse($this->testUser->hasAllRoles('testRole'));
$this->assertFalse($this->testUser->hasAllRoles($roleModel->all()));
$roleModel->create(['name' => 'second role']);
$this->testUser->assignRole($this->testUserRole);
$this->assertTrue($this->testUser->hasAllRoles('testRole'));
$this->assertTrue($this->testUser->hasAllRoles('testRole', 'web'));
$this->assertFalse($this->testUser->hasAllRoles('testRole', 'fakeGuard'));
$this->assertFalse($this->testUser->hasAllRoles(['testRole', 'second role']));
$this->assertFalse($this->testUser->hasAllRoles(['testRole', 'second role'], 'web'));
$this->testUser->assignRole('second role');
$this->assertTrue($this->testUser->hasAllRoles(['testRole', 'second role']));
$this->assertTrue($this->testUser->hasAllRoles(['testRole', 'second role'], 'web'));
$this->assertFalse($this->testUser->hasAllRoles(['testRole', 'second role'], 'fakeGuard'));
}
/** @test */
#[Test]
public function it_can_determine_that_a_user_has_exact_all_of_the_given_roles()
{
$roleModel = app(Role::class);
$this->assertFalse($this->testUser->hasExactRoles($roleModel->first()));
$this->assertFalse($this->testUser->hasExactRoles('testRole'));
$this->assertFalse($this->testUser->hasExactRoles($roleModel->all()));
$roleModel->create(['name' => 'second role']);
$this->testUser->assignRole($this->testUserRole);
$this->assertTrue($this->testUser->hasExactRoles('testRole'));
$this->assertTrue($this->testUser->hasExactRoles('testRole', 'web'));
$this->assertFalse($this->testUser->hasExactRoles('testRole', 'fakeGuard'));
$this->assertFalse($this->testUser->hasExactRoles(['testRole', 'second role']));
$this->assertFalse($this->testUser->hasExactRoles(['testRole', 'second role'], 'web'));
$this->testUser->assignRole('second role');
$this->assertTrue($this->testUser->hasExactRoles(['testRole', 'second role']));
$this->assertTrue($this->testUser->hasExactRoles(['testRole', 'second role'], 'web'));
$this->assertFalse($this->testUser->hasExactRoles(['testRole', 'second role'], 'fakeGuard'));
$roleModel->create(['name' => 'third role']);
$this->testUser->assignRole('third role');
$this->assertFalse($this->testUser->hasExactRoles(['testRole', 'second role']));
$this->assertFalse($this->testUser->hasExactRoles(['testRole', 'second role'], 'web'));
$this->assertFalse($this->testUser->hasExactRoles(['testRole', 'second role'], 'fakeGuard'));
$this->assertTrue($this->testUser->hasExactRoles(['testRole', 'second role', 'third role']));
$this->assertTrue($this->testUser->hasExactRoles(['testRole', 'second role', 'third role'], 'web'));
$this->assertFalse($this->testUser->hasExactRoles(['testRole', 'second role', 'third role'], 'fakeGuard'));
}
/** @test */
#[Test]
public function it_can_determine_that_a_user_does_not_have_a_role_from_another_guard()
{
$this->assertFalse($this->testUser->hasRole('testAdminRole'));
$this->assertFalse($this->testUser->hasRole($this->testAdminRole));
$this->testUser->assignRole('testRole');
$this->assertTrue($this->testUser->hasAnyRole(['testRole', 'testAdminRole']));
$this->assertFalse($this->testUser->hasAnyRole('testAdminRole', $this->testAdminRole));
}
/** @test */
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | true |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/HasPermissionsTest.php | tests/HasPermissionsTest.php | <?php
namespace Spatie\Permission\Tests;
use DB;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Event;
use PHPUnit\Framework\Attributes\RequiresPhp;
use PHPUnit\Framework\Attributes\Test;
use Spatie\Permission\Contracts\Permission;
use Spatie\Permission\Contracts\Role;
use Spatie\Permission\Events\PermissionAttached;
use Spatie\Permission\Events\PermissionDetached;
use Spatie\Permission\Exceptions\GuardDoesNotMatch;
use Spatie\Permission\Exceptions\PermissionDoesNotExist;
use Spatie\Permission\Tests\TestModels\SoftDeletingUser;
use Spatie\Permission\Tests\TestModels\User;
class HasPermissionsTest extends TestCase
{
/** @test */
#[Test]
public function it_can_assign_a_permission_to_a_user()
{
$this->testUser->givePermissionTo($this->testUserPermission);
$this->assertTrue($this->testUser->hasPermissionTo($this->testUserPermission));
}
/** @test */
#[Test]
public function it_can_assign_a_permission_to_a_user_with_a_non_default_guard()
{
$testUserPermission = app(Permission::class)->create([
'name' => 'edit-articles',
'guard_name' => 'api',
]);
$this->testUser->givePermissionTo($testUserPermission);
$this->assertTrue($this->testUser->hasPermissionTo($testUserPermission));
}
/** @test */
#[Test]
public function it_throws_an_exception_when_assigning_a_permission_that_does_not_exist()
{
$this->expectException(PermissionDoesNotExist::class);
$this->testUser->givePermissionTo('permission-does-not-exist');
}
/** @test */
#[Test]
public function it_throws_an_exception_when_assigning_a_permission_to_a_user_from_a_different_guard()
{
$this->expectException(GuardDoesNotMatch::class);
$this->testUser->givePermissionTo($this->testAdminPermission);
$this->expectException(PermissionDoesNotExist::class);
$this->testUser->givePermissionTo('admin-permission');
}
/** @test */
#[Test]
public function it_can_revoke_a_permission_from_a_user()
{
$this->testUser->givePermissionTo($this->testUserPermission);
$this->assertTrue($this->testUser->hasPermissionTo($this->testUserPermission));
$this->testUser->revokePermissionTo($this->testUserPermission);
$this->assertFalse($this->testUser->hasPermissionTo($this->testUserPermission));
}
/**
* @test
*
* @requires PHP >= 8.1
*/
#[RequiresPhp('>= 8.1')]
#[Test]
public function it_can_assign_and_remove_a_permission_using_enums()
{
$enum = TestModels\TestRolePermissionsEnum::VIEWARTICLES;
$permission = app(Permission::class)->findOrCreate($enum->value, 'web');
$this->testUser->givePermissionTo($enum);
$this->assertTrue($this->testUser->hasPermissionTo($enum));
$this->assertTrue($this->testUser->hasAnyPermission($enum));
$this->assertTrue($this->testUser->hasDirectPermission($enum));
$this->testUser->revokePermissionTo($enum);
$this->assertFalse($this->testUser->hasPermissionTo($enum));
$this->assertFalse($this->testUser->hasAnyPermission($enum));
$this->assertFalse($this->testUser->hasDirectPermission($enum));
}
/**
* @test
*
* @requires PHP >= 8.1
*/
#[RequiresPhp('>= 8.1')]
#[Test]
public function it_can_scope_users_using_enums()
{
$enum1 = TestModels\TestRolePermissionsEnum::VIEWARTICLES;
$enum2 = TestModels\TestRolePermissionsEnum::EDITARTICLES;
$permission1 = app(Permission::class)->findOrCreate($enum1->value, 'web');
$permission2 = app(Permission::class)->findOrCreate($enum2->value, 'web');
User::all()->each(fn ($item) => $item->delete());
$user1 = User::create(['email' => 'user1@test.com']);
$user2 = User::create(['email' => 'user2@test.com']);
$user3 = User::create(['email' => 'user3@test.com']);
$user1->givePermissionTo([$enum1, $enum2]);
$this->testUserRole->givePermissionTo($enum2);
$user2->assignRole('testRole');
$scopedUsers1 = User::permission($enum2)->get();
$scopedUsers2 = User::permission([$enum1])->get();
$scopedUsers3 = User::withoutPermission([$enum1])->get();
$scopedUsers4 = User::withoutPermission([$enum2])->get();
$this->assertEquals(2, $scopedUsers1->count());
$this->assertEquals(1, $scopedUsers2->count());
$this->assertEquals(2, $scopedUsers3->count());
$this->assertEquals(1, $scopedUsers4->count());
}
/** @test */
#[Test]
public function it_can_scope_users_using_a_string()
{
User::all()->each(fn ($item) => $item->delete());
$user1 = User::create(['email' => 'user1@test.com']);
$user2 = User::create(['email' => 'user2@test.com']);
$user3 = User::create(['email' => 'user3@test.com']);
$user1->givePermissionTo(['edit-articles', 'edit-news']);
$this->testUserRole->givePermissionTo('edit-articles');
$user2->assignRole('testRole');
$scopedUsers1 = User::permission('edit-articles')->get();
$scopedUsers2 = User::permission(['edit-news'])->get();
$scopedUsers3 = User::withoutPermission('edit-news')->get();
$this->assertEquals(2, $scopedUsers1->count());
$this->assertEquals(1, $scopedUsers2->count());
$this->assertEquals(2, $scopedUsers3->count());
}
/** @test */
#[Test]
public function it_can_scope_users_using_a_int()
{
User::all()->each(fn ($item) => $item->delete());
$user1 = User::create(['email' => 'user1@test.com']);
$user2 = User::create(['email' => 'user2@test.com']);
$user3 = User::create(['email' => 'user3@test.com']);
$user1->givePermissionTo([1, 2]);
$this->testUserRole->givePermissionTo(1);
$user2->assignRole('testRole');
$scopedUsers1 = User::permission(1)->get();
$scopedUsers2 = User::permission([2])->get();
$scopedUsers3 = User::withoutPermission([2])->get();
$this->assertEquals(2, $scopedUsers1->count());
$this->assertEquals(1, $scopedUsers2->count());
$this->assertEquals(2, $scopedUsers3->count());
}
/** @test */
#[Test]
public function it_can_scope_users_using_an_array()
{
User::all()->each(fn ($item) => $item->delete());
$user1 = User::create(['email' => 'user1@test.com']);
$user2 = User::create(['email' => 'user2@test.com']);
$user3 = User::create(['email' => 'user3@test.com']);
$user1->givePermissionTo(['edit-articles', 'edit-news']);
$this->testUserRole->givePermissionTo('edit-articles');
$user2->assignRole('testRole');
$user3->assignRole('testRole2');
$scopedUsers1 = User::permission(['edit-articles', 'edit-news'])->get();
$scopedUsers2 = User::permission(['edit-news'])->get();
$scopedUsers3 = User::withoutPermission(['edit-news'])->get();
$this->assertEquals(2, $scopedUsers1->count());
$this->assertEquals(1, $scopedUsers2->count());
$this->assertEquals(2, $scopedUsers3->count());
}
/** @test */
#[Test]
public function it_can_scope_users_using_a_collection()
{
User::all()->each(fn ($item) => $item->delete());
$user1 = User::create(['email' => 'user1@test.com']);
$user2 = User::create(['email' => 'user2@test.com']);
$user3 = User::create(['email' => 'user3@test.com']);
$user1->givePermissionTo(['edit-articles', 'edit-news']);
$this->testUserRole->givePermissionTo('edit-articles');
$user2->assignRole('testRole');
$user3->assignRole('testRole2');
$scopedUsers1 = User::permission(collect(['edit-articles', 'edit-news']))->get();
$scopedUsers2 = User::permission(collect(['edit-news']))->get();
$scopedUsers3 = User::withoutPermission(collect(['edit-news']))->get();
$this->assertEquals(2, $scopedUsers1->count());
$this->assertEquals(1, $scopedUsers2->count());
$this->assertEquals(2, $scopedUsers3->count());
}
/** @test */
#[Test]
public function it_can_scope_users_using_an_object()
{
User::all()->each(fn ($item) => $item->delete());
$user1 = User::create(['email' => 'user1@test.com']);
$user1->givePermissionTo($this->testUserPermission->name);
$scopedUsers1 = User::permission($this->testUserPermission)->get();
$scopedUsers2 = User::permission([$this->testUserPermission])->get();
$scopedUsers3 = User::permission(collect([$this->testUserPermission]))->get();
$scopedUsers4 = User::withoutPermission(collect([$this->testUserPermission]))->get();
$this->assertEquals(1, $scopedUsers1->count());
$this->assertEquals(1, $scopedUsers2->count());
$this->assertEquals(1, $scopedUsers3->count());
$this->assertEquals(0, $scopedUsers4->count());
}
/** @test */
#[Test]
public function it_can_scope_users_without_direct_permissions_only_role()
{
User::all()->each(fn ($item) => $item->delete());
$user1 = User::create(['email' => 'user1@test.com']);
$user2 = User::create(['email' => 'user2@test.com']);
$user3 = User::create(['email' => 'user3@test.com']);
$this->testUserRole->givePermissionTo('edit-articles');
$user1->assignRole('testRole');
$user2->assignRole('testRole');
$user3->assignRole('testRole2');
$scopedUsers1 = User::permission('edit-articles')->get();
$scopedUsers2 = User::withoutPermission('edit-articles')->get();
$this->assertEquals(2, $scopedUsers1->count());
$this->assertEquals(1, $scopedUsers2->count());
}
/** @test */
#[Test]
public function it_can_scope_users_with_only_direct_permission()
{
User::all()->each(fn ($item) => $item->delete());
$user1 = User::create(['email' => 'user1@test.com']);
$user2 = User::create(['email' => 'user2@test.com']);
$user3 = User::create(['email' => 'user3@test.com']);
$user1->givePermissionTo(['edit-news']);
$user2->givePermissionTo(['edit-articles', 'edit-news']);
$scopedUsers1 = User::permission('edit-news')->get();
$scopedUsers2 = User::withoutPermission('edit-news')->get();
$this->assertEquals(2, $scopedUsers1->count());
$this->assertEquals(1, $scopedUsers2->count());
}
/** @test */
#[Test]
public function it_throws_an_exception_when_calling_hasPermissionTo_with_an_invalid_type()
{
$user = User::create(['email' => 'user1@test.com']);
$this->expectException(PermissionDoesNotExist::class);
$user->hasPermissionTo(new \stdClass);
}
/** @test */
#[Test]
public function it_throws_an_exception_when_calling_hasPermissionTo_with_null()
{
$user = User::create(['email' => 'user1@test.com']);
$this->expectException(PermissionDoesNotExist::class);
$user->hasPermissionTo(null);
}
/** @test */
#[Test]
public function it_throws_an_exception_when_calling_hasDirectPermission_with_an_invalid_type()
{
$user = User::create(['email' => 'user1@test.com']);
$this->expectException(PermissionDoesNotExist::class);
$user->hasDirectPermission(new \stdClass);
}
/** @test */
#[Test]
public function it_throws_an_exception_when_calling_hasDirectPermission_with_null()
{
$user = User::create(['email' => 'user1@test.com']);
$this->expectException(PermissionDoesNotExist::class);
$user->hasDirectPermission(null);
}
/** @test */
#[Test]
public function it_throws_an_exception_when_trying_to_scope_a_non_existing_permission()
{
$this->expectException(PermissionDoesNotExist::class);
User::permission('not defined permission')->get();
$this->expectException(PermissionDoesNotExist::class);
User::withoutPermission('not defined permission')->get();
}
/** @test */
#[Test]
public function it_throws_an_exception_when_trying_to_scope_a_permission_from_another_guard()
{
$this->expectException(PermissionDoesNotExist::class);
User::permission('testAdminPermission')->get();
$this->expectException(PermissionDoesNotExist::class);
User::withoutPermission('testAdminPermission')->get();
$this->expectException(GuardDoesNotMatch::class);
User::permission($this->testAdminPermission)->get();
$this->expectException(GuardDoesNotMatch::class);
User::withoutPermission($this->testAdminPermission)->get();
}
/** @test */
#[Test]
public function it_doesnt_detach_permissions_when_user_soft_deleting()
{
$user = SoftDeletingUser::create(['email' => 'test@example.com']);
$user->givePermissionTo(['edit-news']);
$user->delete();
$user = SoftDeletingUser::withTrashed()->find($user->id);
$this->assertTrue($user->hasPermissionTo('edit-news'));
}
/** @test */
#[Test]
public function it_can_give_and_revoke_multiple_permissions()
{
$this->testUserRole->givePermissionTo(['edit-articles', 'edit-news']);
$this->assertEquals(2, $this->testUserRole->permissions()->count());
$this->testUserRole->revokePermissionTo(['edit-articles', 'edit-news']);
$this->assertEquals(0, $this->testUserRole->permissions()->count());
}
/** @test */
#[Test]
public function it_can_give_and_revoke_permissions_models_array()
{
$models = [app(Permission::class)::where('name', 'edit-articles')->first(), app(Permission::class)::where('name', 'edit-news')->first()];
$this->testUserRole->givePermissionTo($models);
$this->assertEquals(2, $this->testUserRole->permissions()->count());
$this->testUserRole->revokePermissionTo($models);
$this->assertEquals(0, $this->testUserRole->permissions()->count());
}
/** @test */
#[Test]
public function it_can_give_and_revoke_permissions_models_collection()
{
$models = app(Permission::class)::whereIn('name', ['edit-articles', 'edit-news'])->get();
$this->testUserRole->givePermissionTo($models);
$this->assertEquals(2, $this->testUserRole->permissions()->count());
$this->testUserRole->revokePermissionTo($models);
$this->assertEquals(0, $this->testUserRole->permissions()->count());
}
/** @test */
#[Test]
public function it_can_determine_that_the_user_does_not_have_a_permission()
{
$this->assertFalse($this->testUser->hasPermissionTo('edit-articles'));
}
/** @test */
#[Test]
public function it_throws_an_exception_when_the_permission_does_not_exist()
{
$this->expectException(PermissionDoesNotExist::class);
$this->testUser->hasPermissionTo('does-not-exist');
}
/** @test */
#[Test]
public function it_throws_an_exception_when_the_permission_does_not_exist_for_this_guard()
{
$this->expectException(PermissionDoesNotExist::class);
$this->testUser->hasPermissionTo('does-not-exist', 'web');
}
/** @test */
#[Test]
public function it_can_reject_a_user_that_does_not_have_any_permissions_at_all()
{
$user = new User;
$this->assertFalse($user->hasPermissionTo('edit-articles'));
}
/** @test */
#[Test]
public function it_can_determine_that_the_user_has_any_of_the_permissions_directly()
{
$this->assertFalse($this->testUser->hasAnyPermission('edit-articles'));
$this->testUser->givePermissionTo('edit-articles');
$this->assertTrue($this->testUser->hasAnyPermission('edit-news', 'edit-articles'));
$this->testUser->givePermissionTo('edit-news');
$this->testUser->revokePermissionTo($this->testUserPermission);
$this->assertTrue($this->testUser->hasAnyPermission('edit-articles', 'edit-news'));
$this->assertFalse($this->testUser->hasAnyPermission('edit-blog', 'Edit News', ['Edit News']));
}
/** @test */
#[Test]
public function it_can_determine_that_the_user_has_any_of_the_permissions_directly_using_an_array()
{
$this->assertFalse($this->testUser->hasAnyPermission(['edit-articles']));
$this->testUser->givePermissionTo('edit-articles');
$this->assertTrue($this->testUser->hasAnyPermission(['edit-news', 'edit-articles']));
$this->testUser->givePermissionTo('edit-news');
$this->testUser->revokePermissionTo($this->testUserPermission);
$this->assertTrue($this->testUser->hasAnyPermission(['edit-articles', 'edit-news']));
}
/** @test */
#[Test]
public function it_can_determine_that_the_user_has_any_of_the_permissions_via_role()
{
$this->testUserRole->givePermissionTo('edit-articles');
$this->testUser->assignRole('testRole');
$this->assertTrue($this->testUser->hasAnyPermission('edit-news', 'edit-articles'));
$this->assertFalse($this->testUser->hasAnyPermission('edit-blog', 'Edit News', ['Edit News']));
}
/** @test */
#[Test]
public function it_can_determine_that_the_user_has_all_of_the_permissions_directly()
{
$this->testUser->givePermissionTo('edit-articles', 'edit-news');
$this->assertTrue($this->testUser->hasAllPermissions('edit-articles', 'edit-news'));
$this->testUser->revokePermissionTo('edit-articles');
$this->assertFalse($this->testUser->hasAllPermissions('edit-articles', 'edit-news'));
$this->assertFalse($this->testUser->hasAllPermissions(['edit-articles', 'edit-news'], 'edit-blog'));
}
/** @test */
#[Test]
public function it_can_determine_that_the_user_has_all_of_the_permissions_directly_using_an_array()
{
$this->assertFalse($this->testUser->hasAllPermissions(['edit-articles', 'edit-news']));
$this->testUser->revokePermissionTo('edit-articles');
$this->assertFalse($this->testUser->hasAllPermissions(['edit-news', 'edit-articles']));
$this->testUser->givePermissionTo('edit-news');
$this->testUser->revokePermissionTo($this->testUserPermission);
$this->assertFalse($this->testUser->hasAllPermissions(['edit-articles', 'edit-news']));
}
/** @test */
#[Test]
public function it_can_determine_that_the_user_has_all_of_the_permissions_via_role()
{
$this->testUserRole->givePermissionTo('edit-articles', 'edit-news');
$this->testUser->assignRole('testRole');
$this->assertTrue($this->testUser->hasAllPermissions('edit-articles', 'edit-news'));
}
/** @test */
#[Test]
public function it_can_determine_that_user_has_direct_permission()
{
$this->testUser->givePermissionTo('edit-articles');
$this->assertTrue($this->testUser->hasDirectPermission('edit-articles'));
$this->assertEquals(
collect(['edit-articles']),
$this->testUser->getDirectPermissions()->pluck('name')
);
$this->testUser->revokePermissionTo('edit-articles');
$this->assertFalse($this->testUser->hasDirectPermission('edit-articles'));
$this->testUser->assignRole('testRole');
$this->testUserRole->givePermissionTo('edit-articles');
$this->assertFalse($this->testUser->hasDirectPermission('edit-articles'));
}
/** @test */
#[Test]
public function it_can_list_all_the_permissions_via_roles_of_user()
{
$roleModel = app(Role::class);
$roleModel->findByName('testRole2')->givePermissionTo('edit-news');
$this->testUserRole->givePermissionTo('edit-articles');
$this->testUser->assignRole('testRole', 'testRole2');
$this->assertEquals(
collect(['edit-articles', 'edit-news']),
$this->testUser->getPermissionsViaRoles()->pluck('name')->sort()->values()
);
}
/** @test */
#[Test]
public function it_can_list_all_the_coupled_permissions_both_directly_and_via_roles()
{
$this->testUser->givePermissionTo('edit-news');
$this->testUserRole->givePermissionTo('edit-articles');
$this->testUser->assignRole('testRole');
$this->assertEquals(
collect(['edit-articles', 'edit-news']),
$this->testUser->getAllPermissions()->pluck('name')->sort()->values()
);
}
/** @test */
#[Test]
public function it_can_sync_multiple_permissions()
{
$this->testUser->givePermissionTo('edit-news');
$this->testUser->syncPermissions('edit-articles', 'edit-blog');
$this->assertTrue($this->testUser->hasDirectPermission('edit-articles'));
$this->assertTrue($this->testUser->hasDirectPermission('edit-blog'));
$this->assertFalse($this->testUser->hasDirectPermission('edit-news'));
}
/** @test */
#[Test]
public function it_can_avoid_sync_duplicated_permissions()
{
$this->testUser->syncPermissions('edit-articles', 'edit-blog', 'edit-blog');
$this->assertTrue($this->testUser->hasDirectPermission('edit-articles'));
$this->assertTrue($this->testUser->hasDirectPermission('edit-blog'));
}
/** @test */
#[Test]
public function it_can_avoid_detach_on_permission_that_does_not_exist_sync()
{
$this->testUser->syncPermissions('edit-articles');
try {
$this->testUser->syncPermissions('permission-does-not-exist');
$this->fail('Expected PermissionDoesNotExist exception was not thrown.');
} catch (PermissionDoesNotExist $e) {
//
}
$this->assertTrue($this->testUser->hasDirectPermission('edit-articles'));
$this->assertFalse($this->testUser->checkPermissionTo('permission-does-not-exist'));
}
/** @test */
#[Test]
public function it_can_sync_multiple_permissions_by_id()
{
$this->testUser->givePermissionTo('edit-news');
$ids = app(Permission::class)::whereIn('name', ['edit-articles', 'edit-blog'])->pluck($this->testUserPermission->getKeyName());
$this->testUser->syncPermissions($ids);
$this->assertTrue($this->testUser->hasDirectPermission('edit-articles'));
$this->assertTrue($this->testUser->hasDirectPermission('edit-blog'));
$this->assertFalse($this->testUser->hasDirectPermission('edit-news'));
}
/** @test */
#[Test]
public function sync_permission_ignores_null_inputs()
{
$this->testUser->givePermissionTo('edit-news');
$ids = app(Permission::class)::whereIn('name', ['edit-articles', 'edit-blog'])->pluck($this->testUserPermission->getKeyName());
$ids->push(null);
$this->testUser->syncPermissions($ids);
$this->assertTrue($this->testUser->hasDirectPermission('edit-articles'));
$this->assertTrue($this->testUser->hasDirectPermission('edit-blog'));
$this->assertFalse($this->testUser->hasDirectPermission('edit-news'));
}
/** @test */
#[Test]
public function sync_permission_error_does_not_detach_permissions()
{
$this->testUser->givePermissionTo('edit-news');
$this->expectException(PermissionDoesNotExist::class);
$this->testUser->syncPermissions('edit-articles', 'permission-that-does-not-exist');
$this->assertTrue($this->testUser->fresh()->hasDirectPermission('edit-news'));
}
/** @test */
#[Test]
public function it_does_not_remove_already_associated_permissions_when_assigning_new_permissions()
{
$this->testUser->givePermissionTo('edit-news');
$this->testUser->givePermissionTo('edit-articles');
$this->assertTrue($this->testUser->fresh()->hasDirectPermission('edit-news'));
}
/** @test */
#[Test]
public function it_does_not_throw_an_exception_when_assigning_a_permission_that_is_already_assigned()
{
$this->testUser->givePermissionTo('edit-news');
$this->testUser->givePermissionTo('edit-news');
$this->assertTrue($this->testUser->fresh()->hasDirectPermission('edit-news'));
}
/** @test */
#[Test]
public function it_can_sync_permissions_to_a_model_that_is_not_persisted()
{
$user = new User(['email' => 'test@user.com']);
$user->syncPermissions('edit-articles');
$user->save();
$user->save(); // test save same model twice
$this->assertTrue($user->hasPermissionTo('edit-articles'));
$user->syncPermissions('edit-articles');
$this->assertTrue($user->hasPermissionTo('edit-articles'));
$this->assertTrue($user->fresh()->hasPermissionTo('edit-articles'));
}
/** @test */
#[Test]
public function it_does_not_run_unnecessary_sqls_when_assigning_new_permissions()
{
$permission2 = app(Permission::class)->where('name', ['edit-news'])->first();
DB::enableQueryLog();
$this->testUser->syncPermissions($this->testUserPermission, $permission2);
DB::disableQueryLog();
$necessaryQueriesCount = 2;
$this->assertCount($necessaryQueriesCount, DB::getQueryLog());
}
/** @test */
#[Test]
public function calling_givePermissionTo_before_saving_object_doesnt_interfere_with_other_objects()
{
$user = new User(['email' => 'test@user.com']);
$user->givePermissionTo('edit-news');
$user->save();
$user2 = new User(['email' => 'test2@user.com']);
$user2->givePermissionTo('edit-articles');
DB::enableQueryLog();
$user2->save();
DB::disableQueryLog();
$this->assertTrue($user->fresh()->hasPermissionTo('edit-news'));
$this->assertFalse($user->fresh()->hasPermissionTo('edit-articles'));
$this->assertTrue($user2->fresh()->hasPermissionTo('edit-articles'));
$this->assertFalse($user2->fresh()->hasPermissionTo('edit-news'));
$this->assertSame(2, count(DB::getQueryLog())); // avoid unnecessary sync
}
/** @test */
#[Test]
public function calling_syncPermissions_before_saving_object_doesnt_interfere_with_other_objects()
{
$user = new User(['email' => 'test@user.com']);
$user->syncPermissions('edit-news');
$user->save();
$user2 = new User(['email' => 'test2@user.com']);
$user2->syncPermissions('edit-articles');
DB::enableQueryLog();
$user2->save();
DB::disableQueryLog();
$this->assertTrue($user->fresh()->hasPermissionTo('edit-news'));
$this->assertFalse($user->fresh()->hasPermissionTo('edit-articles'));
$this->assertTrue($user2->fresh()->hasPermissionTo('edit-articles'));
$this->assertFalse($user2->fresh()->hasPermissionTo('edit-news'));
$this->assertSame(2, count(DB::getQueryLog())); // avoid unnecessary sync
}
/** @test */
#[Test]
public function it_can_retrieve_permission_names()
{
$this->testUser->givePermissionTo('edit-news', 'edit-articles');
$this->assertEquals(
collect(['edit-articles', 'edit-news']),
$this->testUser->getPermissionNames()->sort()->values()
);
}
/** @test */
#[Test]
public function it_can_check_many_direct_permissions()
{
$this->testUser->givePermissionTo(['edit-articles', 'edit-news']);
$this->assertTrue($this->testUser->hasAllDirectPermissions(['edit-news', 'edit-articles']));
$this->assertTrue($this->testUser->hasAllDirectPermissions('edit-news', 'edit-articles'));
$this->assertFalse($this->testUser->hasAllDirectPermissions(['edit-articles', 'edit-news', 'edit-blog']));
$this->assertFalse($this->testUser->hasAllDirectPermissions(['edit-articles', 'edit-news'], 'edit-blog'));
}
/** @test */
#[Test]
public function it_can_check_if_there_is_any_of_the_direct_permissions_given()
{
$this->testUser->givePermissionTo(['edit-articles', 'edit-news']);
$this->assertTrue($this->testUser->hasAnyDirectPermission(['edit-news', 'edit-blog']));
$this->assertTrue($this->testUser->hasAnyDirectPermission('edit-news', 'edit-blog'));
$this->assertFalse($this->testUser->hasAnyDirectPermission('edit-blog', 'Edit News', ['Edit News']));
}
/** @test */
#[Test]
public function it_can_check_permission_based_on_logged_in_user_guard()
{
$this->testUser->givePermissionTo(app(Permission::class)::create([
'name' => 'do_that',
'guard_name' => 'api',
]));
$response = $this->actingAs($this->testUser, 'api')
->json('GET', '/check-api-guard-permission');
$response->assertJson([
'status' => true,
]);
}
/** @test */
#[Test]
public function it_can_reject_permission_based_on_logged_in_user_guard()
{
$unassignedPermission = app(Permission::class)::create([
'name' => 'do_that',
'guard_name' => 'api',
]);
$assignedPermission = app(Permission::class)::create([
'name' => 'do_that',
'guard_name' => 'web',
]);
$this->testUser->givePermissionTo($assignedPermission);
$response = $this->withExceptionHandling()
->actingAs($this->testUser, 'api')
->json('GET', '/check-api-guard-permission');
$response->assertJson([
'status' => false,
]);
}
/** @test */
#[Test]
public function it_fires_an_event_when_a_permission_is_added()
{
Event::fake();
app('config')->set('permission.events_enabled', true);
$this->testUser->givePermissionTo(['edit-articles', 'edit-news']);
$ids = app(Permission::class)::whereIn('name', ['edit-articles', 'edit-news'])
->pluck($this->testUserPermission->getKeyName())
->toArray();
Event::assertDispatched(PermissionAttached::class, function ($event) use ($ids) {
return $event->model instanceof User
&& $event->model->hasPermissionTo('edit-news')
&& $event->model->hasPermissionTo('edit-articles')
&& $ids === $event->permissionsOrIds;
});
}
/** @test */
#[Test]
public function it_does_not_fire_an_event_when_events_are_not_enabled()
{
Event::fake();
app('config')->set('permission.events_enabled', false);
$this->testUser->givePermissionTo(['edit-articles', 'edit-news']);
$ids = app(Permission::class)::whereIn('name', ['edit-articles', 'edit-news'])
->pluck($this->testUserPermission->getKeyName())
->toArray();
Event::assertNotDispatched(PermissionAttached::class);
}
/** @test */
#[Test]
public function it_fires_an_event_when_a_permission_is_removed()
{
Event::fake();
app('config')->set('permission.events_enabled', true);
$permissions = app(Permission::class)::whereIn('name', ['edit-articles', 'edit-news'])->get();
$this->testUser->givePermissionTo($permissions);
$this->testUser->revokePermissionTo($permissions);
Event::assertDispatched(PermissionDetached::class, function ($event) use ($permissions) {
return $event->model instanceof User
&& ! $event->model->hasPermissionTo('edit-news')
&& ! $event->model->hasPermissionTo('edit-articles')
&& $event->permissionsOrIds === $permissions;
});
}
/** @test */
#[Test]
public function it_can_be_given_a_permission_on_role_when_lazy_loading_is_restricted()
{
$this->assertTrue(Model::preventsLazyLoading());
try {
$testRole = app(Role::class)->with('permissions')->get()->first();
$testRole->givePermissionTo('edit-articles');
$this->assertTrue($testRole->hasPermissionTo('edit-articles'));
} catch (Exception $e) {
$this->fail('Lazy loading detected in the givePermissionTo method: '.$e->getMessage());
}
}
/** @test */
#[Test]
public function it_can_be_given_a_permission_on_user_when_lazy_loading_is_restricted()
{
$this->assertTrue(Model::preventsLazyLoading());
try {
User::create(['email' => 'other@user.com']);
$testUser = User::with('permissions')->get()->first();
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | true |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/PermissionRegistrarTest.php | tests/PermissionRegistrarTest.php | <?php
namespace Spatie\Permission\Tests;
use PHPUnit\Framework\Attributes\Test;
use Spatie\Permission\Contracts\Permission as PermissionContract;
use Spatie\Permission\Contracts\Role as RoleContract;
use Spatie\Permission\Models\Permission as SpatiePermission;
use Spatie\Permission\Models\Role as SpatieRole;
use Spatie\Permission\PermissionRegistrar;
use Spatie\Permission\Tests\TestModels\Permission as TestPermission;
use Spatie\Permission\Tests\TestModels\Role as TestRole;
class PermissionRegistrarTest extends TestCase
{
/** @test */
#[Test]
public function it_can_clear_loaded_permissions_collection()
{
$reflectedClass = new \ReflectionClass(app(PermissionRegistrar::class));
$reflectedProperty = $reflectedClass->getProperty('permissions');
$reflectedProperty->setAccessible(true);
app(PermissionRegistrar::class)->getPermissions();
$this->assertNotNull($reflectedProperty->getValue(app(PermissionRegistrar::class)));
app(PermissionRegistrar::class)->clearPermissionsCollection();
$this->assertNull($reflectedProperty->getValue(app(PermissionRegistrar::class)));
}
/** @test */
#[Test]
public function it_can_check_uids()
{
$uids = [
// UUIDs
'00000000-0000-0000-0000-000000000000',
'9be37b52-e1fa-4e86-b65f-cbfcbedde838',
'fc458041-fb21-4eea-a04b-b55c87a7224a',
'78144b52-a889-11ed-afa1-0242ac120002',
'78144f4e-a889-11ed-afa1-0242ac120002',
// GUIDs
'4b8590bb-90a2-4f38-8dc9-70e663a5b0e5',
'A98C5A1E-A742-4808-96FA-6F409E799937',
'1f01164a-98e9-4246-93ec-7941aefb1da6',
'91b73d20-89e6-46b0-b39b-632706cc3ed7',
'0df4a5b8-7c2e-484f-ad1d-787d1b83aacc',
// ULIDs
'01GRVB3DREB63KNN4G2QVV99DF',
'01GRVB3DRECY317SJCJ6DMTFCA',
'01GRVB3DREGGPBXNH1M24GX1DS',
'01GRVB3DRESRM2K9AVQSW1JCKA',
'01GRVB3DRES5CQ31PB24MP4CSV',
];
$not_uids = [
'9be37b52-e1fa',
'9be37b52-e1fa-4e86',
'9be37b52-e1fa-4e86-b65f',
'01GRVB3DREB63KNN4G2',
'TEST STRING',
'00-00-00-00-00-00',
'91GRVB3DRES5CQ31PB24MP4CSV',
];
foreach ($uids as $uid) {
$this->assertTrue(PermissionRegistrar::isUid($uid));
}
foreach ($not_uids as $not_uid) {
$this->assertFalse(PermissionRegistrar::isUid($not_uid));
}
}
/** @test */
#[Test]
public function it_can_get_permission_class()
{
$this->assertSame(SpatiePermission::class, app(PermissionRegistrar::class)->getPermissionClass());
$this->assertSame(SpatiePermission::class, get_class(app(PermissionContract::class)));
}
/** @test */
#[Test]
public function it_can_change_permission_class()
{
$this->assertSame(SpatiePermission::class, config('permission.models.permission'));
$this->assertSame(SpatiePermission::class, app(PermissionRegistrar::class)->getPermissionClass());
$this->assertSame(SpatiePermission::class, get_class(app(PermissionContract::class)));
app(PermissionRegistrar::class)->setPermissionClass(TestPermission::class);
$this->assertSame(TestPermission::class, config('permission.models.permission'));
$this->assertSame(TestPermission::class, app(PermissionRegistrar::class)->getPermissionClass());
$this->assertSame(TestPermission::class, get_class(app(PermissionContract::class)));
}
/** @test */
#[Test]
public function it_can_get_role_class()
{
$this->assertSame(SpatieRole::class, app(PermissionRegistrar::class)->getRoleClass());
$this->assertSame(SpatieRole::class, get_class(app(RoleContract::class)));
}
/** @test */
#[Test]
public function it_can_change_role_class()
{
$this->assertSame(SpatieRole::class, config('permission.models.role'));
$this->assertSame(SpatieRole::class, app(PermissionRegistrar::class)->getRoleClass());
$this->assertSame(SpatieRole::class, get_class(app(RoleContract::class)));
app(PermissionRegistrar::class)->setRoleClass(TestRole::class);
$this->assertSame(TestRole::class, config('permission.models.role'));
$this->assertSame(TestRole::class, app(PermissionRegistrar::class)->getRoleClass());
$this->assertSame(TestRole::class, get_class(app(RoleContract::class)));
}
/** @test */
#[Test]
public function it_can_change_team_id()
{
$team_id = '00000000-0000-0000-0000-000000000000';
app(PermissionRegistrar::class)->setPermissionsTeamId($team_id);
$this->assertSame($team_id, app(PermissionRegistrar::class)->getPermissionsTeamId());
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/CustomGateTest.php | tests/CustomGateTest.php | <?php
namespace Spatie\Permission\Tests;
use Illuminate\Contracts\Auth\Access\Gate;
use PHPUnit\Framework\Attributes\Test;
class CustomGateTest extends TestCase
{
protected function getEnvironmentSetUp($app)
{
parent::getEnvironmentSetUp($app);
$app['config']->set('permission.register_permission_check_method', false);
}
/** @test */
#[Test]
public function it_doesnt_register_the_method_for_checking_permissions_on_the_gate()
{
$this->testUser->givePermissionTo('edit-articles');
$this->assertEmpty(app(Gate::class)->abilities());
$this->assertFalse($this->testUser->can('edit-articles'));
}
/** @test */
#[Test]
public function it_can_authorize_using_custom_method_for_checking_permissions()
{
app(Gate::class)->define('edit-articles', function () {
return true;
});
$this->assertArrayHasKey('edit-articles', app(Gate::class)->abilities());
$this->assertTrue($this->testUser->can('edit-articles'));
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/CacheTest.php | tests/CacheTest.php | <?php
namespace Spatie\Permission\Tests;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use PHPUnit\Framework\Attributes\Test;
use Spatie\Permission\Contracts\Permission;
use Spatie\Permission\Contracts\Role;
use Spatie\Permission\Exceptions\PermissionDoesNotExist;
use Spatie\Permission\PermissionRegistrar;
use Spatie\Permission\Tests\TestModels\User;
class CacheTest extends TestCase
{
protected $cache_init_count = 0;
protected $cache_load_count = 0;
protected $cache_run_count = 2; // roles lookup, permissions lookup
protected $registrar;
protected function setUp(): void
{
parent::setUp();
$this->registrar = app(PermissionRegistrar::class);
$this->registrar->forgetCachedPermissions();
DB::connection()->enableQueryLog();
$cacheStore = $this->registrar->getCacheStore();
switch (true) {
case $cacheStore instanceof \Illuminate\Cache\DatabaseStore:
$this->cache_init_count = 1;
$this->cache_load_count = 1;
// no break
default:
}
}
/** @test */
#[Test]
public function it_can_cache_the_permissions()
{
$this->resetQueryCount();
$this->registrar->getPermissions();
$this->assertQueryCount($this->cache_init_count + $this->cache_load_count + $this->cache_run_count);
}
/** @test */
#[Test]
public function it_flushes_the_cache_when_creating_a_permission()
{
app(Permission::class)->create(['name' => 'new']);
$this->resetQueryCount();
$this->registrar->getPermissions();
$this->assertQueryCount($this->cache_init_count + $this->cache_load_count + $this->cache_run_count);
}
/** @test */
#[Test]
public function it_flushes_the_cache_when_updating_a_permission()
{
$permission = app(Permission::class)->create(['name' => 'new']);
$permission->name = 'other name';
$permission->save();
$this->resetQueryCount();
$this->registrar->getPermissions();
$this->assertQueryCount($this->cache_init_count + $this->cache_load_count + $this->cache_run_count);
}
/** @test */
#[Test]
public function it_flushes_the_cache_when_creating_a_role()
{
app(Role::class)->create(['name' => 'new']);
$this->resetQueryCount();
$this->registrar->getPermissions();
$this->assertQueryCount($this->cache_init_count + $this->cache_load_count + $this->cache_run_count);
}
/** @test */
#[Test]
public function it_flushes_the_cache_when_updating_a_role()
{
$role = app(Role::class)->create(['name' => 'new']);
$role->name = 'other name';
$role->save();
$this->resetQueryCount();
$this->registrar->getPermissions();
$this->assertQueryCount($this->cache_init_count + $this->cache_load_count + $this->cache_run_count);
}
/** @test */
#[Test]
public function removing_a_permission_from_a_user_should_not_flush_the_cache()
{
$this->testUser->givePermissionTo('edit-articles');
$this->registrar->getPermissions();
$this->testUser->revokePermissionTo('edit-articles');
$this->resetQueryCount();
$this->registrar->getPermissions();
$this->assertQueryCount(0);
}
/** @test */
#[Test]
public function removing_a_role_from_a_user_should_not_flush_the_cache()
{
$this->testUser->assignRole('testRole');
$this->registrar->getPermissions();
$this->testUser->removeRole('testRole');
$this->resetQueryCount();
$this->registrar->getPermissions();
$this->assertQueryCount(0);
}
/** @test */
#[Test]
public function it_flushes_the_cache_when_removing_a_role_from_a_permission()
{
$this->testUserPermission->assignRole('testRole');
$this->registrar->getPermissions();
$this->testUserPermission->removeRole('testRole');
$this->resetQueryCount();
$this->registrar->getPermissions();
$this->assertQueryCount($this->cache_init_count + $this->cache_load_count + $this->cache_run_count);
}
/** @test */
#[Test]
public function it_flushes_the_cache_when_assign_a_permission_to_a_role()
{
$this->testUserRole->givePermissionTo('edit-articles');
$this->resetQueryCount();
$this->registrar->getPermissions();
$this->assertQueryCount($this->cache_init_count + $this->cache_load_count + $this->cache_run_count);
}
/** @test */
#[Test]
public function user_creation_should_not_flush_the_cache()
{
$this->registrar->getPermissions();
User::create(['email' => 'new']);
$this->resetQueryCount();
$this->registrar->getPermissions();
// should all be in memory, so no init/load required
$this->assertQueryCount(0);
}
/** @test */
#[Test]
public function it_flushes_the_cache_when_giving_a_permission_to_a_role()
{
$this->testUserRole->givePermissionTo($this->testUserPermission);
$this->resetQueryCount();
$this->registrar->getPermissions();
$this->assertQueryCount($this->cache_init_count + $this->cache_load_count + $this->cache_run_count);
}
/** @test */
#[Test]
public function has_permission_to_should_use_the_cache()
{
$this->testUserRole->givePermissionTo(['edit-articles', 'edit-news', 'Edit News']);
$this->testUser->assignRole('testRole');
$this->testUser->loadMissing('roles', 'permissions'); // load relations
$this->resetQueryCount();
$this->assertTrue($this->testUser->hasPermissionTo('edit-articles'));
$this->assertQueryCount($this->cache_init_count + $this->cache_load_count + $this->cache_run_count);
$this->resetQueryCount();
$this->assertTrue($this->testUser->hasPermissionTo('edit-news'));
$this->assertQueryCount(0);
$this->resetQueryCount();
$this->assertTrue($this->testUser->hasPermissionTo('edit-articles'));
$this->assertQueryCount(0);
$this->resetQueryCount();
$this->assertTrue($this->testUser->hasPermissionTo('Edit News'));
$this->assertQueryCount(0);
}
/** @test */
#[Test]
public function the_cache_should_differentiate_by_guard_name()
{
$this->expectException(PermissionDoesNotExist::class);
$this->testUserRole->givePermissionTo(['edit-articles', 'web']);
$this->testUser->assignRole('testRole');
$this->testUser->loadMissing('roles', 'permissions'); // load relations
$this->resetQueryCount();
$this->assertTrue($this->testUser->hasPermissionTo('edit-articles', 'web'));
$this->assertQueryCount($this->cache_init_count + $this->cache_load_count + $this->cache_run_count);
$this->resetQueryCount();
$this->assertFalse($this->testUser->hasPermissionTo('edit-articles', 'admin'));
$this->assertQueryCount(1); // 1 for first lookup of this permission with this guard
}
/** @test */
#[Test]
public function get_all_permissions_should_use_the_cache()
{
$this->testUserRole->givePermissionTo($expected = ['edit-articles', 'edit-news']);
$this->testUser->assignRole('testRole');
$this->testUser->loadMissing('roles.permissions', 'permissions'); // load relations
$this->resetQueryCount();
$this->registrar->getPermissions();
$this->assertQueryCount($this->cache_init_count + $this->cache_load_count + $this->cache_run_count);
$this->resetQueryCount();
$actual = $this->testUser->getAllPermissions()->pluck('name')->sort()->values();
$this->assertEquals($actual, collect($expected));
$this->assertQueryCount(0);
}
/** @test */
#[Test]
public function get_all_permissions_should_not_over_hydrate_roles()
{
$this->testUserRole->givePermissionTo(['edit-articles', 'edit-news']);
$permissions = $this->registrar->getPermissions();
$roles = $permissions->flatMap->roles;
// Should have same object reference
$this->assertSame($roles[0], $roles[1]);
}
/** @test */
#[Test]
public function it_can_reset_the_cache_with_artisan_command()
{
Artisan::call('permission:create-permission', ['name' => 'new-permission']);
$this->assertCount(1, \Spatie\Permission\Models\Permission::where('name', 'new-permission')->get());
$this->resetQueryCount();
// retrieve permissions, and assert that the cache had to be loaded
$this->registrar->getPermissions();
$this->assertQueryCount($this->cache_init_count + $this->cache_load_count + $this->cache_run_count);
// reset the cache
Artisan::call('permission:cache-reset');
$this->resetQueryCount();
$this->registrar->getPermissions();
// assert that the cache had to be reloaded
$this->assertQueryCount($this->cache_init_count + $this->cache_load_count + $this->cache_run_count);
}
protected function assertQueryCount(int $expected)
{
$this->assertCount($expected, DB::getQueryLog());
}
protected function resetQueryCount()
{
DB::flushQueryLog();
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/MultipleGuardsTest.php | tests/MultipleGuardsTest.php | <?php
namespace Spatie\Permission\Tests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use PHPUnit\Framework\Attributes\Test;
use Spatie\Permission\Contracts\Permission;
use Spatie\Permission\Tests\TestModels\Manager;
class MultipleGuardsTest extends TestCase
{
protected function getEnvironmentSetUp($app)
{
parent::getEnvironmentSetUp($app);
$app['config']->set('auth.guards', [
'web' => ['driver' => 'session', 'provider' => 'users'],
'api' => ['driver' => 'token', 'provider' => 'users'],
'jwt' => ['driver' => 'token', 'provider' => 'users'],
'abc' => ['driver' => 'abc'],
'admin' => ['driver' => 'session', 'provider' => 'admins'],
]);
$this->setUpRoutes();
}
/**
* Create routes to test authentication with guards.
*/
public function setUpRoutes(): void
{
Route::middleware('auth:api')->get('/check-api-guard-permission', function (Request $request) {
return [
'status' => $request->user()->checkPermissionTo('use_api_guard'),
];
});
}
/** @test */
#[Test]
public function it_can_give_a_permission_to_a_model_that_is_used_by_multiple_guards()
{
$this->testUser->givePermissionTo(app(Permission::class)::create([
'name' => 'do_this',
'guard_name' => 'web',
]));
$this->testUser->givePermissionTo(app(Permission::class)::create([
'name' => 'do_that',
'guard_name' => 'api',
]));
$this->assertTrue($this->testUser->checkPermissionTo('do_this', 'web'));
$this->assertTrue($this->testUser->checkPermissionTo('do_that', 'api'));
$this->assertFalse($this->testUser->checkPermissionTo('do_that', 'web'));
}
/** @test */
#[Test]
public function the_gate_can_grant_permission_to_a_user_by_passing_a_guard_name()
{
$this->testUser->givePermissionTo(app(Permission::class)::create([
'name' => 'do_this',
'guard_name' => 'web',
]));
$this->testUser->givePermissionTo(app(Permission::class)::create([
'name' => 'do_that',
'guard_name' => 'api',
]));
$this->assertTrue($this->testUser->can('do_this', 'web'));
$this->assertTrue($this->testUser->can('do_that', 'api'));
$this->assertFalse($this->testUser->can('do_that', 'web'));
$this->assertTrue($this->testUser->cannot('do_that', 'web'));
$this->assertTrue($this->testUser->canAny(['do_this', 'do_that'], 'web'));
$this->testAdminRole->givePermissionTo($this->testAdminPermission);
$this->testAdmin->assignRole($this->testAdminRole);
$this->assertTrue($this->testAdmin->hasPermissionTo($this->testAdminPermission));
$this->assertTrue($this->testAdmin->can('admin-permission'));
$this->assertTrue($this->testAdmin->can('admin-permission', 'admin'));
$this->assertTrue($this->testAdmin->cannot('admin-permission', 'web'));
$this->assertTrue($this->testAdmin->cannot('non-existing-permission'));
$this->assertTrue($this->testAdmin->cannot('non-existing-permission', 'web'));
$this->assertTrue($this->testAdmin->cannot('non-existing-permission', 'admin'));
$this->assertTrue($this->testAdmin->cannot(['admin-permission', 'non-existing-permission'], 'web'));
$this->assertFalse($this->testAdmin->can('edit-articles', 'web'));
$this->assertFalse($this->testAdmin->can('edit-articles', 'admin'));
$this->assertTrue($this->testUser->cannot('edit-articles', 'admin'));
$this->assertTrue($this->testUser->cannot('admin-permission', 'admin'));
$this->assertTrue($this->testUser->cannot('admin-permission', 'web'));
}
/** @test */
#[Test]
public function it_can_honour_guardName_function_on_model_for_overriding_guard_name_property()
{
$user = Manager::create(['email' => 'manager@test.com']);
$user->givePermissionTo(app(Permission::class)::create([
'name' => 'do_jwt',
'guard_name' => 'jwt',
]));
// Manager test user has the guardName override method, which returns 'jwt'
$this->assertTrue($user->checkPermissionTo('do_jwt', 'jwt'));
$this->assertTrue($user->hasPermissionTo('do_jwt', 'jwt'));
// Manager test user has the $guard_name property set to 'web'
$this->assertFalse($user->checkPermissionTo('do_jwt', 'web'));
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/WildcardMiddlewareTest.php | tests/WildcardMiddlewareTest.php | <?php
namespace Spatie\Permission\Tests;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use PHPUnit\Framework\Attributes\Test;
use Spatie\Permission\Exceptions\UnauthorizedException;
use Spatie\Permission\Middleware\PermissionMiddleware;
use Spatie\Permission\Middleware\RoleMiddleware;
use Spatie\Permission\Middleware\RoleOrPermissionMiddleware;
use Spatie\Permission\Models\Permission;
class WildcardMiddlewareTest extends TestCase
{
protected $roleMiddleware;
protected $permissionMiddleware;
protected $roleOrPermissionMiddleware;
protected function setUp(): void
{
parent::setUp();
$this->roleMiddleware = new RoleMiddleware;
$this->permissionMiddleware = new PermissionMiddleware;
$this->roleOrPermissionMiddleware = new RoleOrPermissionMiddleware;
app('config')->set('permission.enable_wildcard_permission', true);
}
/** @test */
#[Test]
public function a_guest_cannot_access_a_route_protected_by_the_permission_middleware()
{
$this->assertEquals(
403,
$this->runMiddleware($this->permissionMiddleware, 'articles.edit')
);
}
/** @test */
#[Test]
public function a_user_can_access_a_route_protected_by_permission_middleware_if_have_this_permission()
{
Auth::login($this->testUser);
Permission::create(['name' => 'articles']);
$this->testUser->givePermissionTo('articles');
$this->assertEquals(
200,
$this->runMiddleware($this->permissionMiddleware, 'articles.edit')
);
}
/** @test */
#[Test]
public function a_user_can_access_a_route_protected_by_this_permission_middleware_if_have_one_of_the_permissions()
{
Auth::login($this->testUser);
Permission::create(['name' => 'articles.*.test']);
$this->testUser->givePermissionTo('articles.*.test');
$this->assertEquals(
200,
$this->runMiddleware($this->permissionMiddleware, 'news.edit|articles.create.test')
);
$this->assertEquals(
200,
$this->runMiddleware($this->permissionMiddleware, ['news.edit', 'articles.create.test'])
);
}
/** @test */
#[Test]
public function a_user_cannot_access_a_route_protected_by_the_permission_middleware_if_have_a_different_permission()
{
Auth::login($this->testUser);
Permission::create(['name' => 'articles.*']);
$this->testUser->givePermissionTo('articles.*');
$this->assertEquals(
403,
$this->runMiddleware($this->permissionMiddleware, 'news.edit')
);
}
/** @test */
#[Test]
public function a_user_cannot_access_a_route_protected_by_permission_middleware_if_have_not_permissions()
{
Auth::login($this->testUser);
$this->assertEquals(
403,
$this->runMiddleware($this->permissionMiddleware, 'articles.edit|news.edit')
);
}
/** @test */
#[Test]
public function a_user_can_access_a_route_protected_by_permission_or_role_middleware_if_has_this_permission_or_role()
{
Auth::login($this->testUser);
Permission::create(['name' => 'articles.*']);
$this->testUser->assignRole('testRole');
$this->testUser->givePermissionTo('articles.*');
$this->assertEquals(
200,
$this->runMiddleware($this->roleOrPermissionMiddleware, 'testRole|news.edit|articles.create')
);
$this->testUser->removeRole('testRole');
$this->assertEquals(
200,
$this->runMiddleware($this->roleOrPermissionMiddleware, 'testRole|articles.edit')
);
$this->testUser->revokePermissionTo('articles.*');
$this->testUser->assignRole('testRole');
$this->assertEquals(
200,
$this->runMiddleware($this->roleOrPermissionMiddleware, 'testRole|articles.edit')
);
$this->assertEquals(
200,
$this->runMiddleware($this->roleOrPermissionMiddleware, ['testRole', 'articles.edit'])
);
}
/** @test */
#[Test]
public function the_required_permissions_can_be_fetched_from_the_exception()
{
Auth::login($this->testUser);
$requiredPermissions = [];
try {
$this->permissionMiddleware->handle(new Request, function () {
return (new Response)->setContent('<html></html>');
}, 'permission.some');
} catch (UnauthorizedException $e) {
$requiredPermissions = $e->getRequiredPermissions();
}
$this->assertEquals(['permission.some'], $requiredPermissions);
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/HasPermissionsWithCustomModelsTest.php | tests/HasPermissionsWithCustomModelsTest.php | <?php
namespace Spatie\Permission\Tests;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use PHPUnit\Framework\Attributes\Test;
use Spatie\Permission\PermissionRegistrar;
use Spatie\Permission\Tests\TestModels\Admin;
use Spatie\Permission\Tests\TestModels\Permission;
use Spatie\Permission\Tests\TestModels\User;
class HasPermissionsWithCustomModelsTest extends HasPermissionsTest
{
/** @var bool */
protected $useCustomModels = true;
/** @var int */
protected $resetDatabaseQuery = 0;
protected function getEnvironmentSetUp($app)
{
parent::getEnvironmentSetUp($app);
if ($app['config']->get('cache.default') == 'database') {
$this->resetDatabaseQuery = 1;
}
}
/** @test */
#[Test]
public function it_can_use_custom_model_permission()
{
$this->assertSame(get_class($this->testUserPermission), Permission::class);
}
/** @test */
#[Test]
public function it_can_use_custom_fields_from_cache()
{
DB::connection()->getSchemaBuilder()->table(config('permission.table_names.roles'), function ($table) {
$table->string('type')->default('R');
});
DB::connection()->getSchemaBuilder()->table(config('permission.table_names.permissions'), function ($table) {
$table->string('type')->default('P');
});
$this->testUserRole->givePermissionTo($this->testUserPermission);
app(PermissionRegistrar::class)->getPermissions();
DB::enableQueryLog();
$this->assertSame('P', Permission::findByName('edit-articles')->type);
$this->assertSame('R', Permission::findByName('edit-articles')->roles[0]->type);
DB::disableQueryLog();
$this->assertSame(0, count(DB::getQueryLog()));
}
/** @test */
#[Test]
public function it_can_scope_users_using_a_int()
{
// Skipped because custom model uses uuid,
// replacement "it_can_scope_users_using_a_uuid"
$this->assertTrue(true);
}
/** @test */
#[Test]
public function it_can_scope_users_using_a_uuid()
{
$uuid1 = $this->testUserPermission->getKey();
$uuid2 = app(Permission::class)::where('name', 'edit-news')->first()->getKey();
$user1 = User::create(['email' => 'user1@test.com']);
$user2 = User::create(['email' => 'user2@test.com']);
$user1->givePermissionTo([$uuid1, $uuid2]);
$this->testUserRole->givePermissionTo($uuid1);
$user2->assignRole('testRole');
$scopedUsers1 = User::permission($uuid1)->get();
$scopedUsers2 = User::permission([$uuid2])->get();
$this->assertEquals(2, $scopedUsers1->count());
$this->assertEquals(1, $scopedUsers2->count());
}
/** @test */
#[Test]
public function it_doesnt_detach_roles_when_soft_deleting()
{
$this->testUserRole->givePermissionTo($this->testUserPermission);
DB::enableQueryLog();
$this->testUserPermission->delete();
DB::disableQueryLog();
$this->assertSame(1 + $this->resetDatabaseQuery, count(DB::getQueryLog()));
$permission = Permission::onlyTrashed()->find($this->testUserPermission->getKey());
$this->assertEquals(1, DB::table(config('permission.table_names.role_has_permissions'))->where('permission_test_id', $permission->getKey())->count());
}
/** @test */
#[Test]
public function it_doesnt_detach_users_when_soft_deleting()
{
$this->testUser->givePermissionTo($this->testUserPermission);
DB::enableQueryLog();
$this->testUserPermission->delete();
DB::disableQueryLog();
$this->assertSame(1 + $this->resetDatabaseQuery, count(DB::getQueryLog()));
$permission = Permission::onlyTrashed()->find($this->testUserPermission->getKey());
$this->assertEquals(1, DB::table(config('permission.table_names.model_has_permissions'))->where('permission_test_id', $permission->getKey())->count());
}
/** @test */
#[Test]
public function it_does_detach_roles_and_users_when_force_deleting()
{
$permission_id = $this->testUserPermission->getKey();
$this->testUserRole->givePermissionTo($permission_id);
$this->testUser->givePermissionTo($permission_id);
DB::enableQueryLog();
$this->testUserPermission->forceDelete();
DB::disableQueryLog();
$this->assertSame(3 + $this->resetDatabaseQuery, count(DB::getQueryLog())); // avoid detach permissions on permissions
$permission = Permission::withTrashed()->find($permission_id);
$this->assertNull($permission);
$this->assertEquals(0, DB::table(config('permission.table_names.role_has_permissions'))->where('permission_test_id', $permission_id)->count());
$this->assertEquals(0, DB::table(config('permission.table_names.model_has_permissions'))->where('permission_test_id', $permission_id)->count());
}
/** @test */
#[Test]
public function it_should_touch_when_assigning_new_permissions()
{
Carbon::setTestNow('2021-07-19 10:13:14');
$user = Admin::create(['email' => 'user1@test.com']);
$permission1 = Permission::create(['name' => 'edit-news', 'guard_name' => 'admin']);
$permission2 = Permission::create(['name' => 'edit-blog', 'guard_name' => 'admin']);
$this->assertSame('2021-07-19 10:13:14', $permission1->updated_at->format('Y-m-d H:i:s'));
Carbon::setTestNow('2021-07-20 19:13:14');
$user->syncPermissions([$permission1->getKey(), $permission2->getKey()]);
$this->assertSame('2021-07-20 19:13:14', $permission1->refresh()->updated_at->format('Y-m-d H:i:s'));
$this->assertSame('2021-07-20 19:13:14', $permission2->refresh()->updated_at->format('Y-m-d H:i:s'));
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/RoleOrPermissionMiddlewareTest.php | tests/RoleOrPermissionMiddlewareTest.php | <?php
namespace Spatie\Permission\Tests;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Gate;
use InvalidArgumentException;
use Laravel\Passport\Passport;
use PHPUnit\Framework\Attributes\Test;
use Spatie\Permission\Exceptions\UnauthorizedException;
use Spatie\Permission\Middleware\RoleOrPermissionMiddleware;
use Spatie\Permission\Tests\TestModels\UserWithoutHasRoles;
class RoleOrPermissionMiddlewareTest extends TestCase
{
protected $roleOrPermissionMiddleware;
protected $usePassport = true;
protected function setUp(): void
{
parent::setUp();
$this->roleOrPermissionMiddleware = new RoleOrPermissionMiddleware;
}
/** @test */
#[Test]
public function a_guest_cannot_access_a_route_protected_by_the_role_or_permission_middleware()
{
$this->assertEquals(
403,
$this->runMiddleware($this->roleOrPermissionMiddleware, 'testRole')
);
}
/** @test */
#[Test]
public function a_user_can_access_a_route_protected_by_permission_or_role_middleware_if_has_this_permission_or_role()
{
Auth::login($this->testUser);
$this->testUser->assignRole('testRole');
$this->testUser->givePermissionTo('edit-articles');
$this->assertEquals(
200,
$this->runMiddleware($this->roleOrPermissionMiddleware, 'testRole|edit-news|edit-articles')
);
$this->testUser->removeRole('testRole');
$this->assertEquals(
200,
$this->runMiddleware($this->roleOrPermissionMiddleware, 'testRole|edit-articles')
);
$this->testUser->revokePermissionTo('edit-articles');
$this->testUser->assignRole('testRole');
$this->assertEquals(
200,
$this->runMiddleware($this->roleOrPermissionMiddleware, 'testRole|edit-articles')
);
$this->assertEquals(
200,
$this->runMiddleware($this->roleOrPermissionMiddleware, ['testRole', 'edit-articles'])
);
}
/** @test */
#[Test]
public function a_client_can_access_a_route_protected_by_permission_or_role_middleware_if_has_this_permission_or_role(): void
{
if ($this->getLaravelVersion() < 9) {
$this->markTestSkipped('requires laravel >= 9');
}
Passport::actingAsClient($this->testClient, ['*']);
$this->testClient->assignRole('clientRole');
$this->testClient->givePermissionTo('edit-posts');
$this->assertEquals(
200,
$this->runMiddleware($this->roleOrPermissionMiddleware, 'clientRole|edit-news|edit-posts', null, true)
);
$this->testClient->removeRole('clientRole');
$this->assertEquals(
200,
$this->runMiddleware($this->roleOrPermissionMiddleware, 'clientRole|edit-posts', null, true)
);
$this->testClient->revokePermissionTo('edit-posts');
$this->testClient->assignRole('clientRole');
$this->assertEquals(
200,
$this->runMiddleware($this->roleOrPermissionMiddleware, 'clientRole|edit-posts', null, true)
);
$this->assertEquals(
200,
$this->runMiddleware($this->roleOrPermissionMiddleware, ['clientRole', 'edit-posts'], null, true)
);
}
/** @test */
#[Test]
public function a_super_admin_user_can_access_a_route_protected_by_permission_or_role_middleware()
{
Auth::login($this->testUser);
Gate::before(function ($user, $ability) {
return $user->getKey() === $this->testUser->getKey() ? true : null;
});
$this->assertEquals(
200,
$this->runMiddleware($this->roleOrPermissionMiddleware, 'testRole|edit-articles')
);
}
/** @test */
#[Test]
public function a_user_can_not_access_a_route_protected_by_permission_or_role_middleware_if_have_not_has_roles_trait()
{
$userWithoutHasRoles = UserWithoutHasRoles::create(['email' => 'test_not_has_roles@user.com']);
Auth::login($userWithoutHasRoles);
$this->assertEquals(
403,
$this->runMiddleware($this->roleOrPermissionMiddleware, 'testRole|edit-articles')
);
}
/** @test */
#[Test]
public function a_user_can_not_access_a_route_protected_by_permission_or_role_middleware_if_have_not_this_permission_and_role()
{
Auth::login($this->testUser);
$this->assertEquals(
403,
$this->runMiddleware($this->roleOrPermissionMiddleware, 'testRole|edit-articles')
);
$this->assertEquals(
403,
$this->runMiddleware($this->roleOrPermissionMiddleware, 'missingRole|missingPermission')
);
}
/** @test */
#[Test]
public function a_client_can_not_access_a_route_protected_by_permission_or_role_middleware_if_have_not_this_permission_and_role(): void
{
if ($this->getLaravelVersion() < 9) {
$this->markTestSkipped('requires laravel >= 9');
}
Passport::actingAsClient($this->testClient, ['*']);
$this->assertEquals(
403,
$this->runMiddleware($this->roleOrPermissionMiddleware, 'clientRole|edit-posts', null, true)
);
$this->assertEquals(
403,
$this->runMiddleware($this->roleOrPermissionMiddleware, 'missingRole|missingPermission', null, true)
);
}
/** @test */
#[Test]
public function use_not_existing_custom_guard_in_role_or_permission()
{
$class = null;
try {
$this->roleOrPermissionMiddleware->handle(new Request, function () {
return (new Response)->setContent('<html></html>');
}, 'testRole', 'xxx');
} catch (InvalidArgumentException $e) {
$class = get_class($e);
}
$this->assertEquals(InvalidArgumentException::class, $class);
}
/** @test */
#[Test]
public function user_can_not_access_permission_or_role_with_guard_admin_while_login_using_default_guard()
{
Auth::login($this->testUser);
$this->testUser->assignRole('testRole');
$this->testUser->givePermissionTo('edit-articles');
$this->assertEquals(
403,
$this->runMiddleware($this->roleOrPermissionMiddleware, 'edit-articles|testRole', 'admin')
);
}
/** @test */
#[Test]
public function client_can_not_access_permission_or_role_with_guard_admin_while_login_using_default_guard(): void
{
if ($this->getLaravelVersion() < 9) {
$this->markTestSkipped('requires laravel >= 9');
}
Passport::actingAsClient($this->testClient, ['*']);
$this->testClient->assignRole('clientRole');
$this->testClient->givePermissionTo('edit-posts');
$this->assertEquals(
403,
$this->runMiddleware($this->roleOrPermissionMiddleware, 'edit-posts|clientRole', 'admin', true)
);
}
/** @test */
#[Test]
public function user_can_access_permission_or_role_with_guard_admin_while_login_using_admin_guard()
{
Auth::guard('admin')->login($this->testAdmin);
$this->testAdmin->assignRole('testAdminRole');
$this->testAdmin->givePermissionTo('admin-permission');
$this->assertEquals(
200,
$this->runMiddleware($this->roleOrPermissionMiddleware, 'admin-permission|testAdminRole', 'admin')
);
}
/** @test */
#[Test]
public function the_required_permissions_or_roles_can_be_fetched_from_the_exception()
{
Auth::login($this->testUser);
$message = null;
$requiredRolesOrPermissions = [];
try {
$this->roleOrPermissionMiddleware->handle(new Request, function () {
return (new Response)->setContent('<html></html>');
}, 'some-permission|some-role');
} catch (UnauthorizedException $e) {
$message = $e->getMessage();
$requiredRolesOrPermissions = $e->getRequiredPermissions();
}
$this->assertEquals('User does not have any of the necessary access rights.', $message);
$this->assertEquals(['some-permission', 'some-role'], $requiredRolesOrPermissions);
}
/** @test */
#[Test]
public function the_required_permissions_or_roles_can_be_displayed_in_the_exception()
{
Auth::login($this->testUser);
Config::set(['permission.display_permission_in_exception' => true]);
Config::set(['permission.display_role_in_exception' => true]);
$message = null;
try {
$this->roleOrPermissionMiddleware->handle(new Request, function () {
return (new Response)->setContent('<html></html>');
}, 'some-permission|some-role');
} catch (UnauthorizedException $e) {
$message = $e->getMessage();
}
$this->assertStringEndsWith('Necessary roles or permissions are some-permission, some-role', $message);
}
/** @test */
#[Test]
public function the_middleware_can_be_created_with_static_using_method()
{
$this->assertSame(
'Spatie\Permission\Middleware\RoleOrPermissionMiddleware:edit-articles',
RoleOrPermissionMiddleware::using('edit-articles')
);
$this->assertEquals(
'Spatie\Permission\Middleware\RoleOrPermissionMiddleware:edit-articles,my-guard',
RoleOrPermissionMiddleware::using('edit-articles', 'my-guard')
);
$this->assertEquals(
'Spatie\Permission\Middleware\RoleOrPermissionMiddleware:edit-articles|testAdminRole',
RoleOrPermissionMiddleware::using(['edit-articles', 'testAdminRole'])
);
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/TestCase.php | tests/TestCase.php | <?php
namespace Spatie\Permission\Tests;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Foundation\Console\AboutCommand;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Schema;
use Laravel\Passport\PassportServiceProvider;
use Orchestra\Testbench\TestCase as Orchestra;
use Spatie\Permission\Contracts\Permission;
use Spatie\Permission\Contracts\Role;
use Spatie\Permission\Exceptions\UnauthorizedException;
use Spatie\Permission\PermissionRegistrar;
use Spatie\Permission\PermissionServiceProvider;
use Spatie\Permission\Tests\TestModels\Admin;
use Spatie\Permission\Tests\TestModels\Client;
use Spatie\Permission\Tests\TestModels\User;
abstract class TestCase extends Orchestra
{
/** @var \Spatie\Permission\Tests\TestModels\User */
protected $testUser;
/** @var \Spatie\Permission\Tests\TestModels\Admin */
protected $testAdmin;
/** @var \Spatie\Permission\Models\Role */
protected $testUserRole;
/** @var \Spatie\Permission\Models\Role */
protected $testAdminRole;
/** @var \Spatie\Permission\Models\Permission */
protected $testUserPermission;
/** @var \Spatie\Permission\Models\Permission */
protected $testAdminPermission;
/** @var bool */
protected $useCustomModels = false;
/** @var bool */
protected $hasTeams = false;
protected static $migration;
protected static $customMigration;
/** @var bool */
protected $usePassport = false;
protected Client $testClient;
protected \Spatie\Permission\Models\Permission $testClientPermission;
protected \Spatie\Permission\Models\Role $testClientRole;
protected function setUp(): void
{
parent::setUp();
if (! self::$migration) {
$this->prepareMigration();
}
// Note: this also flushes the cache from within the migration
$this->setUpDatabase($this->app);
$this->setUpBaseTestPermissions($this->app);
if ($this->hasTeams) {
setPermissionsTeamId(1);
}
if ($this->usePassport) {
$this->setUpPassport($this->app);
}
$this->setUpRoutes();
}
protected function tearDown(): void
{
parent::tearDown();
if (method_exists(AboutCommand::class, 'flushState')) {
AboutCommand::flushState();
}
}
/**
* @param \Illuminate\Foundation\Application $app
*/
protected function getPackageProviders($app): array
{
return $this->getLaravelVersion() < 9 ? [
PermissionServiceProvider::class,
] : [
PermissionServiceProvider::class,
PassportServiceProvider::class,
];
}
/**
* Set up the environment.
*
* @param \Illuminate\Foundation\Application $app
*/
protected function getEnvironmentSetUp($app)
{
Model::preventLazyLoading();
$app['config']->set('permission.register_permission_check_method', true);
$app['config']->set('permission.teams', $this->hasTeams);
$app['config']->set('permission.testing', true); // fix sqlite
$app['config']->set('permission.column_names.model_morph_key', 'model_test_id');
$app['config']->set('permission.column_names.team_foreign_key', 'team_test_id');
$app['config']->set('database.default', 'sqlite');
$app['config']->set('database.connections.sqlite', [
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
]);
$app['config']->set('permission.column_names.role_pivot_key', 'role_test_id');
$app['config']->set('permission.column_names.permission_pivot_key', 'permission_test_id');
$app['config']->set('view.paths', [__DIR__.'/resources/views']);
// ensure api guard exists, since we use it for testing multi-guard support
$app['config']->set('auth.guards.api', ['driver' => 'session', 'provider' => 'users']);
// Set-up admin guard
$app['config']->set('auth.guards.admin', ['driver' => 'session', 'provider' => 'admins']);
$app['config']->set('auth.providers.admins', ['driver' => 'eloquent', 'model' => Admin::class]);
if ($this->useCustomModels) {
$app['config']->set('permission.models.permission', \Spatie\Permission\Tests\TestModels\Permission::class);
$app['config']->set('permission.models.role', \Spatie\Permission\Tests\TestModels\Role::class);
}
// Use test User model for users provider
$app['config']->set('auth.providers.users.model', User::class);
$app['config']->set('cache.prefix', 'spatie_tests---');
$app['config']->set('cache.default', getenv('CACHE_DRIVER') ?: 'array');
// FOR MANUAL TESTING OF ALTERNATE CACHE STORES:
// $app['config']->set('cache.default', 'array');
// Laravel supports: array, database, file
// requires extensions: memcached, redis, dynamodb, octane
}
/**
* Set up the database.
*
* @param \Illuminate\Foundation\Application $app
*/
protected function setUpDatabase($app)
{
$schema = $app['db']->connection()->getSchemaBuilder();
$schema->create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('email');
$table->softDeletes();
});
$schema->create('admins', function (Blueprint $table) {
$table->increments('id');
$table->string('email');
});
$schema->create('content', function (Blueprint $table) {
$table->increments('id');
$table->string('content');
$table->foreignId('user_id')->nullable()->constrained()->nullOnDelete();
$table->timestamps();
});
if (Cache::getStore() instanceof \Illuminate\Cache\DatabaseStore ||
$app[PermissionRegistrar::class]->getCacheStore() instanceof \Illuminate\Cache\DatabaseStore) {
$this->createCacheTable();
}
if (! $this->useCustomModels) {
self::$migration->up();
} else {
self::$customMigration->up();
$schema->table(config('permission.table_names.roles'), function (Blueprint $table) {
$table->softDeletes();
});
$schema->table(config('permission.table_names.permissions'), function (Blueprint $table) {
$table->softDeletes();
});
}
$this->testUser = User::create(['email' => 'test@user.com']);
$this->testAdmin = Admin::create(['email' => 'admin@user.com']);
}
/**
* Set up initial roles and permissions used in many tests
*
* @param \Illuminate\Foundation\Application $app
*/
protected function setUpBaseTestPermissions($app): void
{
$this->testUserRole = $app[Role::class]->create(['name' => 'testRole']);
$app[Role::class]->create(['name' => 'testRole2']);
$this->testAdminRole = $app[Role::class]->create(['name' => 'testAdminRole', 'guard_name' => 'admin']);
$this->testUserPermission = $app[Permission::class]->create(['name' => 'edit-articles']);
$app[Permission::class]->create(['name' => 'edit-news']);
$app[Permission::class]->create(['name' => 'edit-blog']);
$this->testAdminPermission = $app[Permission::class]->create([
'name' => 'admin-permission',
'guard_name' => 'admin',
]);
$app[Permission::class]->create(['name' => 'Edit News']);
}
protected function setUpPassport($app): void
{
if ($this->getLaravelVersion() < 9) {
return;
}
$app['config']->set('permission.use_passport_client_credentials', true);
$app['config']->set('auth.guards.api', ['driver' => 'passport', 'provider' => 'users']);
// mimic passport:install (must load migrations using our own call to loadMigrationsFrom() else rollbacks won't occur, and migrations will be left in skeleton directory
// $this->artisan('passport:keys');
$this->loadMigrationsFrom(__DIR__.'/../vendor/laravel/passport/database/migrations/');
$provider = in_array('users', array_keys(config('auth.providers'))) ? 'users' : null;
$this->artisan('passport:client', ['--personal' => true, '--name' => config('app.name').' Personal Access Client']);
$this->artisan('passport:client', ['--password' => true, '--name' => config('app.name').' Password Grant Client', '--provider' => $provider]);
$this->testClient = Client::create(['name' => 'Test', 'redirect' => 'https://example.com', 'personal_access_client' => 0, 'password_client' => 0, 'revoked' => 0]);
$this->testClientRole = $app[Role::class]->create(['name' => 'clientRole', 'guard_name' => 'api']);
$this->testClientPermission = $app[Permission::class]->create(['name' => 'edit-posts', 'guard_name' => 'api']);
}
private function prepareMigration()
{
$migration = str_replace(
[
'(\'id\'); // permission id',
'(\'id\'); // role id',
'references(\'id\') // permission id',
'references(\'id\') // role id',
'bigIncrements',
'unsignedBigInteger($pivotRole)',
'unsignedBigInteger($pivotPermission)',
],
[
'(\'permission_test_id\');',
'(\'role_test_id\');',
'references(\'permission_test_id\')',
'references(\'role_test_id\')',
'uuid',
'uuid($pivotRole)->nullable(false)',
'uuid($pivotPermission)->nullable(false)',
],
file_get_contents(__DIR__.'/../database/migrations/create_permission_tables.php.stub')
);
file_put_contents(__DIR__.'/CreatePermissionCustomTables.php', $migration);
self::$migration = require __DIR__.'/../database/migrations/create_permission_tables.php.stub';
self::$customMigration = require __DIR__.'/CreatePermissionCustomTables.php';
}
protected function reloadPermissions()
{
app(PermissionRegistrar::class)->forgetCachedPermissions();
}
public function createCacheTable()
{
Schema::create('cache', function ($table) {
$table->string('key')->unique();
$table->text('value');
$table->integer('expiration');
});
}
/**
* Create routes to test authentication with guards.
*/
public function setUpRoutes(): void
{
Route::middleware('auth:api')->get('/check-api-guard-permission', function (Request $request) {
return [
'status' => $request->user()->hasPermissionTo('do_that'),
];
});
}
// //// TEST HELPERS
public function runMiddleware($middleware, $permission, $guard = null, bool $client = false)
{
$request = new Request;
if ($client) {
$request->headers->set('Authorization', 'Bearer '.str()->random(30));
}
try {
return $middleware->handle($request, function () {
return (new Response)->setContent('<html></html>');
}, $permission, $guard)->status();
} catch (UnauthorizedException $e) {
return $e->getStatusCode();
}
}
public function getLastRouteMiddlewareFromRouter($router)
{
return last($router->getRoutes()->get())->middleware();
}
public function getRouter()
{
return app('router');
}
public function getRouteResponse()
{
return function () {
return (new Response)->setContent('<html></html>');
};
}
protected function getLaravelVersion()
{
return (float) app()->version();
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/RoleWithNestingTest.php | tests/RoleWithNestingTest.php | <?php
namespace Spatie\Permission\Tests;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Test;
use Spatie\Permission\Tests\TestModels\Role;
class RoleWithNestingTest extends TestCase
{
/** @var bool */
protected $useCustomModels = true;
/** @var Role[] */
protected array $parent_roles = [];
/** @var Role[] */
protected array $child_roles = [];
protected function setUp(): void
{
parent::setUp();
$this->parent_roles = [
'has_no_children' => Role::create(['name' => 'has_no_children']),
'has_1_child' => Role::create(['name' => 'has_1_child']),
'has_3_children' => Role::create(['name' => 'has_3_children']),
];
$this->child_roles = [
'has_no_parents' => Role::create(['name' => 'has_no_parents']),
'has_1_parent' => Role::create(['name' => 'has_1_parent']),
'has_2_parents' => Role::create(['name' => 'has_2_parents']),
'third_child' => Role::create(['name' => 'third_child']),
];
$this->parent_roles['has_1_child']->children()->attach($this->child_roles['has_2_parents']);
$this->parent_roles['has_3_children']->children()->attach([
$this->child_roles['has_2_parents']->getKey(),
$this->child_roles['has_1_parent']->getKey(),
$this->child_roles['third_child']->getKey(),
]);
}
/**
* Set up the database.
*
* @param \Illuminate\Foundation\Application $app
*/
protected function setUpDatabase($app)
{
parent::setUpDatabase($app);
$tableRoles = $app['config']->get('permission.table_names.roles');
$app['db']->connection()->getSchemaBuilder()->create(Role::HIERARCHY_TABLE, function ($table) use ($tableRoles) {
$table->id();
$table->uuid('parent_id');
$table->uuid('child_id');
$table->foreign('parent_id')->references('role_test_id')->on($tableRoles);
$table->foreign('child_id')->references('role_test_id')->on($tableRoles);
});
}
/** @test
* @dataProvider roles_list
*/
#[DataProvider('roles_list')]
#[Test]
public function it_returns_correct_withCount_of_nested_roles($role_group, $index, $relation, $expectedCount)
{
$role = $this->$role_group[$index];
$count_field_name = sprintf('%s_count', $relation);
$actualCount = (int) Role::withCount($relation)->find($role->getKey())->$count_field_name;
$this->assertSame(
$expectedCount,
$actualCount,
sprintf('%s expects %d %s, %d found', $role->name, $expectedCount, $relation, $actualCount)
);
}
public static function roles_list()
{
return [
['parent_roles', 'has_no_children', 'children', 0],
['parent_roles', 'has_1_child', 'children', 1],
['parent_roles', 'has_3_children', 'children', 3],
['child_roles', 'has_no_parents', 'parents', 0],
['child_roles', 'has_1_parent', 'parents', 1],
['child_roles', 'has_2_parents', 'parents', 2],
];
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/GateTest.php | tests/GateTest.php | <?php
namespace Spatie\Permission\Tests;
use Illuminate\Contracts\Auth\Access\Gate;
use PHPUnit\Framework\Attributes\RequiresPhp;
use PHPUnit\Framework\Attributes\Test;
use Spatie\Permission\Contracts\Permission;
class GateTest extends TestCase
{
/** @test */
#[Test]
public function it_can_determine_if_a_user_does_not_have_a_permission()
{
$this->assertFalse($this->testUser->can('edit-articles'));
}
/** @test */
#[Test]
public function it_allows_other_gate_before_callbacks_to_run_if_a_user_does_not_have_a_permission()
{
$this->assertFalse($this->testUser->can('edit-articles'));
app(Gate::class)->before(function () {
// this Gate-before intercept overrides everything to true ... like a typical Super-Admin might use
return true;
});
$this->assertTrue($this->testUser->can('edit-articles'));
}
/** @test */
#[Test]
public function it_allows_gate_after_callback_to_grant_denied_privileges()
{
$this->assertFalse($this->testUser->can('edit-articles'));
app(Gate::class)->after(function ($user, $ability, $result) {
return true;
});
$this->assertTrue($this->testUser->can('edit-articles'));
}
/** @test */
#[Test]
public function it_can_determine_if_a_user_has_a_direct_permission()
{
$this->testUser->givePermissionTo('edit-articles');
$this->assertTrue($this->testUser->can('edit-articles'));
$this->assertFalse($this->testUser->can('non-existing-permission'));
$this->assertFalse($this->testUser->can('admin-permission'));
}
/**
* @test
*
* @requires PHP >= 8.1
*/
#[RequiresPhp('>= 8.1')]
#[Test]
public function it_can_determine_if_a_user_has_a_direct_permission_using_enums()
{
$enum = TestModels\TestRolePermissionsEnum::VIEWARTICLES;
$permission = app(Permission::class)->findOrCreate($enum->value, 'web');
$this->assertFalse($this->testUser->can($enum->value));
$this->assertFalse($this->testUser->canAny([$enum->value, 'some other permission']));
$this->testUser->givePermissionTo($enum);
$this->assertTrue($this->testUser->hasPermissionTo($enum));
$this->assertTrue($this->testUser->can($enum->value));
$this->assertTrue($this->testUser->canAny([$enum->value, 'some other permission']));
}
/** @test */
#[Test]
public function it_can_determine_if_a_user_has_a_permission_through_roles()
{
$this->testUserRole->givePermissionTo($this->testUserPermission);
$this->testUser->assignRole($this->testUserRole);
$this->assertTrue($this->testUser->hasPermissionTo($this->testUserPermission));
$this->assertTrue($this->testUser->can('edit-articles'));
$this->assertFalse($this->testUser->can('non-existing-permission'));
$this->assertFalse($this->testUser->can('admin-permission'));
}
/** @test */
#[Test]
public function it_can_determine_if_a_user_with_a_different_guard_has_a_permission_when_using_roles()
{
$this->testAdminRole->givePermissionTo($this->testAdminPermission);
$this->testAdmin->assignRole($this->testAdminRole);
$this->assertTrue($this->testAdmin->hasPermissionTo($this->testAdminPermission));
$this->assertTrue($this->testAdmin->can('admin-permission'));
$this->assertFalse($this->testAdmin->can('non-existing-permission'));
$this->assertFalse($this->testAdmin->can('edit-articles'));
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/WildcardHasPermissionsTest.php | tests/WildcardHasPermissionsTest.php | <?php
namespace Spatie\Permission\Tests;
use PHPUnit\Framework\Attributes\RequiresPhp;
use PHPUnit\Framework\Attributes\Test;
use Spatie\Permission\Exceptions\PermissionDoesNotExist;
use Spatie\Permission\Exceptions\WildcardPermissionInvalidArgument;
use Spatie\Permission\Exceptions\WildcardPermissionNotProperlyFormatted;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Tests\TestModels\User;
use Spatie\Permission\Tests\TestModels\WildcardPermission;
class WildcardHasPermissionsTest extends TestCase
{
/** @test */
#[Test]
public function it_can_check_wildcard_permission()
{
app('config')->set('permission.enable_wildcard_permission', true);
$user1 = User::create(['email' => 'user1@test.com']);
$permission1 = Permission::create(['name' => 'articles.edit,view,create']);
$permission2 = Permission::create(['name' => 'news.*']);
$permission3 = Permission::create(['name' => 'posts.*']);
$user1->givePermissionTo([$permission1, $permission2, $permission3]);
$this->assertTrue($user1->hasPermissionTo('posts.create'));
$this->assertTrue($user1->hasPermissionTo('posts.create.123'));
$this->assertTrue($user1->hasPermissionTo('posts.*'));
$this->assertTrue($user1->hasPermissionTo('articles.view'));
$this->assertFalse($user1->hasPermissionTo('projects.view'));
}
/** @test */
#[Test]
public function it_can_check_wildcard_permission_for_a_non_default_guard()
{
app('config')->set('permission.enable_wildcard_permission', true);
$user1 = User::create(['email' => 'user1@test.com']);
$permission1 = Permission::create(['name' => 'articles.edit,view,create', 'guard_name' => 'api']);
$permission2 = Permission::create(['name' => 'news.*', 'guard_name' => 'api']);
$permission3 = Permission::create(['name' => 'posts.*', 'guard_name' => 'api']);
$user1->givePermissionTo([$permission1, $permission2, $permission3]);
$this->assertTrue($user1->hasPermissionTo('posts.create', 'api'));
$this->assertTrue($user1->hasPermissionTo('posts.create.123', 'api'));
$this->assertTrue($user1->hasPermissionTo('posts.*', 'api'));
$this->assertTrue($user1->hasPermissionTo('articles.view', 'api'));
$this->assertFalse($user1->hasPermissionTo('projects.view', 'api'));
}
/** @test */
#[Test]
public function it_can_check_wildcard_permission_from_instance_without_explicit_guard_argument()
{
app('config')->set('permission.enable_wildcard_permission', true);
$user1 = User::create(['email' => 'user1@test.com']);
$permission2 = Permission::create(['name' => 'articles.view']);
$permission1 = Permission::create(['name' => 'articles.edit', 'guard_name' => 'api']);
$permission3 = Permission::create(['name' => 'news.*', 'guard_name' => 'api']);
$permission4 = Permission::create(['name' => 'posts.*', 'guard_name' => 'api']);
$user1->givePermissionTo([$permission1, $permission2, $permission3]);
$this->assertTrue($user1->hasPermissionTo($permission1));
$this->assertTrue($user1->hasPermissionTo($permission2));
$this->assertTrue($user1->hasPermissionTo($permission3));
$this->assertFalse($user1->hasPermissionTo($permission4));
$this->assertFalse($user1->hasPermissionTo('articles.edit'));
}
/**
* @test
*
* @requires PHP >= 8.1
*/
#[RequiresPhp('>= 8.1')]
#[Test]
public function it_can_assign_wildcard_permissions_using_enums()
{
app('config')->set('permission.enable_wildcard_permission', true);
$user1 = User::create(['email' => 'user1@test.com']);
$articlesCreator = TestModels\TestRolePermissionsEnum::WildcardArticlesCreator;
$newsEverything = TestModels\TestRolePermissionsEnum::WildcardNewsEverything;
$postsEverything = TestModels\TestRolePermissionsEnum::WildcardPostsEverything;
$postsCreate = TestModels\TestRolePermissionsEnum::WildcardPostsCreate;
$permission1 = app(Permission::class)->findOrCreate($articlesCreator->value, 'web');
$permission2 = app(Permission::class)->findOrCreate($newsEverything->value, 'web');
$permission3 = app(Permission::class)->findOrCreate($postsEverything->value, 'web');
$user1->givePermissionTo([$permission1, $permission2, $permission3]);
$this->assertTrue($user1->hasPermissionTo($postsCreate));
$this->assertTrue($user1->hasPermissionTo($postsCreate->value.'.123'));
$this->assertTrue($user1->hasPermissionTo($postsEverything));
$this->assertTrue($user1->hasPermissionTo(TestModels\TestRolePermissionsEnum::WildcardArticlesView));
$this->assertTrue($user1->hasAnyPermission(TestModels\TestRolePermissionsEnum::WildcardArticlesView));
$this->assertFalse($user1->hasPermissionTo(TestModels\TestRolePermissionsEnum::WildcardProjectsView));
$user1->revokePermissionTo([$permission1, $permission2, $permission3]);
$this->assertFalse($user1->hasPermissionTo(TestModels\TestRolePermissionsEnum::WildcardPostsCreate));
$this->assertFalse($user1->hasPermissionTo($postsCreate->value.'.123'));
$this->assertFalse($user1->hasPermissionTo(TestModels\TestRolePermissionsEnum::WildcardPostsEverything));
$this->assertFalse($user1->hasPermissionTo(TestModels\TestRolePermissionsEnum::WildcardArticlesView));
$this->assertFalse($user1->hasAnyPermission(TestModels\TestRolePermissionsEnum::WildcardArticlesView));
}
/** @test */
#[Test]
public function it_can_check_wildcard_permissions_via_roles()
{
app('config')->set('permission.enable_wildcard_permission', true);
$user1 = User::create(['email' => 'user1@test.com']);
$user1->assignRole('testRole');
$permission1 = Permission::create(['name' => 'articles,projects.edit,view,create']);
$permission2 = Permission::create(['name' => 'news.*.456']);
$permission3 = Permission::create(['name' => 'posts']);
$this->testUserRole->givePermissionTo([$permission1, $permission2, $permission3]);
$this->assertTrue($user1->hasPermissionTo('posts.create'));
$this->assertTrue($user1->hasPermissionTo('news.create.456'));
$this->assertTrue($user1->hasPermissionTo('projects.create'));
$this->assertTrue($user1->hasPermissionTo('articles.view'));
$this->assertFalse($user1->hasPermissionTo('articles.list'));
$this->assertFalse($user1->hasPermissionTo('projects.list'));
}
/** @test */
#[Test]
public function it_can_check_custom_wildcard_permission()
{
app('config')->set('permission.enable_wildcard_permission', true);
app('config')->set('permission.wildcard_permission', WildcardPermission::class);
$user1 = User::create(['email' => 'user1@test.com']);
$permission1 = Permission::create(['name' => 'articles:edit;view;create']);
$permission2 = Permission::create(['name' => 'news:@']);
$permission3 = Permission::create(['name' => 'posts:@']);
$user1->givePermissionTo([$permission1, $permission2, $permission3]);
$this->assertTrue($user1->hasPermissionTo('posts:create'));
$this->assertTrue($user1->hasPermissionTo('posts:create:123'));
$this->assertTrue($user1->hasPermissionTo('posts:@'));
$this->assertTrue($user1->hasPermissionTo('articles:view'));
$this->assertFalse($user1->hasPermissionTo('posts.*'));
$this->assertFalse($user1->hasPermissionTo('articles.view'));
$this->assertFalse($user1->hasPermissionTo('projects:view'));
}
/** @test */
#[Test]
public function it_can_check_custom_wildcard_permissions_via_roles()
{
app('config')->set('permission.enable_wildcard_permission', true);
app('config')->set('permission.wildcard_permission', WildcardPermission::class);
$user1 = User::create(['email' => 'user1@test.com']);
$user1->assignRole('testRole');
$permission1 = Permission::create(['name' => 'articles;projects:edit;view;create']);
$permission2 = Permission::create(['name' => 'news:@:456']);
$permission3 = Permission::create(['name' => 'posts']);
$this->testUserRole->givePermissionTo([$permission1, $permission2, $permission3]);
$this->assertTrue($user1->hasPermissionTo('posts:create'));
$this->assertTrue($user1->hasPermissionTo('news:create:456'));
$this->assertTrue($user1->hasPermissionTo('projects:create'));
$this->assertTrue($user1->hasPermissionTo('articles:view'));
$this->assertFalse($user1->hasPermissionTo('news.create.456'));
$this->assertFalse($user1->hasPermissionTo('projects.create'));
$this->assertFalse($user1->hasPermissionTo('articles:list'));
$this->assertFalse($user1->hasPermissionTo('projects:list'));
}
/** @test */
#[Test]
public function it_can_check_non_wildcard_permissions()
{
app('config')->set('permission.enable_wildcard_permission', true);
$user1 = User::create(['email' => 'user1@test.com']);
$permission1 = Permission::create(['name' => 'edit articles']);
$permission2 = Permission::create(['name' => 'create news']);
$permission3 = Permission::create(['name' => 'update comments']);
$user1->givePermissionTo([$permission1, $permission2, $permission3]);
$this->assertTrue($user1->hasPermissionTo('edit articles'));
$this->assertTrue($user1->hasPermissionTo('create news'));
$this->assertTrue($user1->hasPermissionTo('update comments'));
}
/** @test */
#[Test]
public function it_can_verify_complex_wildcard_permissions()
{
app('config')->set('permission.enable_wildcard_permission', true);
$user1 = User::create(['email' => 'user1@test.com']);
$permission1 = Permission::create(['name' => '*.create,update,delete.*.test,course,finance']);
$permission2 = Permission::create(['name' => 'papers,posts,projects,orders.*.test,test1,test2.*']);
$permission3 = Permission::create(['name' => 'User::class.create,edit,view']);
$user1->givePermissionTo([$permission1, $permission2, $permission3]);
$this->assertTrue($user1->hasPermissionTo('invoices.delete.367463.finance'));
$this->assertTrue($user1->hasPermissionTo('projects.update.test2.test3'));
$this->assertTrue($user1->hasPermissionTo('User::class.edit'));
$this->assertFalse($user1->hasPermissionTo('User::class.delete'));
$this->assertFalse($user1->hasPermissionTo('User::class.*'));
}
/** @test */
#[Test]
public function it_throws_exception_when_wildcard_permission_is_not_properly_formatted()
{
app('config')->set('permission.enable_wildcard_permission', true);
$user1 = User::create(['email' => 'user1@test.com']);
$permission = Permission::create(['name' => '*..']);
$user1->givePermissionTo([$permission]);
$this->expectException(WildcardPermissionNotProperlyFormatted::class);
$user1->hasPermissionTo('invoices.*');
}
/** @test */
#[Test]
public function it_can_verify_permission_instances_not_assigned_to_user()
{
app('config')->set('permission.enable_wildcard_permission', true);
$user = User::create(['email' => 'user@test.com']);
$userPermission = Permission::create(['name' => 'posts.*']);
$permissionToVerify = Permission::create(['name' => 'posts.create']);
$user->givePermissionTo([$userPermission]);
$this->assertTrue($user->hasPermissionTo('posts.create'));
$this->assertTrue($user->hasPermissionTo('posts.create.123'));
$this->assertTrue($user->hasPermissionTo($permissionToVerify->id));
$this->assertTrue($user->hasPermissionTo($permissionToVerify));
}
/** @test */
#[Test]
public function it_can_verify_permission_instances_assigned_to_user()
{
app('config')->set('permission.enable_wildcard_permission', true);
$user = User::create(['email' => 'user@test.com']);
$userPermission = Permission::create(['name' => 'posts.*']);
$permissionToVerify = Permission::create(['name' => 'posts.create']);
$user->givePermissionTo([$userPermission, $permissionToVerify]);
$this->assertTrue($user->hasPermissionTo('posts.create'));
$this->assertTrue($user->hasPermissionTo('posts.create.123'));
$this->assertTrue($user->hasPermissionTo($permissionToVerify));
$this->assertTrue($user->hasPermissionTo($userPermission));
}
/** @test */
#[Test]
public function it_can_verify_integers_as_strings()
{
app('config')->set('permission.enable_wildcard_permission', true);
$user = User::create(['email' => 'user@test.com']);
$userPermission = Permission::create(['name' => '8']);
$user->givePermissionTo([$userPermission]);
$this->assertTrue($user->hasPermissionTo('8'));
}
/** @test */
#[Test]
public function it_throws_exception_when_permission_has_invalid_arguments()
{
app('config')->set('permission.enable_wildcard_permission', true);
$user = User::create(['email' => 'user@test.com']);
$this->expectException(WildcardPermissionInvalidArgument::class);
$user->hasPermissionTo(['posts.create']);
}
/** @test */
#[Test]
public function it_throws_exception_when_permission_id_not_exists()
{
app('config')->set('permission.enable_wildcard_permission', true);
$user = User::create(['email' => 'user@test.com']);
$this->expectException(PermissionDoesNotExist::class);
$user->hasPermissionTo(6);
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/RoleTest.php | tests/RoleTest.php | <?php
namespace Spatie\Permission\Tests;
use PHPUnit\Framework\Attributes\Test;
use Spatie\Permission\Contracts\Role;
use Spatie\Permission\Exceptions\GuardDoesNotMatch;
use Spatie\Permission\Exceptions\PermissionDoesNotExist;
use Spatie\Permission\Exceptions\RoleAlreadyExists;
use Spatie\Permission\Exceptions\RoleDoesNotExist;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\PermissionRegistrar;
use Spatie\Permission\Tests\TestModels\Admin;
use Spatie\Permission\Tests\TestModels\RuntimeRole;
use Spatie\Permission\Tests\TestModels\User;
class RoleTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
Permission::create(['name' => 'other-permission']);
Permission::create(['name' => 'wrong-guard-permission', 'guard_name' => 'admin']);
}
/** @test */
#[Test]
public function it_get_user_models_using_with()
{
$this->testUser->assignRole($this->testUserRole);
$role = app(Role::class)::with('users')
->where($this->testUserRole->getKeyName(), $this->testUserRole->getKey())->first();
$this->assertEquals($role->getKey(), $this->testUserRole->getKey());
$this->assertCount(1, $role->users);
$this->assertEquals($role->users[0]->id, $this->testUser->id);
}
/** @test */
#[Test]
public function it_has_user_models_of_the_right_class()
{
$this->testAdmin->assignRole($this->testAdminRole);
$this->testUser->assignRole($this->testUserRole);
$this->assertCount(1, $this->testUserRole->users);
$this->assertTrue($this->testUserRole->users->first()->is($this->testUser));
$this->assertInstanceOf(User::class, $this->testUserRole->users->first());
$this->assertCount(1, $this->testAdminRole->users);
$this->assertTrue($this->testAdminRole->users->first()->is($this->testAdmin));
$this->assertInstanceOf(Admin::class, $this->testAdminRole->users->first());
}
/** @test */
#[Test]
public function it_throws_an_exception_when_the_role_already_exists()
{
$this->expectException(RoleAlreadyExists::class);
app(Role::class)->create(['name' => 'test-role']);
app(Role::class)->create(['name' => 'test-role']);
}
/** @test */
#[Test]
public function it_can_be_given_a_permission()
{
$this->testUserRole->givePermissionTo('edit-articles');
$this->assertTrue($this->testUserRole->hasPermissionTo('edit-articles'));
}
/** @test */
#[Test]
public function it_throws_an_exception_when_given_a_permission_that_does_not_exist()
{
$this->expectException(PermissionDoesNotExist::class);
$this->testUserRole->givePermissionTo('create-evil-empire');
}
/** @test */
#[Test]
public function it_throws_an_exception_when_given_a_permission_that_belongs_to_another_guard()
{
$this->expectException(PermissionDoesNotExist::class);
$this->testUserRole->givePermissionTo('admin-permission');
$this->expectException(GuardDoesNotMatch::class);
$this->testUserRole->givePermissionTo($this->testAdminPermission);
}
/** @test */
#[Test]
public function it_can_be_given_multiple_permissions_using_an_array()
{
$this->testUserRole->givePermissionTo(['edit-articles', 'edit-news']);
$this->assertTrue($this->testUserRole->hasPermissionTo('edit-articles'));
$this->assertTrue($this->testUserRole->hasPermissionTo('edit-news'));
}
/** @test */
#[Test]
public function it_can_be_given_multiple_permissions_using_multiple_arguments()
{
$this->testUserRole->givePermissionTo('edit-articles', 'edit-news');
$this->assertTrue($this->testUserRole->hasPermissionTo('edit-articles'));
$this->assertTrue($this->testUserRole->hasPermissionTo('edit-news'));
}
/** @test */
#[Test]
public function it_can_sync_permissions()
{
$this->testUserRole->givePermissionTo('edit-articles');
$this->testUserRole->syncPermissions('edit-news');
$this->assertFalse($this->testUserRole->hasPermissionTo('edit-articles'));
$this->assertTrue($this->testUserRole->hasPermissionTo('edit-news'));
}
/** @test */
#[Test]
public function it_throws_an_exception_when_syncing_permissions_that_do_not_exist()
{
$this->testUserRole->givePermissionTo('edit-articles');
$this->expectException(PermissionDoesNotExist::class);
$this->testUserRole->syncPermissions('permission-does-not-exist');
}
/** @test */
#[Test]
public function it_throws_an_exception_when_syncing_permissions_that_belong_to_a_different_guard()
{
$this->testUserRole->givePermissionTo('edit-articles');
$this->expectException(PermissionDoesNotExist::class);
$this->testUserRole->syncPermissions('admin-permission');
$this->expectException(GuardDoesNotMatch::class);
$this->testUserRole->syncPermissions($this->testAdminPermission);
}
/** @test */
#[Test]
public function it_will_remove_all_permissions_when_passing_an_empty_array_to_sync_permissions()
{
$this->testUserRole->givePermissionTo('edit-articles');
$this->testUserRole->givePermissionTo('edit-news');
$this->testUserRole->syncPermissions([]);
$this->assertFalse($this->testUserRole->hasPermissionTo('edit-articles'));
$this->assertFalse($this->testUserRole->hasPermissionTo('edit-news'));
}
/** @test */
#[Test]
public function sync_permission_error_does_not_detach_permissions()
{
$this->testUserRole->givePermissionTo('edit-news');
$this->expectException(PermissionDoesNotExist::class);
$this->testUserRole->syncPermissions('edit-articles', 'permission-that-does-not-exist');
$this->assertTrue($this->testUserRole->fresh()->hasDirectPermission('edit-news'));
}
/** @test */
#[Test]
public function it_can_revoke_a_permission()
{
$this->testUserRole->givePermissionTo('edit-articles');
$this->assertTrue($this->testUserRole->hasPermissionTo('edit-articles'));
$this->testUserRole->revokePermissionTo('edit-articles');
$this->testUserRole = $this->testUserRole->fresh();
$this->assertFalse($this->testUserRole->hasPermissionTo('edit-articles'));
}
/** @test */
#[Test]
public function it_can_be_given_a_permission_using_objects()
{
$this->testUserRole->givePermissionTo($this->testUserPermission);
$this->assertTrue($this->testUserRole->hasPermissionTo($this->testUserPermission));
}
/** @test */
#[Test]
public function it_returns_false_if_it_does_not_have_the_permission()
{
$this->assertFalse($this->testUserRole->hasPermissionTo('other-permission'));
}
/** @test */
#[Test]
public function it_throws_an_exception_if_the_permission_does_not_exist()
{
$this->expectException(PermissionDoesNotExist::class);
$this->testUserRole->hasPermissionTo('doesnt-exist');
}
/** @test */
#[Test]
public function it_returns_false_if_it_does_not_have_a_permission_object()
{
$permission = app(Permission::class)->findByName('other-permission');
$this->assertFalse($this->testUserRole->hasPermissionTo($permission));
}
/** @test */
#[Test]
public function it_creates_permission_object_with_findOrCreate_if_it_does_not_have_a_permission_object()
{
$permission = app(Permission::class)->findOrCreate('another-permission');
$this->assertFalse($this->testUserRole->hasPermissionTo($permission));
$this->testUserRole->givePermissionTo($permission);
$this->testUserRole = $this->testUserRole->fresh();
$this->assertTrue($this->testUserRole->hasPermissionTo('another-permission'));
}
/** @test */
#[Test]
public function it_creates_a_role_with_findOrCreate_if_the_named_role_does_not_exist()
{
$this->expectException(RoleDoesNotExist::class);
$role1 = app(Role::class)->findByName('non-existing-role');
$this->assertNull($role1);
$role2 = app(Role::class)->findOrCreate('yet-another-role');
$this->assertInstanceOf(Role::class, $role2);
}
/** @test */
#[Test]
public function it_throws_an_exception_when_a_permission_of_the_wrong_guard_is_passed_in()
{
$this->expectException(GuardDoesNotMatch::class);
$permission = app(Permission::class)->findByName('wrong-guard-permission', 'admin');
$this->testUserRole->hasPermissionTo($permission);
}
/** @test */
#[Test]
public function it_belongs_to_a_guard()
{
$role = app(Role::class)->create(['name' => 'admin', 'guard_name' => 'admin']);
$this->assertEquals('admin', $role->guard_name);
}
/** @test */
#[Test]
public function it_belongs_to_the_default_guard_by_default()
{
$this->assertEquals(
$this->app['config']->get('auth.defaults.guard'),
$this->testUserRole->guard_name
);
}
/** @test */
#[Test]
public function it_can_change_role_class_on_runtime()
{
$role = app(Role::class)->create(['name' => 'test-role-old']);
$this->assertNotInstanceOf(RuntimeRole::class, $role);
$role->givePermissionTo('edit-articles');
app('config')->set('permission.models.role', RuntimeRole::class);
app()->bind(Role::class, RuntimeRole::class);
app(PermissionRegistrar::class)->setRoleClass(RuntimeRole::class);
$permission = app(Permission::class)->findByName('edit-articles');
$this->assertInstanceOf(RuntimeRole::class, $permission->roles[0]);
$this->assertSame('test-role-old', $permission->roles[0]->name);
$role = app(Role::class)->create(['name' => 'test-role']);
$this->assertInstanceOf(RuntimeRole::class, $role);
$this->testUser->assignRole('test-role');
$this->assertTrue($this->testUser->hasRole('test-role'));
$this->assertInstanceOf(RuntimeRole::class, $this->testUser->roles[0]);
$this->assertSame('test-role', $this->testUser->roles[0]->name);
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/PolicyTest.php | tests/PolicyTest.php | <?php
namespace Spatie\Permission\Tests;
use Illuminate\Contracts\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Access\Gate;
use PHPUnit\Framework\Attributes\Test;
use Spatie\Permission\Tests\TestModels\Content;
class PolicyTest extends TestCase
{
/** @test */
#[Test]
public function policy_methods_and_before_intercepts_can_allow_and_deny()
{
$record1 = Content::create(['content' => 'special admin content']);
$record2 = Content::create(['content' => 'viewable', 'user_id' => $this->testUser->id]);
app(Gate::class)->policy(Content::class, ContentPolicy::class);
$this->assertFalse($this->testUser->can('view', $record1)); // policy rule for 'view'
$this->assertFalse($this->testUser->can('update', $record1)); // policy rule for 'update'
$this->assertTrue($this->testUser->can('update', $record2)); // policy rule for 'update' when matching user_id
// test that the Admin cannot yet view 'special admin content', because doesn't have Role yet
$this->assertFalse($this->testAdmin->can('update', $record1));
$this->testAdmin->assignRole($this->testAdminRole);
// test that the Admin can view 'special admin content'
$this->assertTrue($this->testAdmin->can('update', $record1)); // policy override via 'before'
$this->assertTrue($this->testAdmin->can('update', $record2)); // policy override via 'before'
}
}
class ContentPolicy
{
public function before(Authorizable $user, string $ability): ?bool
{
return $user->hasRole('testAdminRole', 'admin') ?: null;
}
public function view($user, $content)
{
return $user->id === $content->user_id;
}
public function update($user, $modelRecord): bool
{
return $user->id === $modelRecord->user_id || $user->can('edit-articles');
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/TestHelper.php | tests/TestHelper.php | <?php
namespace Spatie\Permission\Tests;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
class TestHelper
{
/**
* @param string $middleware
* @param object $parameter
* @return int
*/
public function testMiddleware($middleware, $parameter)
{
try {
return $middleware->handle(new Request, function () {
return (new Response)->setContent('<html></html>');
}, $parameter)->status();
} catch (HttpException $e) {
return $e->getStatusCode();
}
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/RouteTest.php | tests/RouteTest.php | <?php
namespace Spatie\Permission\Tests;
use PHPUnit\Framework\Attributes\RequiresPhp;
use PHPUnit\Framework\Attributes\Test;
use Spatie\Permission\Tests\TestModels\TestRolePermissionsEnum;
class RouteTest extends TestCase
{
/** @test */
#[Test]
public function test_role_function()
{
$router = $this->getRouter();
$router->get('role-test', $this->getRouteResponse())
->name('role.test')
->role('superadmin');
$this->assertEquals(['role:superadmin'], $this->getLastRouteMiddlewareFromRouter($router));
}
/** @test */
#[Test]
public function test_permission_function()
{
$router = $this->getRouter();
$router->get('permission-test', $this->getRouteResponse())
->name('permission.test')
->permission(['edit articles', 'save articles']);
$this->assertEquals(['permission:edit articles|save articles'], $this->getLastRouteMiddlewareFromRouter($router));
}
/** @test */
#[Test]
public function test_role_and_permission_function_together()
{
$router = $this->getRouter();
$router->get('role-permission-test', $this->getRouteResponse())
->name('role-permission.test')
->role('superadmin|admin')
->permission('create user|edit user');
$this->assertEquals(
[
'role:superadmin|admin',
'permission:create user|edit user',
],
$this->getLastRouteMiddlewareFromRouter($router)
);
}
/**
* @test
*
* @requires PHP 8.1.0
*/
#[RequiresPhp('>= 8.1.0')]
#[Test]
public function test_role_function_with_backed_enum()
{
$router = $this->getRouter();
$router->get('role-test.enum', $this->getRouteResponse())
->name('role.test.enum')
->role(TestRolePermissionsEnum::USERMANAGER);
$this->assertEquals(['role:'.TestRolePermissionsEnum::USERMANAGER->value], $this->getLastRouteMiddlewareFromRouter($router));
}
/**
* @test
*
* @requires PHP 8.1.0
*/
#[RequiresPhp('>= 8.1.0')]
#[Test]
public function test_permission_function_with_backed_enum()
{
$router = $this->getRouter();
$router->get('permission-test.enum', $this->getRouteResponse())
->name('permission.test.enum')
->permission(TestRolePermissionsEnum::WRITER);
$expected = ['permission:'.TestRolePermissionsEnum::WRITER->value];
$this->assertEquals($expected, $this->getLastRouteMiddlewareFromRouter($router));
}
/**
* @test
*
* @requires PHP 8.1.0
*/
#[RequiresPhp('>= 8.1.0')]
#[Test]
public function test_role_and_permission_function_together_with_backed_enum()
{
$router = $this->getRouter();
$router->get('roles-permissions-test.enum', $this->getRouteResponse())
->name('roles-permissions.test.enum')
->role([TestRolePermissionsEnum::USERMANAGER, TestRolePermissionsEnum::ADMIN])
->permission([TestRolePermissionsEnum::WRITER, TestRolePermissionsEnum::EDITOR]);
$this->assertEquals(
[
'role:'.TestRolePermissionsEnum::USERMANAGER->value.'|'.TestRolePermissionsEnum::ADMIN->value,
'permission:'.TestRolePermissionsEnum::WRITER->value.'|'.TestRolePermissionsEnum::EDITOR->value,
],
$this->getLastRouteMiddlewareFromRouter($router)
);
}
/** @test */
#[Test]
public function test_role_or_permission_function()
{
$router = $this->getRouter();
$router->get('role-or-permission-test', $this->getRouteResponse())
->name('role-or-permission.test')
->roleOrPermission('admin|edit articles');
$this->assertEquals(['role_or_permission:admin|edit articles'], $this->getLastRouteMiddlewareFromRouter($router));
}
/** @test */
#[Test]
public function test_role_or_permission_function_with_array()
{
$router = $this->getRouter();
$router->get('role-or-permission-array-test', $this->getRouteResponse())
->name('role-or-permission-array.test')
->roleOrPermission(['admin', 'edit articles']);
$this->assertEquals(['role_or_permission:admin|edit articles'], $this->getLastRouteMiddlewareFromRouter($router));
}
/**
* @test
*
* @requires PHP 8.1.0
*/
#[RequiresPhp('>= 8.1.0')]
#[Test]
public function test_role_or_permission_function_with_backed_enum()
{
$router = $this->getRouter();
$router->get('role-or-permission-test.enum', $this->getRouteResponse())
->name('role-or-permission.test.enum')
->roleOrPermission(TestRolePermissionsEnum::USERMANAGER);
$this->assertEquals(['role_or_permission:'.TestRolePermissionsEnum::USERMANAGER->value], $this->getLastRouteMiddlewareFromRouter($router));
}
/**
* @test
*
* @requires PHP 8.1.0
*/
#[RequiresPhp('>= 8.1.0')]
#[Test]
public function test_role_or_permission_function_with_backed_enum_array()
{
$router = $this->getRouter();
$router->get('role-or-permission-array-test.enum', $this->getRouteResponse())
->name('role-or-permission-array.test.enum')
->roleOrPermission([TestRolePermissionsEnum::USERMANAGER, TestRolePermissionsEnum::EDITARTICLES]); // @phpstan-ignore-line
$this->assertEquals(
['role_or_permission:'.TestRolePermissionsEnum::USERMANAGER->value.'|'.TestRolePermissionsEnum::EDITARTICLES->value], // @phpstan-ignore-line
$this->getLastRouteMiddlewareFromRouter($router)
);
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/WildcardRouteTest.php | tests/WildcardRouteTest.php | <?php
namespace Spatie\Permission\Tests;
use PHPUnit\Framework\Attributes\Test;
class WildcardRouteTest extends TestCase
{
/** @test */
#[Test]
public function test_permission_function()
{
app('config')->set('permission.enable_wildcard_permission', true);
$router = $this->getRouter();
$router->get('permission-test', $this->getRouteResponse())
->name('permission.test')
->permission(['articles.edit', 'articles.save']);
$this->assertEquals(['permission:articles.edit|articles.save'], $this->getLastRouteMiddlewareFromRouter($router));
}
/** @test */
#[Test]
public function test_role_and_permission_function_together()
{
app('config')->set('permission.enable_wildcard_permission', true);
$router = $this->getRouter();
$router->get('role-permission-test', $this->getRouteResponse())
->name('role-permission.test')
->role('superadmin|admin')
->permission('user.create|user.edit');
$this->assertEquals(
[
'role:superadmin|admin',
'permission:user.create|user.edit',
],
$this->getLastRouteMiddlewareFromRouter($router)
);
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/CommandTest.php | tests/CommandTest.php | <?php
namespace Spatie\Permission\Tests;
use Composer\InstalledVersions;
use Illuminate\Foundation\Console\AboutCommand;
use Illuminate\Support\Facades\Artisan;
use PHPUnit\Framework\Attributes\Test;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Tests\TestModels\User;
class CommandTest extends TestCase
{
/** @test */
#[Test]
public function it_can_create_a_role()
{
Artisan::call('permission:create-role', ['name' => 'new-role']);
$this->assertCount(1, Role::where('name', 'new-role')->get());
$this->assertCount(0, Role::where('name', 'new-role')->first()->permissions);
}
/** @test */
#[Test]
public function it_can_create_a_role_with_a_specific_guard()
{
Artisan::call('permission:create-role', [
'name' => 'new-role',
'guard' => 'api',
]);
$this->assertCount(1, Role::where('name', 'new-role')
->where('guard_name', 'api')
->get());
}
/** @test */
#[Test]
public function it_can_create_a_permission()
{
Artisan::call('permission:create-permission', ['name' => 'new-permission']);
$this->assertCount(1, Permission::where('name', 'new-permission')->get());
}
/** @test */
#[Test]
public function it_can_create_a_permission_with_a_specific_guard()
{
Artisan::call('permission:create-permission', [
'name' => 'new-permission',
'guard' => 'api',
]);
$this->assertCount(1, Permission::where('name', 'new-permission')
->where('guard_name', 'api')
->get());
}
/** @test */
#[Test]
public function it_can_create_a_role_and_permissions_at_same_time()
{
Artisan::call('permission:create-role', [
'name' => 'new-role',
'permissions' => 'first permission | second permission',
]);
$role = Role::where('name', 'new-role')->first();
$this->assertTrue($role->hasPermissionTo('first permission'));
$this->assertTrue($role->hasPermissionTo('second permission'));
}
/** @test */
#[Test]
public function it_can_create_a_role_without_duplication()
{
Artisan::call('permission:create-role', ['name' => 'new-role']);
Artisan::call('permission:create-role', ['name' => 'new-role']);
$this->assertCount(1, Role::where('name', 'new-role')->get());
$this->assertCount(0, Role::where('name', 'new-role')->first()->permissions);
}
/** @test */
#[Test]
public function it_can_create_a_permission_without_duplication()
{
Artisan::call('permission:create-permission', ['name' => 'new-permission']);
Artisan::call('permission:create-permission', ['name' => 'new-permission']);
$this->assertCount(1, Permission::where('name', 'new-permission')->get());
}
/** @test */
#[Test]
public function it_can_show_permission_tables()
{
Role::where('name', 'testRole2')->delete();
Role::create(['name' => 'testRole_2']);
Artisan::call('permission:show');
$output = Artisan::output();
$this->assertTrue(strpos($output, 'Guard: web') !== false);
$this->assertTrue(strpos($output, 'Guard: admin') !== false);
// | | testRole | testRole_2 |
// | edit-articles | · | · |
if (method_exists($this, 'assertMatchesRegularExpression')) {
$this->assertMatchesRegularExpression('/\|\s+\|\s+testRole\s+\|\s+testRole_2\s+\|/', $output);
$this->assertMatchesRegularExpression('/\|\s+edit-articles\s+\|\s+·\s+\|\s+·\s+\|/', $output);
} else { // phpUnit 9/8
$this->assertRegExp('/\|\s+\|\s+testRole\s+\|\s+testRole_2\s+\|/', $output);
$this->assertRegExp('/\|\s+edit-articles\s+\|\s+·\s+\|\s+·\s+\|/', $output);
}
Role::findByName('testRole')->givePermissionTo('edit-articles');
$this->reloadPermissions();
Artisan::call('permission:show');
$output = Artisan::output();
// | edit-articles | · | · |
if (method_exists($this, 'assertMatchesRegularExpression')) {
$this->assertMatchesRegularExpression('/\|\s+edit-articles\s+\|\s+✔\s+\|\s+·\s+\|/', $output);
} else {
$this->assertRegExp('/\|\s+edit-articles\s+\|\s+✔\s+\|\s+·\s+\|/', $output);
}
}
/** @test */
#[Test]
public function it_can_show_permissions_for_guard()
{
Artisan::call('permission:show', ['guard' => 'web']);
$output = Artisan::output();
$this->assertTrue(strpos($output, 'Guard: web') !== false);
$this->assertTrue(strpos($output, 'Guard: admin') === false);
}
/** @test */
#[Test]
public function it_can_setup_teams_upgrade()
{
config()->set('permission.teams', true);
$this->artisan('permission:setup-teams')
->expectsQuestion('Proceed with the migration creation?', 'yes')
->assertExitCode(0);
$matchingFiles = glob(database_path('migrations/*_add_teams_fields.php'));
$this->assertTrue(count($matchingFiles) > 0);
$AddTeamsFields = require $matchingFiles[count($matchingFiles) - 1];
$AddTeamsFields->up();
$AddTeamsFields->up(); // test upgrade teams migration fresh
Role::create(['name' => 'new-role', 'team_test_id' => 1]);
$role = Role::where('name', 'new-role')->first();
$this->assertNotNull($role);
$this->assertSame(1, (int) $role->team_test_id);
// remove migration
foreach ($matchingFiles as $file) {
unlink($file);
}
}
/** @test */
#[Test]
public function it_can_show_roles_by_teams()
{
config()->set('permission.teams', true);
app(\Spatie\Permission\PermissionRegistrar::class)->initializeCache();
Role::where('name', 'testRole2')->delete();
Role::create(['name' => 'testRole_2']);
Role::create(['name' => 'testRole_Team', 'team_test_id' => 1]);
Role::create(['name' => 'testRole_Team', 'team_test_id' => 2]); // same name different team
Artisan::call('permission:show');
$output = Artisan::output();
// | | Team ID: NULL | Team ID: 1 | Team ID: 2 |
// | | testRole | testRole_2 | testRole_Team | testRole_Team |
if (method_exists($this, 'assertMatchesRegularExpression')) {
$this->assertMatchesRegularExpression('/\|\s+\|\s+Team ID: NULL\s+\|\s+Team ID: 1\s+\|\s+Team ID: 2\s+\|/', $output);
$this->assertMatchesRegularExpression('/\|\s+\|\s+testRole\s+\|\s+testRole_2\s+\|\s+testRole_Team\s+\|\s+testRole_Team\s+\|/', $output);
} else { // phpUnit 9/8
$this->assertRegExp('/\|\s+\|\s+Team ID: NULL\s+\|\s+Team ID: 1\s+\|\s+Team ID: 2\s+\|/', $output);
$this->assertRegExp('/\|\s+\|\s+testRole\s+\|\s+testRole_2\s+\|\s+testRole_Team\s+\|\s+testRole_Team\s+\|/', $output);
}
}
/** @test */
#[Test]
public function it_can_respond_to_about_command_with_default()
{
if (! class_exists(InstalledVersions::class) || ! class_exists(AboutCommand::class)) {
$this->markTestSkipped();
}
if (! method_exists(AboutCommand::class, 'flushState')) {
$this->markTestSkipped();
}
app(\Spatie\Permission\PermissionRegistrar::class)->initializeCache();
Artisan::call('about');
$output = str_replace("\r\n", "\n", Artisan::output());
$pattern = '/Spatie Permissions[ .\n]*Features Enabled[ .]*Default[ .\n]*Version/';
if (method_exists($this, 'assertMatchesRegularExpression')) {
$this->assertMatchesRegularExpression($pattern, $output);
} else { // phpUnit 9/8
$this->assertRegExp($pattern, $output);
}
}
/** @test */
#[Test]
public function it_can_respond_to_about_command_with_teams()
{
if (! class_exists(InstalledVersions::class) || ! class_exists(AboutCommand::class)) {
$this->markTestSkipped();
}
if (! method_exists(AboutCommand::class, 'flushState')) {
$this->markTestSkipped();
}
app(\Spatie\Permission\PermissionRegistrar::class)->initializeCache();
config()->set('permission.teams', true);
Artisan::call('about');
$output = str_replace("\r\n", "\n", Artisan::output());
$pattern = '/Spatie Permissions[ .\n]*Features Enabled[ .]*Teams[ .\n]*Version/';
if (method_exists($this, 'assertMatchesRegularExpression')) {
$this->assertMatchesRegularExpression($pattern, $output);
} else { // phpUnit 9/8
$this->assertRegExp($pattern, $output);
}
}
/** @test */
#[Test]
public function it_can_assign_role_to_user()
{
$user = User::first();
Artisan::call('permission:assign-role', [
'name' => 'testRole',
'userId' => $user->id,
'guard' => 'web',
'userModelNamespace' => User::class,
]);
$output = Artisan::output();
$this->assertStringContainsString('Role `testRole` assigned to user ID '.$user->id.' successfully.', $output);
$this->assertCount(1, Role::where('name', 'testRole')->get());
$this->assertCount(1, $user->roles);
$this->assertTrue($user->hasRole('testRole'));
}
/** @test */
#[Test]
public function it_fails_to_assign_role_when_user_not_found()
{
Artisan::call('permission:assign-role', [
'name' => 'testRole',
'userId' => 99999,
'guard' => 'web',
'userModelNamespace' => User::class,
]);
$output = Artisan::output();
$this->assertStringContainsString('User with ID 99999 not found.', $output);
}
/** @test */
#[Test]
public function it_fails_to_assign_role_when_namespace_invalid()
{
$user = User::first();
$userModelClass = 'App\Models\NonExistentUser';
Artisan::call('permission:assign-role', [
'name' => 'testRole',
'userId' => $user->id,
'guard' => 'web',
'userModelNamespace' => $userModelClass,
]);
$output = Artisan::output();
$this->assertStringContainsString("User model class [{$userModelClass}] does not exist.", $output);
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/TeamHasPermissionsTest.php | tests/TeamHasPermissionsTest.php | <?php
namespace Spatie\Permission\Tests;
use PHPUnit\Framework\Attributes\Test;
use Spatie\Permission\Tests\TestModels\User;
class TeamHasPermissionsTest extends HasPermissionsTest
{
/** @var bool */
protected $hasTeams = true;
/** @test */
#[Test]
public function it_can_assign_same_and_different_permission_on_same_user_on_different_teams()
{
setPermissionsTeamId(1);
$this->testUser->givePermissionTo('edit-articles', 'edit-news');
setPermissionsTeamId(2);
$this->testUser->givePermissionTo('edit-articles', 'edit-blog');
setPermissionsTeamId(1);
$this->testUser->load('permissions');
$this->assertEquals(
collect(['edit-articles', 'edit-news']),
$this->testUser->getPermissionNames()->sort()->values()
);
$this->assertTrue($this->testUser->hasAllDirectPermissions(['edit-articles', 'edit-news']));
$this->assertFalse($this->testUser->hasAllDirectPermissions(['edit-articles', 'edit-blog']));
setPermissionsTeamId(2);
$this->testUser->load('permissions');
$this->assertEquals(
collect(['edit-articles', 'edit-blog']),
$this->testUser->getPermissionNames()->sort()->values()
);
$this->assertTrue($this->testUser->hasAllDirectPermissions(['edit-articles', 'edit-blog']));
$this->assertFalse($this->testUser->hasAllDirectPermissions(['edit-articles', 'edit-news']));
}
/** @test */
#[Test]
public function it_can_list_all_the_coupled_permissions_both_directly_and_via_roles_on_same_user_on_different_teams()
{
$this->testUserRole->givePermissionTo('edit-articles');
setPermissionsTeamId(1);
$this->testUser->assignRole('testRole');
$this->testUser->givePermissionTo('edit-news');
setPermissionsTeamId(2);
$this->testUser->assignRole('testRole');
$this->testUser->givePermissionTo('edit-blog');
setPermissionsTeamId(1);
$this->testUser->load('roles', 'permissions');
$this->assertEquals(
collect(['edit-articles', 'edit-news']),
$this->testUser->getAllPermissions()->pluck('name')->sort()->values()
);
setPermissionsTeamId(2);
$this->testUser->load('roles', 'permissions');
$this->assertEquals(
collect(['edit-articles', 'edit-blog']),
$this->testUser->getAllPermissions()->pluck('name')->sort()->values()
);
}
/** @test */
#[Test]
public function it_can_sync_or_remove_permission_without_detach_on_different_teams()
{
setPermissionsTeamId(1);
$this->testUser->syncPermissions('edit-articles', 'edit-news');
setPermissionsTeamId(2);
$this->testUser->syncPermissions('edit-articles', 'edit-blog');
setPermissionsTeamId(1);
$this->testUser->load('permissions');
$this->assertEquals(
collect(['edit-articles', 'edit-news']),
$this->testUser->getPermissionNames()->sort()->values()
);
$this->testUser->revokePermissionTo('edit-articles');
$this->assertEquals(
collect(['edit-news']),
$this->testUser->getPermissionNames()->sort()->values()
);
setPermissionsTeamId(2);
$this->testUser->load('permissions');
$this->assertEquals(
collect(['edit-articles', 'edit-blog']),
$this->testUser->getPermissionNames()->sort()->values()
);
}
/** @test */
#[Test]
public function it_can_scope_users_on_different_teams()
{
$user1 = User::create(['email' => 'user1@test.com']);
$user2 = User::create(['email' => 'user2@test.com']);
setPermissionsTeamId(2);
$user1->givePermissionTo(['edit-articles', 'edit-news']);
$this->testUserRole->givePermissionTo('edit-articles');
$user2->assignRole('testRole');
setPermissionsTeamId(1);
$user1->givePermissionTo(['edit-articles']);
setPermissionsTeamId(2);
$scopedUsers1Team2 = User::permission(['edit-articles', 'edit-news'])->get();
$scopedUsers2Team2 = User::permission('edit-news')->get();
$this->assertEquals(2, $scopedUsers1Team2->count());
$this->assertEquals(1, $scopedUsers2Team2->count());
setPermissionsTeamId(1);
$scopedUsers1Team1 = User::permission(['edit-articles', 'edit-news'])->get();
$scopedUsers2Team1 = User::permission('edit-news')->get();
$this->assertEquals(1, $scopedUsers1Team1->count());
$this->assertEquals(0, $scopedUsers2Team1->count());
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/RoleMiddlewareTest.php | tests/RoleMiddlewareTest.php | <?php
namespace Spatie\Permission\Tests;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;
use InvalidArgumentException;
use Laravel\Passport\Passport;
use PHPUnit\Framework\Attributes\Test;
use Spatie\Permission\Contracts\Role;
use Spatie\Permission\Exceptions\UnauthorizedException;
use Spatie\Permission\Middleware\RoleMiddleware;
use Spatie\Permission\Tests\TestModels\UserWithoutHasRoles;
class RoleMiddlewareTest extends TestCase
{
protected $roleMiddleware;
protected $usePassport = true;
protected function setUp(): void
{
parent::setUp();
$this->roleMiddleware = new RoleMiddleware;
}
/** @test */
#[Test]
public function a_guest_cannot_access_a_route_protected_by_rolemiddleware()
{
$this->assertEquals(
403,
$this->runMiddleware($this->roleMiddleware, 'testRole')
);
}
/** @test */
#[Test]
public function a_user_cannot_access_a_route_protected_by_role_middleware_of_another_guard()
{
Auth::login($this->testUser);
$this->testUser->assignRole('testRole');
$this->assertEquals(
403,
$this->runMiddleware($this->roleMiddleware, 'testAdminRole')
);
}
/** @test */
#[Test]
public function a_client_cannot_access_a_route_protected_by_role_middleware_of_another_guard(): void
{
if ($this->getLaravelVersion() < 9) {
$this->markTestSkipped('requires laravel >= 9');
}
Passport::actingAsClient($this->testClient, ['*']);
$this->testClient->assignRole('clientRole');
$this->assertEquals(
403,
$this->runMiddleware($this->roleMiddleware, 'testAdminRole', null, true)
);
}
/** @test */
#[Test]
public function a_user_can_access_a_route_protected_by_role_middleware_if_have_this_role()
{
Auth::login($this->testUser);
$this->testUser->assignRole('testRole');
$this->assertEquals(
200,
$this->runMiddleware($this->roleMiddleware, 'testRole')
);
}
/** @test */
#[Test]
public function a_client_can_access_a_route_protected_by_role_middleware_if_have_this_role(): void
{
if ($this->getLaravelVersion() < 9) {
$this->markTestSkipped('requires laravel >= 9');
}
Passport::actingAsClient($this->testClient, ['*']);
$this->testClient->assignRole('clientRole');
$this->assertEquals(
200,
$this->runMiddleware($this->roleMiddleware, 'clientRole', null, true)
);
}
/** @test */
#[Test]
public function a_user_can_access_a_route_protected_by_this_role_middleware_if_have_one_of_the_roles()
{
Auth::login($this->testUser);
$this->testUser->assignRole('testRole');
$this->assertEquals(
200,
$this->runMiddleware($this->roleMiddleware, 'testRole|testRole2')
);
$this->assertEquals(
200,
$this->runMiddleware($this->roleMiddleware, ['testRole2', 'testRole'])
);
}
/** @test */
#[Test]
public function a_client_can_access_a_route_protected_by_this_role_middleware_if_have_one_of_the_roles(): void
{
if ($this->getLaravelVersion() < 9) {
$this->markTestSkipped('requires laravel >= 9');
}
Passport::actingAsClient($this->testClient, ['*']);
$this->testClient->assignRole('clientRole');
$this->assertEquals(
200,
$this->runMiddleware($this->roleMiddleware, 'clientRole|testRole2', null, true)
);
$this->assertEquals(
200,
$this->runMiddleware($this->roleMiddleware, ['testRole2', 'clientRole'], null, true)
);
}
/** @test */
#[Test]
public function a_user_cannot_access_a_route_protected_by_the_role_middleware_if_have_not_has_roles_trait()
{
$userWithoutHasRoles = UserWithoutHasRoles::create(['email' => 'test_not_has_roles@user.com']);
Auth::login($userWithoutHasRoles);
$this->assertEquals(
403,
$this->runMiddleware($this->roleMiddleware, 'testRole')
);
}
/** @test */
#[Test]
public function a_user_cannot_access_a_route_protected_by_the_role_middleware_if_have_a_different_role()
{
Auth::login($this->testUser);
$this->testUser->assignRole(['testRole']);
$this->assertEquals(
403,
$this->runMiddleware($this->roleMiddleware, 'testRole2')
);
}
/** @test */
#[Test]
public function a_client_cannot_access_a_route_protected_by_the_role_middleware_if_have_a_different_role(): void
{
if ($this->getLaravelVersion() < 9) {
$this->markTestSkipped('requires laravel >= 9');
}
Passport::actingAsClient($this->testClient, ['*']);
$this->testClient->assignRole(['clientRole']);
$this->assertEquals(
403,
$this->runMiddleware($this->roleMiddleware, 'clientRole2', null, true)
);
}
/** @test */
#[Test]
public function a_user_cannot_access_a_route_protected_by_role_middleware_if_have_not_roles()
{
Auth::login($this->testUser);
$this->assertEquals(
403,
$this->runMiddleware($this->roleMiddleware, 'testRole|testRole2')
);
}
/** @test */
#[Test]
public function a_client_cannot_access_a_route_protected_by_role_middleware_if_have_not_roles(): void
{
if ($this->getLaravelVersion() < 9) {
$this->markTestSkipped('requires laravel >= 9');
}
Passport::actingAsClient($this->testClient, ['*']);
$this->assertEquals(
403,
$this->runMiddleware($this->roleMiddleware, 'testRole|testRole2', null, true)
);
}
/** @test */
#[Test]
public function a_user_cannot_access_a_route_protected_by_role_middleware_if_role_is_undefined()
{
Auth::login($this->testUser);
$this->assertEquals(
403,
$this->runMiddleware($this->roleMiddleware, '')
);
}
/** @test */
#[Test]
public function a_client_cannot_access_a_route_protected_by_role_middleware_if_role_is_undefined(): void
{
if ($this->getLaravelVersion() < 9) {
$this->markTestSkipped('requires laravel >= 9');
}
Passport::actingAsClient($this->testClient, ['*']);
$this->assertEquals(
403,
$this->runMiddleware($this->roleMiddleware, '', null, true)
);
}
/** @test */
#[Test]
public function the_required_roles_can_be_fetched_from_the_exception()
{
Auth::login($this->testUser);
$message = null;
$requiredRoles = [];
try {
$this->roleMiddleware->handle(new Request, function () {
return (new Response)->setContent('<html></html>');
}, 'some-role');
} catch (UnauthorizedException $e) {
$message = $e->getMessage();
$requiredRoles = $e->getRequiredRoles();
}
$this->assertEquals('User does not have the right roles.', $message);
$this->assertEquals(['some-role'], $requiredRoles);
}
/** @test */
#[Test]
public function the_required_roles_can_be_displayed_in_the_exception()
{
Auth::login($this->testUser);
Config::set(['permission.display_role_in_exception' => true]);
$message = null;
try {
$this->roleMiddleware->handle(new Request, function () {
return (new Response)->setContent('<html></html>');
}, 'some-role');
} catch (UnauthorizedException $e) {
$message = $e->getMessage();
}
$this->assertStringEndsWith('Necessary roles are some-role', $message);
}
/** @test */
#[Test]
public function use_not_existing_custom_guard_in_role()
{
$class = null;
try {
$this->roleMiddleware->handle(new Request, function () {
return (new Response)->setContent('<html></html>');
}, 'testRole', 'xxx');
} catch (InvalidArgumentException $e) {
$class = get_class($e);
}
$this->assertEquals(InvalidArgumentException::class, $class);
}
/** @test */
#[Test]
public function user_can_not_access_role_with_guard_admin_while_login_using_default_guard()
{
Auth::login($this->testUser);
$this->testUser->assignRole('testRole');
$this->assertEquals(
403,
$this->runMiddleware($this->roleMiddleware, 'testRole', 'admin')
);
}
/** @test */
#[Test]
public function client_can_not_access_role_with_guard_admin_while_login_using_default_guard(): void
{
if ($this->getLaravelVersion() < 9) {
$this->markTestSkipped('requires laravel >= 9');
}
Passport::actingAsClient($this->testClient, ['*']);
$this->testClient->assignRole('clientRole');
$this->assertEquals(
403,
$this->runMiddleware($this->roleMiddleware, 'clientRole', 'admin', true)
);
}
/** @test */
#[Test]
public function user_can_access_role_with_guard_admin_while_login_using_admin_guard()
{
Auth::guard('admin')->login($this->testAdmin);
$this->testAdmin->assignRole('testAdminRole');
$this->assertEquals(
200,
$this->runMiddleware($this->roleMiddleware, 'testAdminRole', 'admin')
);
}
/** @test */
#[Test]
public function the_middleware_can_be_created_with_static_using_method()
{
$this->assertSame(
'Spatie\Permission\Middleware\RoleMiddleware:testAdminRole',
RoleMiddleware::using('testAdminRole')
);
$this->assertEquals(
'Spatie\Permission\Middleware\RoleMiddleware:testAdminRole,my-guard',
RoleMiddleware::using('testAdminRole', 'my-guard')
);
$this->assertEquals(
'Spatie\Permission\Middleware\RoleMiddleware:testAdminRole|anotherRole',
RoleMiddleware::using(['testAdminRole', 'anotherRole'])
);
}
/**
* @test
*
* @requires PHP >= 8.1
*/
#[RequiresPhp('>= 8.1')]
#[Test]
public function the_middleware_can_handle_enum_based_roles_with_static_using_method()
{
$this->assertSame(
'Spatie\Permission\Middleware\RoleMiddleware:writer',
RoleMiddleware::using(TestModels\TestRolePermissionsEnum::WRITER)
);
$this->assertEquals(
'Spatie\Permission\Middleware\RoleMiddleware:writer,my-guard',
RoleMiddleware::using(TestModels\TestRolePermissionsEnum::WRITER, 'my-guard')
);
$this->assertEquals(
'Spatie\Permission\Middleware\RoleMiddleware:writer|editor',
RoleMiddleware::using([TestModels\TestRolePermissionsEnum::WRITER, TestModels\TestRolePermissionsEnum::EDITOR])
);
}
/**
* @test
*
* @requires PHP >= 8.1
*/
#[RequiresPhp('>= 8.1')]
#[Test]
public function the_middleware_can_handle_enum_based_roles_with_handle_method()
{
app(Role::class)->create(['name' => TestModels\TestRolePermissionsEnum::WRITER->value]);
app(Role::class)->create(['name' => TestModels\TestRolePermissionsEnum::EDITOR->value]);
Auth::login($this->testUser);
$this->testUser->assignRole(TestModels\TestRolePermissionsEnum::WRITER);
$this->assertEquals(
200,
$this->runMiddleware($this->roleMiddleware, TestModels\TestRolePermissionsEnum::WRITER)
);
$this->testUser->assignRole(TestModels\TestRolePermissionsEnum::EDITOR);
$this->assertEquals(
200,
$this->runMiddleware($this->roleMiddleware, [TestModels\TestRolePermissionsEnum::WRITER, TestModels\TestRolePermissionsEnum::EDITOR])
);
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/HasRolesWithCustomModelsTest.php | tests/HasRolesWithCustomModelsTest.php | <?php
namespace Spatie\Permission\Tests;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use PHPUnit\Framework\Attributes\Test;
use Spatie\Permission\Tests\TestModels\Admin;
use Spatie\Permission\Tests\TestModels\Role;
class HasRolesWithCustomModelsTest extends HasRolesTest
{
/** @var bool */
protected $useCustomModels = true;
/** @var int */
protected $resetDatabaseQuery = 0;
protected function getEnvironmentSetUp($app)
{
parent::getEnvironmentSetUp($app);
if ($app['config']->get('cache.default') == 'database') {
$this->resetDatabaseQuery = 1;
}
}
/** @test */
#[Test]
public function it_can_use_custom_model_role()
{
$this->assertSame(get_class($this->testUserRole), Role::class);
}
/** @test */
#[Test]
public function it_doesnt_detach_permissions_when_soft_deleting()
{
$this->testUserRole->givePermissionTo($this->testUserPermission);
DB::enableQueryLog();
$this->testUserRole->delete();
DB::disableQueryLog();
$this->assertSame(1 + $this->resetDatabaseQuery, count(DB::getQueryLog()));
$role = Role::onlyTrashed()->find($this->testUserRole->getKey());
$this->assertEquals(1, DB::table(config('permission.table_names.role_has_permissions'))->where('role_test_id', $role->getKey())->count());
}
/** @test */
#[Test]
public function it_doesnt_detach_users_when_soft_deleting()
{
$this->testUser->assignRole($this->testUserRole);
DB::enableQueryLog();
$this->testUserRole->delete();
DB::disableQueryLog();
$this->assertSame(1 + $this->resetDatabaseQuery, count(DB::getQueryLog()));
$role = Role::onlyTrashed()->find($this->testUserRole->getKey());
$this->assertEquals(1, DB::table(config('permission.table_names.model_has_roles'))->where('role_test_id', $role->getKey())->count());
}
/** @test */
#[Test]
public function it_does_detach_permissions_and_users_when_force_deleting()
{
$role_id = $this->testUserRole->getKey();
$this->testUserPermission->assignRole($role_id);
$this->testUser->assignRole($role_id);
DB::enableQueryLog();
$this->testUserRole->forceDelete();
DB::disableQueryLog();
$this->assertSame(3 + $this->resetDatabaseQuery, count(DB::getQueryLog()));
$role = Role::withTrashed()->find($role_id);
$this->assertNull($role);
$this->assertEquals(0, DB::table(config('permission.table_names.role_has_permissions'))->where('role_test_id', $role_id)->count());
$this->assertEquals(0, DB::table(config('permission.table_names.model_has_roles'))->where('role_test_id', $role_id)->count());
}
/** @test */
#[Test]
public function it_should_touch_when_assigning_new_roles()
{
Carbon::setTestNow('2021-07-19 10:13:14');
$user = Admin::create(['email' => 'user1@test.com']);
$role1 = app(Role::class)->create(['name' => 'testRoleInWebGuard', 'guard_name' => 'admin']);
$role2 = app(Role::class)->create(['name' => 'testRoleInWebGuard1', 'guard_name' => 'admin']);
$this->assertSame('2021-07-19 10:13:14', $role1->updated_at->format('Y-m-d H:i:s'));
Carbon::setTestNow('2021-07-20 19:13:14');
$user->syncRoles([$role1->getKey(), $role2->getKey()]);
$this->assertSame('2021-07-20 19:13:14', $role1->refresh()->updated_at->format('Y-m-d H:i:s'));
$this->assertSame('2021-07-20 19:13:14', $role2->refresh()->updated_at->format('Y-m-d H:i:s'));
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/WildcardRoleTest.php | tests/WildcardRoleTest.php | <?php
namespace Spatie\Permission\Tests;
use PHPUnit\Framework\Attributes\Test;
use Spatie\Permission\Models\Permission;
class WildcardRoleTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
app('config')->set('permission.enable_wildcard_permission', true);
Permission::create(['name' => 'other-permission']);
Permission::create(['name' => 'wrong-guard-permission', 'guard_name' => 'admin']);
}
/** @test */
#[Test]
public function it_can_be_given_a_permission()
{
Permission::create(['name' => 'posts.*']);
$this->testUserRole->givePermissionTo('posts.*');
$this->assertTrue($this->testUserRole->hasPermissionTo('posts.create'));
}
/** @test */
#[Test]
public function it_can_be_given_multiple_permissions_using_an_array()
{
Permission::create(['name' => 'posts.*']);
Permission::create(['name' => 'news.*']);
$this->testUserRole->givePermissionTo(['posts.*', 'news.*']);
$this->assertTrue($this->testUserRole->hasPermissionTo('posts.create'));
$this->assertTrue($this->testUserRole->hasPermissionTo('news.create'));
}
/** @test */
#[Test]
public function it_can_be_given_multiple_permissions_using_multiple_arguments()
{
Permission::create(['name' => 'posts.*']);
Permission::create(['name' => 'news.*']);
$this->testUserRole->givePermissionTo('posts.*', 'news.*');
$this->assertTrue($this->testUserRole->hasPermissionTo('posts.edit.123'));
$this->assertTrue($this->testUserRole->hasPermissionTo('news.view.1'));
}
/** @test */
#[Test]
public function it_can_be_given_a_permission_using_objects()
{
$this->testUserRole->givePermissionTo($this->testUserPermission);
$this->assertTrue($this->testUserRole->hasPermissionTo($this->testUserPermission));
}
/** @test */
#[Test]
public function it_returns_false_if_it_does_not_have_the_permission()
{
$this->assertFalse($this->testUserRole->hasPermissionTo('other-permission'));
}
/** @test */
#[Test]
public function it_returns_false_if_permission_does_not_exists()
{
$this->assertFalse($this->testUserRole->hasPermissionTo('doesnt-exist'));
}
/** @test */
#[Test]
public function it_returns_false_if_it_does_not_have_a_permission_object()
{
$permission = app(Permission::class)->findByName('other-permission');
$this->assertFalse($this->testUserRole->hasPermissionTo($permission));
}
/** @test */
#[Test]
public function it_creates_permission_object_with_findOrCreate_if_it_does_not_have_a_permission_object()
{
$permission = app(Permission::class)->findOrCreate('another-permission');
$this->assertFalse($this->testUserRole->hasPermissionTo($permission));
$this->testUserRole->givePermissionTo($permission);
$this->testUserRole = $this->testUserRole->fresh();
$this->assertTrue($this->testUserRole->hasPermissionTo('another-permission'));
}
/** @test */
#[Test]
public function it_returns_false_when_a_permission_of_the_wrong_guard_is_passed_in()
{
$permission = app(Permission::class)->findByName('wrong-guard-permission', 'admin');
$this->assertFalse($this->testUserRole->hasPermissionTo($permission));
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/BladeTest.php | tests/BladeTest.php | <?php
namespace Spatie\Permission\Tests;
use Illuminate\Support\Facades\Artisan;
use PHPUnit\Framework\Attributes\Test;
use Spatie\Permission\Contracts\Role;
class BladeTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
$roleModel = app(Role::class);
$roleModel->create(['name' => 'member']);
$roleModel->create(['name' => 'writer']);
$roleModel->create(['name' => 'intern']);
$roleModel->create(['name' => 'super-admin', 'guard_name' => 'admin']);
$roleModel->create(['name' => 'moderator', 'guard_name' => 'admin']);
}
/** @test */
#[Test]
public function all_blade_directives_will_evaluate_false_when_there_is_nobody_logged_in()
{
$permission = 'edit-articles';
$role = 'writer';
$roles = [$role];
$elserole = 'na';
$elsepermission = 'na';
$this->assertEquals('does not have permission', $this->renderView('can', ['permission' => $permission]));
$this->assertEquals('does not have permission', $this->renderView('haspermission', compact('permission', 'elsepermission')));
$this->assertEquals('does not have role', $this->renderView('role', compact('role', 'elserole')));
$this->assertEquals('does not have role', $this->renderView('hasRole', compact('role', 'elserole')));
$this->assertEquals('does not have all of the given roles', $this->renderView('hasAllRoles', compact('roles')));
$this->assertEquals('does not have all of the given roles', $this->renderView('hasAllRoles', ['roles' => implode('|', $roles)]));
$this->assertEquals('does not have any of the given roles', $this->renderView('hasAnyRole', compact('roles')));
$this->assertEquals('does not have any of the given roles', $this->renderView('hasAnyRole', ['roles' => implode('|', $roles)]));
}
/** @test */
#[Test]
public function all_blade_directives_will_evaluate_false_when_somebody_without_roles_or_permissions_is_logged_in()
{
$permission = 'edit-articles';
$role = 'writer';
$roles = 'writer';
$elserole = 'na';
$elsepermission = 'na';
auth()->setUser($this->testUser);
$this->assertEquals('does not have permission', $this->renderView('can', compact('permission')));
$this->assertEquals('does not have permission', $this->renderView('haspermission', compact('permission', 'elsepermission')));
$this->assertEquals('does not have role', $this->renderView('role', compact('role', 'elserole')));
$this->assertEquals('does not have role', $this->renderView('hasRole', compact('role', 'elserole')));
$this->assertEquals('does not have all of the given roles', $this->renderView('hasAllRoles', compact('roles')));
$this->assertEquals('does not have any of the given roles', $this->renderView('hasAnyRole', compact('roles')));
}
/** @test */
#[Test]
public function all_blade_directives_will_evaluate_false_when_somebody_with_another_guard_is_logged_in()
{
$permission = 'edit-articles';
$role = 'writer';
$roles = 'writer';
$elserole = 'na';
$elsepermission = 'na';
auth('admin')->setUser($this->testAdmin);
$this->assertEquals('does not have permission', $this->renderView('can', compact('permission')));
$this->assertEquals('does not have permission', $this->renderView('haspermission', compact('permission', 'elsepermission')));
$this->assertEquals('does not have role', $this->renderView('role', compact('role', 'elserole')));
$this->assertEquals('does not have role', $this->renderView('hasRole', compact('role', 'elserole')));
$this->assertEquals('does not have all of the given roles', $this->renderView('hasAllRoles', compact('roles')));
$this->assertEquals('does not have any of the given roles', $this->renderView('hasAnyRole', compact('roles')));
$this->assertEquals('does not have any of the given roles', $this->renderView('hasAnyRole', compact('roles')));
}
/** @test */
#[Test]
public function the_can_directive_can_accept_a_guard_name()
{
$user = $this->getWriter();
$user->givePermissionTo('edit-articles');
auth()->setUser($user);
$permission = 'edit-articles';
$guard = 'web';
$this->assertEquals('has permission', $this->renderView('can', compact('permission', 'guard')));
$guard = 'admin';
$this->assertEquals('does not have permission', $this->renderView('can', compact('permission', 'guard')));
auth()->logout();
// log in as the Admin with the permission-via-role
$this->testAdmin->givePermissionTo($this->testAdminPermission);
$user = $this->testAdmin;
auth()->setUser($user);
$permission = 'edit-articles';
$guard = 'web';
$this->assertEquals('does not have permission', $this->renderView('can', compact('permission', 'guard')));
$permission = 'admin-permission';
$guard = 'admin';
$this->assertTrue($this->testAdmin->checkPermissionTo($permission, $guard));
$this->assertEquals('has permission', $this->renderView('can', compact('permission', 'guard')));
}
/** @test */
#[Test]
public function the_can_directive_will_evaluate_true_when_the_logged_in_user_has_the_permission()
{
$user = $this->getWriter();
$user->givePermissionTo('edit-articles');
auth()->setUser($user);
$this->assertEquals('has permission', $this->renderView('can', ['permission' => 'edit-articles']));
}
/** @test */
#[Test]
public function the_haspermission_directive_will_evaluate_true_when_the_logged_in_user_has_the_permission()
{
$user = $this->getWriter();
$permission = 'edit-articles';
$user->givePermissionTo('edit-articles');
auth()->setUser($user);
$this->assertEquals('has permission', $this->renderView('haspermission', compact('permission')));
$guard = 'admin';
$elsepermission = 'na';
$this->assertEquals('does not have permission', $this->renderView('haspermission', compact('permission', 'elsepermission', 'guard')));
$this->testAdminRole->givePermissionTo($this->testAdminPermission);
$this->testAdmin->assignRole($this->testAdminRole);
auth('admin')->setUser($this->testAdmin);
$guard = 'admin';
$permission = 'admin-permission';
$this->assertEquals('has permission', $this->renderView('haspermission', compact('permission', 'guard', 'elsepermission')));
}
/** @test */
#[Test]
public function the_role_directive_will_evaluate_true_when_the_logged_in_user_has_the_role()
{
auth()->setUser($this->getWriter());
$this->assertEquals('has role', $this->renderView('role', ['role' => 'writer', 'elserole' => 'na']));
}
/** @test */
#[Test]
public function the_elserole_directive_will_evaluate_true_when_the_logged_in_user_has_the_role()
{
auth()->setUser($this->getMember());
$this->assertEquals('has else role', $this->renderView('role', ['role' => 'writer', 'elserole' => 'member']));
}
/** @test */
#[Test]
public function the_role_directive_will_evaluate_true_when_the_logged_in_user_has_the_role_for_the_given_guard()
{
auth('admin')->setUser($this->getSuperAdmin());
$this->assertEquals('has role for guard', $this->renderView('guardRole', ['role' => 'super-admin', 'guard' => 'admin']));
}
/** @test */
#[Test]
public function the_hasrole_directive_will_evaluate_true_when_the_logged_in_user_has_the_role()
{
auth()->setUser($this->getWriter());
$this->assertEquals('has role', $this->renderView('hasRole', ['role' => 'writer']));
}
/** @test */
#[Test]
public function the_hasrole_directive_will_evaluate_true_when_the_logged_in_user_has_the_role_for_the_given_guard()
{
auth('admin')->setUser($this->getSuperAdmin());
$this->assertEquals('has role', $this->renderView('guardHasRole', ['role' => 'super-admin', 'guard' => 'admin']));
}
/** @test */
#[Test]
public function the_unlessrole_directive_will_evaluate_true_when_the_logged_in_user_does_not_have_the_role()
{
auth()->setUser($this->getWriter());
$this->assertEquals('does not have role', $this->renderView('unlessrole', ['role' => 'another']));
}
/** @test */
#[Test]
public function the_unlessrole_directive_will_evaluate_true_when_the_logged_in_user_does_not_have_the_role_for_the_given_guard()
{
auth('admin')->setUser($this->getSuperAdmin());
$this->assertEquals('does not have role', $this->renderView('guardunlessrole', ['role' => 'another', 'guard' => 'admin']));
$this->assertEquals('does not have role', $this->renderView('guardunlessrole', ['role' => 'super-admin', 'guard' => 'web']));
}
/** @test */
#[Test]
public function the_hasanyrole_directive_will_evaluate_false_when_the_logged_in_user_does_not_have_any_of_the_required_roles()
{
$roles = ['writer', 'intern'];
auth()->setUser($this->getMember());
$this->assertEquals('does not have any of the given roles', $this->renderView('hasAnyRole', compact('roles')));
$this->assertEquals('does not have any of the given roles', $this->renderView('hasAnyRole', ['roles' => implode('|', $roles)]));
}
/** @test */
#[Test]
public function the_hasanyrole_directive_will_evaluate_true_when_the_logged_in_user_does_have_some_of_the_required_roles()
{
$roles = ['member', 'writer', 'intern'];
auth()->setUser($this->getMember());
$this->assertEquals('does have some of the roles', $this->renderView('hasAnyRole', compact('roles')));
$this->assertEquals('does have some of the roles', $this->renderView('hasAnyRole', ['roles' => implode('|', $roles)]));
}
/** @test */
#[Test]
public function the_hasanyrole_directive_will_evaluate_true_when_the_logged_in_user_does_have_some_of_the_required_roles_for_the_given_guard()
{
$roles = ['super-admin', 'moderator'];
$guard = 'admin';
auth('admin')->setUser($this->getSuperAdmin());
$this->assertEquals('does have some of the roles', $this->renderView('guardHasAnyRole', compact('roles', 'guard')));
}
/** @test */
#[Test]
public function the_hasanyrole_directive_will_evaluate_true_when_the_logged_in_user_does_have_some_of_the_required_roles_in_pipe()
{
$guard = 'admin';
auth('admin')->setUser($this->getSuperAdmin());
$this->assertEquals('does have some of the roles', $this->renderView('guardHasAnyRolePipe', compact('guard')));
}
/** @test */
#[Test]
public function the_hasanyrole_directive_will_evaluate_false_when_the_logged_in_user_doesnt_have_some_of_the_required_roles_in_pipe()
{
$guard = '';
auth('admin')->setUser($this->getMember());
$this->assertEquals('does not have any of the given roles', $this->renderView('guardHasAnyRolePipe', compact('guard')));
}
/** @test */
#[Test]
public function the_hasallroles_directive_will_evaluate_false_when_the_logged_in_user_does_not_have_all_required_roles()
{
$roles = ['member', 'writer'];
auth()->setUser($this->getMember());
$this->assertEquals('does not have all of the given roles', $this->renderView('hasAllRoles', compact('roles')));
$this->assertEquals('does not have all of the given roles', $this->renderView('hasAllRoles', ['roles' => implode('|', $roles)]));
}
/** @test */
#[Test]
public function the_hasallroles_directive_will_evaluate_true_when_the_logged_in_user_does_have_all_required_roles()
{
$roles = ['member', 'writer'];
$user = $this->getMember();
$user->assignRole('writer');
auth()->setUser($user);
$this->assertEquals('does have all of the given roles', $this->renderView('hasAllRoles', compact('roles')));
$this->assertEquals('does have all of the given roles', $this->renderView('hasAllRoles', ['roles' => implode('|', $roles)]));
}
/** @test */
#[Test]
public function the_hasallroles_directive_will_evaluate_true_when_the_logged_in_user_does_have_all_required_roles_for_the_given_guard()
{
$roles = ['super-admin', 'moderator'];
$guard = 'admin';
$admin = $this->getSuperAdmin();
$admin->assignRole('moderator');
auth('admin')->setUser($admin);
$this->assertEquals('does have all of the given roles', $this->renderView('guardHasAllRoles', compact('roles', 'guard')));
}
/** @test */
#[Test]
public function the_hasallroles_directive_will_evaluate_true_when_the_logged_in_user_does_have_all_required_roles_in_pipe()
{
$guard = 'admin';
$admin = $this->getSuperAdmin();
$admin->assignRole('moderator');
auth('admin')->setUser($admin);
$this->assertEquals('does have all of the given roles', $this->renderView('guardHasAllRolesPipe', compact('guard')));
}
/** @test */
#[Test]
public function the_hasallroles_directive_will_evaluate_false_when_the_logged_in_user_doesnt_have_all_required_roles_in_pipe()
{
$guard = '';
$user = $this->getMember();
$user->assignRole('writer');
auth()->setUser($user);
$this->assertEquals('does not have all of the given roles', $this->renderView('guardHasAllRolesPipe', compact('guard')));
}
/** @test */
#[Test]
public function the_hasallroles_directive_will_evaluate_true_when_the_logged_in_user_does_have_all_required_roles_in_array()
{
$guard = 'admin';
$admin = $this->getSuperAdmin();
$admin->assignRole('moderator');
auth('admin')->setUser($admin);
$this->assertEquals('does have all of the given roles', $this->renderView('guardHasAllRolesArray', compact('guard')));
}
/** @test */
#[Test]
public function the_hasallroles_directive_will_evaluate_false_when_the_logged_in_user_doesnt_have_all_required_roles_in_array()
{
$guard = '';
$user = $this->getMember();
$user->assignRole('writer');
auth()->setUser($user);
$this->assertEquals('does not have all of the given roles', $this->renderView('guardHasAllRolesArray', compact('guard')));
}
protected function getWriter()
{
$this->testUser->assignRole('writer');
return $this->testUser;
}
protected function getMember()
{
$this->testUser->assignRole('member');
return $this->testUser;
}
protected function getSuperAdmin()
{
$this->testAdmin->assignRole('super-admin');
return $this->testAdmin;
}
protected function renderView($view, $parameters)
{
Artisan::call('view:clear');
if (is_string($view)) {
$view = view($view)->with($parameters);
}
return trim((string) ($view));
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/TeamHasRolesTest.php | tests/TeamHasRolesTest.php | <?php
namespace Spatie\Permission\Tests;
use PHPUnit\Framework\Attributes\Test;
use Spatie\Permission\Contracts\Role;
use Spatie\Permission\Tests\TestModels\User;
class TeamHasRolesTest extends HasRolesTest
{
/** @var bool */
protected $hasTeams = true;
/** @test */
#[Test]
public function it_deletes_pivot_table_entries_when_deleting_models()
{
$user1 = User::create(['email' => 'user2@test.com']);
$user2 = User::create(['email' => 'user2@test.com']);
setPermissionsTeamId(1);
$user1->assignRole('testRole');
$user1->givePermissionTo('edit-articles');
$user2->assignRole('testRole');
$user2->givePermissionTo('edit-articles');
setPermissionsTeamId(2);
$user1->givePermissionTo('edit-news');
$this->assertDatabaseHas('model_has_permissions', [config('permission.column_names.model_morph_key') => $user1->id]);
$this->assertDatabaseHas('model_has_roles', [config('permission.column_names.model_morph_key') => $user1->id]);
$user1->delete();
setPermissionsTeamId(1);
$this->assertDatabaseMissing('model_has_permissions', [config('permission.column_names.model_morph_key') => $user1->id]);
$this->assertDatabaseMissing('model_has_roles', [config('permission.column_names.model_morph_key') => $user1->id]);
$this->assertDatabaseHas('model_has_permissions', [config('permission.column_names.model_morph_key') => $user2->id]);
$this->assertDatabaseHas('model_has_roles', [config('permission.column_names.model_morph_key') => $user2->id]);
}
/** @test */
#[Test]
public function it_can_assign_same_and_different_roles_on_same_user_different_teams()
{
app(Role::class)->create(['name' => 'testRole3']); // team_test_id = 1 by main class
app(Role::class)->create(['name' => 'testRole3', 'team_test_id' => 2]);
app(Role::class)->create(['name' => 'testRole4', 'team_test_id' => null]); // global role
$testRole3Team1 = app(Role::class)->where(['name' => 'testRole3', 'team_test_id' => 1])->first();
$testRole3Team2 = app(Role::class)->where(['name' => 'testRole3', 'team_test_id' => 2])->first();
$testRole4NoTeam = app(Role::class)->where(['name' => 'testRole4', 'team_test_id' => null])->first();
$this->assertNotNull($testRole3Team1);
$this->assertNotNull($testRole4NoTeam);
setPermissionsTeamId(1);
$this->testUser->assignRole('testRole', 'testRole2');
// explicit load of roles to assert no mismatch
// when same role assigned in diff teams
// while old team's roles are loaded
$this->testUser->load('roles');
setPermissionsTeamId(2);
$this->testUser->assignRole('testRole', 'testRole3');
setPermissionsTeamId(1);
$this->testUser->load('roles');
$this->assertEquals(
collect(['testRole', 'testRole2']),
$this->testUser->getRoleNames()->sort()->values()
);
$this->assertTrue($this->testUser->hasExactRoles(['testRole', 'testRole2']));
$this->testUser->assignRole('testRole3', 'testRole4');
$this->assertTrue($this->testUser->hasExactRoles(['testRole', 'testRole2', 'testRole3', 'testRole4']));
$this->assertTrue($this->testUser->hasRole($testRole3Team1)); // testRole3 team=1
$this->assertTrue($this->testUser->hasRole($testRole4NoTeam)); // global role team=null
setPermissionsTeamId(2);
$this->testUser->load('roles');
$this->assertEquals(
collect(['testRole', 'testRole3']),
$this->testUser->getRoleNames()->sort()->values()
);
$this->assertTrue($this->testUser->hasExactRoles(['testRole', 'testRole3']));
$this->assertTrue($this->testUser->hasRole($testRole3Team2)); // testRole3 team=2
$this->testUser->assignRole('testRole4');
$this->assertTrue($this->testUser->hasExactRoles(['testRole', 'testRole3', 'testRole4']));
$this->assertTrue($this->testUser->hasRole($testRole4NoTeam)); // global role team=null
}
/** @test */
#[Test]
public function it_can_sync_or_remove_roles_without_detach_on_different_teams()
{
app(Role::class)->create(['name' => 'testRole3', 'team_test_id' => 2]);
setPermissionsTeamId(1);
$this->testUser->syncRoles('testRole', 'testRole2');
setPermissionsTeamId(2);
$this->testUser->syncRoles('testRole', 'testRole3');
setPermissionsTeamId(1);
$this->testUser->load('roles');
$this->assertEquals(
collect(['testRole', 'testRole2']),
$this->testUser->getRoleNames()->sort()->values()
);
$this->testUser->removeRole('testRole');
$this->assertEquals(
collect(['testRole2']),
$this->testUser->getRoleNames()->sort()->values()
);
setPermissionsTeamId(2);
$this->testUser->load('roles');
$this->assertEquals(
collect(['testRole', 'testRole3']),
$this->testUser->getRoleNames()->sort()->values()
);
}
/** @test */
#[Test]
public function it_can_scope_users_on_different_teams()
{
User::all()->each(fn ($item) => $item->delete());
$user1 = User::create(['email' => 'user1@test.com']);
$user2 = User::create(['email' => 'user2@test.com']);
setPermissionsTeamId(2);
$user1->assignRole($this->testUserRole);
$user2->assignRole('testRole2');
setPermissionsTeamId(1);
$user1->assignRole('testRole');
setPermissionsTeamId(2);
$scopedUsers1Team1 = User::role($this->testUserRole)->get();
$scopedUsers2Team1 = User::role(['testRole', 'testRole2'])->get();
$scopedUsers3Team1 = User::withoutRole('testRole')->get();
$this->assertEquals(1, $scopedUsers1Team1->count());
$this->assertEquals(2, $scopedUsers2Team1->count());
$this->assertEquals(1, $scopedUsers3Team1->count());
setPermissionsTeamId(1);
$scopedUsers1Team2 = User::role($this->testUserRole)->get();
$scopedUsers2Team2 = User::role('testRole2')->get();
$scopedUsers3Team2 = User::withoutRole('testRole')->get();
$this->assertEquals(1, $scopedUsers1Team2->count());
$this->assertEquals(0, $scopedUsers2Team2->count());
$this->assertEquals(1, $scopedUsers3Team2->count());
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/PermissionTest.php | tests/PermissionTest.php | <?php
namespace Spatie\Permission\Tests;
use PHPUnit\Framework\Attributes\Test;
use Spatie\Permission\Contracts\Permission;
use Spatie\Permission\Exceptions\PermissionAlreadyExists;
use Spatie\Permission\Tests\TestModels\User;
class PermissionTest extends TestCase
{
/** @test */
#[Test]
public function it_get_user_models_using_with()
{
$this->testUser->givePermissionTo($this->testUserPermission);
$permission = app(Permission::class)::with('users')
->where($this->testUserPermission->getKeyName(), $this->testUserPermission->getKey())
->first();
$this->assertEquals($permission->getKey(), $this->testUserPermission->getKey());
$this->assertCount(1, $permission->users);
$this->assertEquals($permission->users[0]->id, $this->testUser->id);
}
/** @test */
#[Test]
public function it_throws_an_exception_when_the_permission_already_exists()
{
$this->expectException(PermissionAlreadyExists::class);
app(Permission::class)->create(['name' => 'test-permission']);
app(Permission::class)->create(['name' => 'test-permission']);
}
/** @test */
#[Test]
public function it_belongs_to_a_guard()
{
$permission = app(Permission::class)->create(['name' => 'can-edit', 'guard_name' => 'admin']);
$this->assertEquals('admin', $permission->guard_name);
}
/** @test */
#[Test]
public function it_belongs_to_the_default_guard_by_default()
{
$this->assertEquals(
$this->app['config']->get('auth.defaults.guard'),
$this->testUserPermission->guard_name
);
}
/** @test */
#[Test]
public function it_has_user_models_of_the_right_class()
{
$this->testAdmin->givePermissionTo($this->testAdminPermission);
$this->testUser->givePermissionTo($this->testUserPermission);
$this->assertCount(1, $this->testUserPermission->users);
$this->assertTrue($this->testUserPermission->users->first()->is($this->testUser));
$this->assertInstanceOf(User::class, $this->testUserPermission->users->first());
}
/** @test */
#[Test]
public function it_is_retrievable_by_id()
{
$permission_by_id = app(Permission::class)->findById($this->testUserPermission->id);
$this->assertEquals($this->testUserPermission->id, $permission_by_id->id);
}
/** @test */
#[Test]
public function it_can_delete_hydrated_permissions()
{
$this->reloadPermissions();
$permission = app(Permission::class)->findByName($this->testUserPermission->name);
$permission->delete();
$this->assertCount(0, app(Permission::class)->where($this->testUserPermission->getKeyName(), $this->testUserPermission->getKey())->get());
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/PermissionMiddlewareTest.php | tests/PermissionMiddlewareTest.php | <?php
namespace Spatie\Permission\Tests;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Gate;
use InvalidArgumentException;
use Laravel\Passport\Passport;
use PHPUnit\Framework\Attributes\Test;
use Spatie\Permission\Contracts\Permission;
use Spatie\Permission\Exceptions\UnauthorizedException;
use Spatie\Permission\Middleware\PermissionMiddleware;
use Spatie\Permission\Tests\TestModels\UserWithoutHasRoles;
class PermissionMiddlewareTest extends TestCase
{
protected $permissionMiddleware;
protected $usePassport = true;
protected function setUp(): void
{
parent::setUp();
$this->permissionMiddleware = new PermissionMiddleware;
}
/** @test */
#[Test]
public function a_guest_cannot_access_a_route_protected_by_the_permission_middleware()
{
$this->assertEquals(
403,
$this->runMiddleware($this->permissionMiddleware, 'edit-articles')
);
}
/** @test */
#[Test]
public function a_user_cannot_access_a_route_protected_by_the_permission_middleware_of_a_different_guard()
{
// These permissions are created fresh here in reverse order of guard being applied, so they are not "found first" in the db lookup when matching
app(Permission::class)->create(['name' => 'admin-permission2', 'guard_name' => 'web']);
$p1 = app(Permission::class)->create(['name' => 'admin-permission2', 'guard_name' => 'admin']);
app(Permission::class)->create(['name' => 'edit-articles2', 'guard_name' => 'admin']);
$p2 = app(Permission::class)->create(['name' => 'edit-articles2', 'guard_name' => 'web']);
Auth::guard('admin')->login($this->testAdmin);
$this->testAdmin->givePermissionTo($p1);
$this->assertEquals(
200,
$this->runMiddleware($this->permissionMiddleware, 'admin-permission2', 'admin')
);
$this->assertEquals(
403,
$this->runMiddleware($this->permissionMiddleware, 'edit-articles2', 'admin')
);
Auth::login($this->testUser);
$this->testUser->givePermissionTo($p2);
$this->assertEquals(
200,
$this->runMiddleware($this->permissionMiddleware, 'edit-articles2', 'web')
);
$this->assertEquals(
403,
$this->runMiddleware($this->permissionMiddleware, 'admin-permission2', 'web')
);
}
/** @test */
#[Test]
public function a_client_cannot_access_a_route_protected_by_the_permission_middleware_of_a_different_guard(): void
{
if ($this->getLaravelVersion() < 9) {
$this->markTestSkipped('requires laravel >= 9');
}
// These permissions are created fresh here in reverse order of guard being applied, so they are not "found first" in the db lookup when matching
app(Permission::class)->create(['name' => 'admin-permission2', 'guard_name' => 'web']);
$p1 = app(Permission::class)->create(['name' => 'admin-permission2', 'guard_name' => 'api']);
Passport::actingAsClient($this->testClient, ['*']);
$this->testClient->givePermissionTo($p1);
$this->assertEquals(
200,
$this->runMiddleware($this->permissionMiddleware, 'admin-permission2', 'api', true)
);
$this->assertEquals(
403,
$this->runMiddleware($this->permissionMiddleware, 'edit-articles2', 'web', true)
);
}
/** @test */
#[Test]
public function a_super_admin_user_can_access_a_route_protected_by_permission_middleware()
{
Auth::login($this->testUser);
Gate::before(function ($user, $ability) {
return $user->getKey() === $this->testUser->getKey() ? true : null;
});
$this->assertEquals(
200,
$this->runMiddleware($this->permissionMiddleware, 'edit-articles')
);
}
/** @test */
#[Test]
public function a_user_can_access_a_route_protected_by_permission_middleware_if_have_this_permission()
{
Auth::login($this->testUser);
$this->testUser->givePermissionTo('edit-articles');
$this->assertEquals(
200,
$this->runMiddleware($this->permissionMiddleware, 'edit-articles')
);
}
/** @test */
#[Test]
public function a_client_can_access_a_route_protected_by_permission_middleware_if_have_this_permission(): void
{
if ($this->getLaravelVersion() < 9) {
$this->markTestSkipped('requires laravel >= 9');
}
Passport::actingAsClient($this->testClient, ['*'], 'api');
$this->testClient->givePermissionTo('edit-posts');
$this->assertEquals(
200,
$this->runMiddleware($this->permissionMiddleware, 'edit-posts', null, true)
);
}
/** @test */
#[Test]
public function a_user_can_access_a_route_protected_by_this_permission_middleware_if_have_one_of_the_permissions()
{
Auth::login($this->testUser);
$this->testUser->givePermissionTo('edit-articles');
$this->assertEquals(
200,
$this->runMiddleware($this->permissionMiddleware, 'edit-news|edit-articles')
);
$this->assertEquals(
200,
$this->runMiddleware($this->permissionMiddleware, ['edit-news', 'edit-articles'])
);
}
/** @test */
#[Test]
public function a_client_can_access_a_route_protected_by_this_permission_middleware_if_have_one_of_the_permissions(): void
{
if ($this->getLaravelVersion() < 9) {
$this->markTestSkipped('requires laravel >= 9');
}
Passport::actingAsClient($this->testClient, ['*']);
$this->testClient->givePermissionTo('edit-posts');
$this->assertEquals(
200,
$this->runMiddleware($this->permissionMiddleware, 'edit-news|edit-posts', null, true)
);
$this->assertEquals(
200,
$this->runMiddleware($this->permissionMiddleware, ['edit-news', 'edit-posts'], null, true)
);
}
/** @test */
#[Test]
public function a_user_cannot_access_a_route_protected_by_the_permission_middleware_if_have_not_has_roles_trait()
{
$userWithoutHasRoles = UserWithoutHasRoles::create(['email' => 'test_not_has_roles@user.com']);
Auth::login($userWithoutHasRoles);
$this->assertEquals(
403,
$this->runMiddleware($this->permissionMiddleware, 'edit-news')
);
}
/** @test */
#[Test]
public function a_user_cannot_access_a_route_protected_by_the_permission_middleware_if_have_a_different_permission()
{
Auth::login($this->testUser);
$this->testUser->givePermissionTo('edit-articles');
$this->assertEquals(
403,
$this->runMiddleware($this->permissionMiddleware, 'edit-news')
);
}
/** @test */
#[Test]
public function a_client_cannot_access_a_route_protected_by_the_permission_middleware_if_have_a_different_permission(): void
{
if ($this->getLaravelVersion() < 9) {
$this->markTestSkipped('requires laravel >= 9');
}
Passport::actingAsClient($this->testClient, ['*']);
$this->testClient->givePermissionTo('edit-posts');
$this->assertEquals(
403,
$this->runMiddleware($this->permissionMiddleware, 'edit-news', null, true)
);
}
/** @test */
#[Test]
public function a_user_cannot_access_a_route_protected_by_permission_middleware_if_have_not_permissions()
{
Auth::login($this->testUser);
$this->assertEquals(
403,
$this->runMiddleware($this->permissionMiddleware, 'edit-articles|edit-news')
);
}
/** @test */
#[Test]
public function a_client_cannot_access_a_route_protected_by_permission_middleware_if_have_not_permissions(): void
{
if ($this->getLaravelVersion() < 9) {
$this->markTestSkipped('requires laravel >= 9');
}
Passport::actingAsClient($this->testClient, ['*']);
$this->assertEquals(
403,
$this->runMiddleware($this->permissionMiddleware, 'edit-articles|edit-posts', null, true)
);
}
/** @test */
#[Test]
public function a_user_can_access_a_route_protected_by_permission_middleware_if_has_permission_via_role()
{
Auth::login($this->testUser);
$this->assertEquals(
403,
$this->runMiddleware($this->permissionMiddleware, 'edit-articles')
);
$this->testUserRole->givePermissionTo('edit-articles');
$this->testUser->assignRole('testRole');
$this->assertEquals(
200,
$this->runMiddleware($this->permissionMiddleware, 'edit-articles')
);
}
/** @test */
#[Test]
public function a_client_can_access_a_route_protected_by_permission_middleware_if_has_permission_via_role(): void
{
if ($this->getLaravelVersion() < 9) {
$this->markTestSkipped('requires laravel >= 9');
}
Passport::actingAsClient($this->testClient, ['*']);
$this->assertEquals(
403,
$this->runMiddleware($this->permissionMiddleware, 'edit-articles', null, true)
);
$this->testClientRole->givePermissionTo('edit-posts');
$this->testClient->assignRole('clientRole');
$this->assertEquals(
200,
$this->runMiddleware($this->permissionMiddleware, 'edit-posts', null, true)
);
}
/** @test */
#[Test]
public function the_required_permissions_can_be_fetched_from_the_exception()
{
Auth::login($this->testUser);
$message = null;
$requiredPermissions = [];
try {
$this->permissionMiddleware->handle(new Request, function () {
return (new Response)->setContent('<html></html>');
}, 'some-permission');
} catch (UnauthorizedException $e) {
$message = $e->getMessage();
$requiredPermissions = $e->getRequiredPermissions();
}
$this->assertEquals('User does not have the right permissions.', $message);
$this->assertEquals(['some-permission'], $requiredPermissions);
}
/** @test */
#[Test]
public function the_required_permissions_can_be_displayed_in_the_exception()
{
Auth::login($this->testUser);
Config::set(['permission.display_permission_in_exception' => true]);
$message = null;
try {
$this->permissionMiddleware->handle(new Request, function () {
return (new Response)->setContent('<html></html>');
}, 'some-permission');
} catch (UnauthorizedException $e) {
$message = $e->getMessage();
}
$this->assertStringEndsWith('Necessary permissions are some-permission', $message);
}
/** @test */
#[Test]
public function use_not_existing_custom_guard_in_permission()
{
$class = null;
try {
$this->permissionMiddleware->handle(new Request, function () {
return (new Response)->setContent('<html></html>');
}, 'edit-articles', 'xxx');
} catch (InvalidArgumentException $e) {
$class = get_class($e);
}
$this->assertEquals(InvalidArgumentException::class, $class);
}
/** @test */
#[Test]
public function user_can_not_access_permission_with_guard_admin_while_login_using_default_guard()
{
Auth::login($this->testUser);
$this->testUser->givePermissionTo('edit-articles');
$this->assertEquals(
403,
$this->runMiddleware($this->permissionMiddleware, 'edit-articles', 'admin')
);
}
/** @test */
#[Test]
public function client_can_not_access_permission_with_guard_admin_while_login_using_default_guard(): void
{
if ($this->getLaravelVersion() < 9) {
$this->markTestSkipped('requires laravel >= 9');
}
Passport::actingAsClient($this->testClient, ['*']);
$this->testClient->givePermissionTo('edit-posts');
$this->assertEquals(
403,
$this->runMiddleware($this->permissionMiddleware, 'edit-posts', 'admin', true)
);
}
/** @test */
#[Test]
public function user_can_access_permission_with_guard_admin_while_login_using_admin_guard()
{
Auth::guard('admin')->login($this->testAdmin);
$this->testAdmin->givePermissionTo('admin-permission');
$this->assertEquals(
200,
$this->runMiddleware($this->permissionMiddleware, 'admin-permission', 'admin')
);
}
/** @test */
#[Test]
public function the_middleware_can_be_created_with_static_using_method()
{
$this->assertSame(
'Spatie\Permission\Middleware\PermissionMiddleware:edit-articles',
PermissionMiddleware::using('edit-articles')
);
$this->assertEquals(
'Spatie\Permission\Middleware\PermissionMiddleware:edit-articles,my-guard',
PermissionMiddleware::using('edit-articles', 'my-guard')
);
$this->assertEquals(
'Spatie\Permission\Middleware\PermissionMiddleware:edit-articles|edit-news',
PermissionMiddleware::using(['edit-articles', 'edit-news'])
);
}
/**
* @test
*
* @requires PHP >= 8.1
*/
#[RequiresPhp('>= 8.1')]
#[Test]
public function the_middleware_can_handle_enum_based_permissions_with_static_using_method()
{
$this->assertSame(
'Spatie\Permission\Middleware\PermissionMiddleware:view articles',
PermissionMiddleware::using(TestModels\TestRolePermissionsEnum::VIEWARTICLES)
);
$this->assertEquals(
'Spatie\Permission\Middleware\PermissionMiddleware:view articles,my-guard',
PermissionMiddleware::using(TestModels\TestRolePermissionsEnum::VIEWARTICLES, 'my-guard')
);
$this->assertEquals(
'Spatie\Permission\Middleware\PermissionMiddleware:view articles|edit articles',
PermissionMiddleware::using([TestModels\TestRolePermissionsEnum::VIEWARTICLES, TestModels\TestRolePermissionsEnum::EDITARTICLES])
);
}
/**
* @test
*
* @requires PHP >= 8.1
*/
#[RequiresPhp('>= 8.1')]
#[Test]
public function the_middleware_can_handle_enum_based_permissions_with_handle_method()
{
app(Permission::class)->create(['name' => TestModels\TestRolePermissionsEnum::VIEWARTICLES->value]);
app(Permission::class)->create(['name' => TestModels\TestRolePermissionsEnum::EDITARTICLES->value]);
Auth::login($this->testUser);
$this->testUser->givePermissionTo(TestModels\TestRolePermissionsEnum::VIEWARTICLES);
$this->assertEquals(
200,
$this->runMiddleware($this->permissionMiddleware, TestModels\TestRolePermissionsEnum::VIEWARTICLES)
);
$this->testUser->givePermissionTo(TestModels\TestRolePermissionsEnum::EDITARTICLES);
$this->assertEquals(
200,
$this->runMiddleware($this->permissionMiddleware, [TestModels\TestRolePermissionsEnum::VIEWARTICLES, TestModels\TestRolePermissionsEnum::EDITARTICLES])
);
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/TestModels/WildcardPermission.php | tests/TestModels/WildcardPermission.php | <?php
namespace Spatie\Permission\Tests\TestModels;
use Spatie\Permission\WildcardPermission as BaseWildcardPermission;
class WildcardPermission extends BaseWildcardPermission
{
/** @var string */
public const WILDCARD_TOKEN = '@';
/** @var non-empty-string */
public const PART_DELIMITER = ':';
/** @var non-empty-string */
public const SUBPART_DELIMITER = ';';
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/TestModels/Client.php | tests/TestModels/Client.php | <?php
namespace Spatie\Permission\Tests\TestModels;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Laravel\Passport\Client as BaseClient;
use Spatie\Permission\Traits\HasRoles;
class Client extends BaseClient implements AuthorizableContract
{
use Authorizable;
use HasRoles;
/**
* Required to make clear that the client requires the api guard
*/
protected string $guard_name = 'api';
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/TestModels/RuntimeRole.php | tests/TestModels/RuntimeRole.php | <?php
namespace Spatie\Permission\Tests\TestModels;
class RuntimeRole extends \Spatie\Permission\Models\Role
{
protected $visible = [
'id',
'name',
];
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/TestModels/TestRolePermissionsEnum.php | tests/TestModels/TestRolePermissionsEnum.php | <?php
namespace Spatie\Permission\Tests\TestModels;
use Illuminate\Support\Str;
/**
* Enum example
*
* Syntax is `case NAME = VALUE`
* The NAME will be used in your application code
* The VALUE will be the role/permission name checked-against in the database.
*
* NOTE: When creating roles/permissions, you must manually convert name to value when passing the role/permission name to Eloquent.
* eg: use MyEnum::NAME->value when specifying the role/permission name
*
* In your application code, when checking for authorization, you can use MyEnum::NAME in most cases.
* You can always manually fallback to MyEnum::NAME->value when using features that aren't aware of Enum support.
*
* TestRolePermissionsEnum::USERMANAGER->name = 'USERMANAGER'
* TestRolePermissionsEnum::USERMANAGER->value = 'User Manager' <-- This is the role-name checked by this package
* TestRolePermissionsEnum::USERMANAGER->label() = 'Manage Users'
*/
enum TestRolePermissionsEnum: string
{
// case NAME = 'value';
// case NAMEINAPP = 'name-in-database';
case WRITER = 'writer';
case EDITOR = 'editor';
case USERMANAGER = 'user-manager';
case ADMIN = 'administrator';
case CASTED_ENUM_1 = 'casted_enum-1';
case CASTED_ENUM_2 = 'casted_enum-2';
case VIEWARTICLES = 'view articles';
case EDITARTICLES = 'edit articles';
case WildcardArticlesCreator = 'articles.edit,view,create';
case WildcardNewsEverything = 'news.*';
case WildcardPostsEverything = 'posts.*';
case WildcardPostsCreate = 'posts.create';
case WildcardArticlesView = 'articles.view';
case WildcardProjectsView = 'projects.view';
// extra helper to allow for greater customization of displayed values, without disclosing the name/value data directly
public function label(): string
{
return match ($this) {
self::WRITER => 'Writers',
self::EDITOR => 'Editors',
self::USERMANAGER => 'User Managers',
self::ADMIN => 'Admins',
self::VIEWARTICLES => 'View Articles',
self::EDITARTICLES => 'Edit Articles',
default => Str::words($this->value),
};
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/TestModels/User.php | tests/TestModels/User.php | <?php
namespace Spatie\Permission\Tests\TestModels;
use Spatie\Permission\Traits\HasRoles;
class User extends UserWithoutHasRoles
{
use HasRoles;
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/TestModels/Admin.php | tests/TestModels/Admin.php | <?php
namespace Spatie\Permission\Tests\TestModels;
class Admin extends User
{
protected $table = 'admins';
protected $touches = ['roles', 'permissions'];
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/TestModels/UserWithoutHasRoles.php | tests/TestModels/UserWithoutHasRoles.php | <?php
namespace Spatie\Permission\Tests\TestModels;
use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\Access\Authorizable;
class UserWithoutHasRoles extends Model implements AuthenticatableContract, AuthorizableContract
{
use Authenticatable;
use Authorizable;
protected $fillable = ['email'];
public $timestamps = false;
protected $table = 'users';
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/TestModels/Manager.php | tests/TestModels/Manager.php | <?php
namespace Spatie\Permission\Tests\TestModels;
class Manager extends User
{
// this function is added here to support the unit tests verifying it works
// When present, it takes precedence over the $guard_name property.
public function guardName(): string
{
return 'jwt';
}
// intentionally different property value for the sake of unit tests
protected string $guard_name = 'web';
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/TestModels/Role.php | tests/TestModels/Role.php | <?php
namespace Spatie\Permission\Tests\TestModels;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;
class Role extends \Spatie\Permission\Models\Role
{
use SoftDeletes;
protected $primaryKey = 'role_test_id';
protected $visible = [
'role_test_id',
'name',
];
const HIERARCHY_TABLE = 'roles_hierarchy';
public function getNameAttribute(): \BackedEnum|string
{
$name = $this->attributes['name'];
if (str_contains($name, 'casted_enum')) {
return TestRolePermissionsEnum::from($name);
}
return $name;
}
public function parents(): BelongsToMany
{
return $this->belongsToMany(
static::class,
static::HIERARCHY_TABLE,
'child_id',
'parent_id');
}
public function children(): BelongsToMany
{
return $this->belongsToMany(
static::class,
static::HIERARCHY_TABLE,
'parent_id',
'child_id');
}
protected static function boot()
{
parent::boot();
static::creating(static function ($model) {
if (empty($model->{$model->getKeyName()})) {
$model->{$model->getKeyName()} = Str::uuid()->toString();
}
});
}
public function getIncrementing(): bool
{
return false;
}
public function getKeyType(): string
{
return 'string';
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/TestModels/SoftDeletingUser.php | tests/TestModels/SoftDeletingUser.php | <?php
namespace Spatie\Permission\Tests\TestModels;
use Illuminate\Database\Eloquent\SoftDeletes;
class SoftDeletingUser extends User
{
use SoftDeletes;
protected string $guard_name = 'web';
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/TestModels/Permission.php | tests/TestModels/Permission.php | <?php
namespace Spatie\Permission\Tests\TestModels;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;
class Permission extends \Spatie\Permission\Models\Permission
{
use SoftDeletes;
protected $primaryKey = 'permission_test_id';
protected $visible = [
'permission_test_id',
'name',
];
protected static function boot()
{
parent::boot();
static::creating(static function ($model) {
if (empty($model->{$model->getKeyName()})) {
$model->{$model->getKeyName()} = Str::uuid()->toString();
}
});
}
public function getIncrementing(): bool
{
return false;
}
public function getKeyType(): string
{
return 'string';
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/TestModels/Content.php | tests/TestModels/Content.php | <?php
namespace Spatie\Permission\Tests\TestModels;
use Illuminate\Database\Eloquent\Model;
class Content extends Model
{
protected $guarded = [];
protected $table = 'content';
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/resources/views/hasRole.blade.php | tests/resources/views/hasRole.blade.php | @hasrole($role)
has role
@else
does not have role
@endhasrole
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/resources/views/guardHasRole.blade.php | tests/resources/views/guardHasRole.blade.php | @hasrole($role, $guard)
has role
@else
does not have role
@endhasrole
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/resources/views/hasAllRoles.blade.php | tests/resources/views/hasAllRoles.blade.php | @hasallroles($roles)
does have all of the given roles
@else
does not have all of the given roles
@endhasallroles
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/resources/views/unlessrole.blade.php | tests/resources/views/unlessrole.blade.php | @unlessrole($role)
does not have role
@else
has role
@endunlessrole
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/resources/views/guardHasAllRoles.blade.php | tests/resources/views/guardHasAllRoles.blade.php | @hasallroles($roles, $guard)
does have all of the given roles
@else
does not have all of the given roles
@endhasallroles
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/resources/views/guardHasAllRolesPipe.blade.php | tests/resources/views/guardHasAllRolesPipe.blade.php | @hasallroles("super-admin|moderator", $guard)
does have all of the given roles
@else
does not have all of the given roles
@endhasallroles
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/resources/views/guardRole.blade.php | tests/resources/views/guardRole.blade.php | @role($role, $guard)
has role for guard
@else
does not have role for guard
@endrole
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/resources/views/guardHasAnyRolePipe.blade.php | tests/resources/views/guardHasAnyRolePipe.blade.php | @hasanyrole("super-admin|moderator", $guard)
does have some of the roles
@else
does not have any of the given roles
@endhasanyrole
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/resources/views/hasAnyRole.blade.php | tests/resources/views/hasAnyRole.blade.php | @hasanyrole($roles)
does have some of the roles
@else
does not have any of the given roles
@endhasanyrole
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/resources/views/guardHasAllRolesArray.blade.php | tests/resources/views/guardHasAllRolesArray.blade.php | @hasallroles(['super-admin', 'moderator'], $guard)
does have all of the given roles
@else
does not have all of the given roles
@endhasallroles
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/resources/views/role.blade.php | tests/resources/views/role.blade.php | @role($role)
has role
@elserole($elserole)
has else role
@else
does not have role
@endrole
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/resources/views/guardHasAnyRole.blade.php | tests/resources/views/guardHasAnyRole.blade.php | @hasanyrole($roles, $guard)
does have some of the roles
@else
does not have any of the given roles
@endhasanyrole
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/resources/views/guardunlessrole.blade.php | tests/resources/views/guardunlessrole.blade.php | @unlessrole($role, $guard)
does not have role
@else
has role
@endunlessrole
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/resources/views/can.blade.php | tests/resources/views/can.blade.php | @can($permission, $guard ?? null)
has permission
@else
does not have permission
@endcan
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/tests/resources/views/haspermission.blade.php | tests/resources/views/haspermission.blade.php | @haspermission($permission, $guard ?? null)
has permission
@elsehaspermission($elsepermission, $guard ?? null)
has else permission
@else
does not have permission
@endhaspermission
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/config/permission.php | config/permission.php | <?php
return [
'models' => [
/*
* When using the "HasPermissions" trait from this package, we need to know which
* Eloquent model should be used to retrieve your permissions. Of course, it
* is often just the "Permission" model but you may use whatever you like.
*
* The model you want to use as a Permission model needs to implement the
* `Spatie\Permission\Contracts\Permission` contract.
*/
'permission' => Spatie\Permission\Models\Permission::class,
/*
* When using the "HasRoles" trait from this package, we need to know which
* Eloquent model should be used to retrieve your roles. Of course, it
* is often just the "Role" model but you may use whatever you like.
*
* The model you want to use as a Role model needs to implement the
* `Spatie\Permission\Contracts\Role` contract.
*/
'role' => Spatie\Permission\Models\Role::class,
],
'table_names' => [
/*
* When using the "HasRoles" trait from this package, we need to know which
* table should be used to retrieve your roles. We have chosen a basic
* default value but you may easily change it to any table you like.
*/
'roles' => 'roles',
/*
* When using the "HasPermissions" trait from this package, we need to know which
* table should be used to retrieve your permissions. We have chosen a basic
* default value but you may easily change it to any table you like.
*/
'permissions' => 'permissions',
/*
* When using the "HasPermissions" trait from this package, we need to know which
* table should be used to retrieve your models permissions. We have chosen a
* basic default value but you may easily change it to any table you like.
*/
'model_has_permissions' => 'model_has_permissions',
/*
* When using the "HasRoles" trait from this package, we need to know which
* table should be used to retrieve your models roles. We have chosen a
* basic default value but you may easily change it to any table you like.
*/
'model_has_roles' => 'model_has_roles',
/*
* When using the "HasRoles" trait from this package, we need to know which
* table should be used to retrieve your roles permissions. We have chosen a
* basic default value but you may easily change it to any table you like.
*/
'role_has_permissions' => 'role_has_permissions',
],
'column_names' => [
/*
* Change this if you want to name the related pivots other than defaults
*/
'role_pivot_key' => null, // default 'role_id',
'permission_pivot_key' => null, // default 'permission_id',
/*
* Change this if you want to name the related model primary key other than
* `model_id`.
*
* For example, this would be nice if your primary keys are all UUIDs. In
* that case, name this `model_uuid`.
*/
'model_morph_key' => 'model_id',
/*
* Change this if you want to use the teams feature and your related model's
* foreign key is other than `team_id`.
*/
'team_foreign_key' => 'team_id',
],
/*
* When set to true, the method for checking permissions will be registered on the gate.
* Set this to false if you want to implement custom logic for checking permissions.
*/
'register_permission_check_method' => true,
/*
* When set to true, Laravel\Octane\Events\OperationTerminated event listener will be registered
* this will refresh permissions on every TickTerminated, TaskTerminated and RequestTerminated
* NOTE: This should not be needed in most cases, but an Octane/Vapor combination benefited from it.
*/
'register_octane_reset_listener' => false,
/*
* Events will fire when a role or permission is assigned/unassigned:
* \Spatie\Permission\Events\RoleAttached
* \Spatie\Permission\Events\RoleDetached
* \Spatie\Permission\Events\PermissionAttached
* \Spatie\Permission\Events\PermissionDetached
*
* To enable, set to true, and then create listeners to watch these events.
*/
'events_enabled' => false,
/*
* Teams Feature.
* When set to true the package implements teams using the 'team_foreign_key'.
* If you want the migrations to register the 'team_foreign_key', you must
* set this to true before doing the migration.
* If you already did the migration then you must make a new migration to also
* add 'team_foreign_key' to 'roles', 'model_has_roles', and 'model_has_permissions'
* (view the latest version of this package's migration file)
*/
'teams' => false,
/*
* The class to use to resolve the permissions team id
*/
'team_resolver' => \Spatie\Permission\DefaultTeamResolver::class,
/*
* Passport Client Credentials Grant
* When set to true the package will use Passports Client to check permissions
*/
'use_passport_client_credentials' => false,
/*
* When set to true, the required permission names are added to exception messages.
* This could be considered an information leak in some contexts, so the default
* setting is false here for optimum safety.
*/
'display_permission_in_exception' => false,
/*
* When set to true, the required role names are added to exception messages.
* This could be considered an information leak in some contexts, so the default
* setting is false here for optimum safety.
*/
'display_role_in_exception' => false,
/*
* By default wildcard permission lookups are disabled.
* See documentation to understand supported syntax.
*/
'enable_wildcard_permission' => false,
/*
* The class to use for interpreting wildcard permissions.
* If you need to modify delimiters, override the class and specify its name here.
*/
// 'wildcard_permission' => Spatie\Permission\WildcardPermission::class,
/* Cache-specific settings */
'cache' => [
/*
* By default all permissions are cached for 24 hours to speed up performance.
* When permissions or roles are updated the cache is flushed automatically.
*/
'expiration_time' => \DateInterval::createFromDateString('24 hours'),
/*
* The cache key used to store all permissions.
*/
'key' => 'spatie.permission.cache',
/*
* You may optionally indicate a specific cache driver to use for permission and
* role caching using any of the `store` drivers listed in the cache.php config
* file. Using 'default' here means to use the `default` set in cache.php.
*/
'store' => 'default',
],
];
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
blueimp/jQuery-File-Upload | https://github.com/blueimp/jQuery-File-Upload/blob/0e92a4d4613d4ed5231ee0d8513519f2e04f99ba/server/php/UploadHandler.php | server/php/UploadHandler.php | <?php
/*
* jQuery File Upload Plugin PHP Class
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2010, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* https://opensource.org/licenses/MIT
*/
class UploadHandler
{
protected $options;
// PHP File Upload error message codes:
// https://php.net/manual/en/features.file-upload.errors.php
protected $error_messages = array(
1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
3 => 'The uploaded file was only partially uploaded',
4 => 'No file was uploaded',
6 => 'Missing a temporary folder',
7 => 'Failed to write file to disk',
8 => 'A PHP extension stopped the file upload',
'post_max_size' => 'The uploaded file exceeds the post_max_size directive in php.ini',
'max_file_size' => 'File is too big',
'min_file_size' => 'File is too small',
'accept_file_types' => 'Filetype not allowed',
'max_number_of_files' => 'Maximum number of files exceeded',
'invalid_file_type' => 'Invalid file type',
'max_width' => 'Image exceeds maximum width',
'min_width' => 'Image requires a minimum width',
'max_height' => 'Image exceeds maximum height',
'min_height' => 'Image requires a minimum height',
'abort' => 'File upload aborted',
'image_resize' => 'Failed to resize image'
);
const IMAGETYPE_GIF = 'image/gif';
const IMAGETYPE_JPEG = 'image/jpeg';
const IMAGETYPE_PNG = 'image/png';
protected $image_objects = array();
protected $response = array();
public function __construct($options = null, $initialize = true, $error_messages = null) {
$this->options = array(
'script_url' => $this->get_full_url().'/'.$this->basename($this->get_server_var('SCRIPT_NAME')),
'upload_dir' => dirname($this->get_server_var('SCRIPT_FILENAME')).'/files/',
'upload_url' => $this->get_full_url().'/files/',
'input_stream' => 'php://input',
'user_dirs' => false,
'mkdir_mode' => 0755,
'param_name' => 'files',
// Set the following option to 'POST', if your server does not support
// DELETE requests. This is a parameter sent to the client:
'delete_type' => 'DELETE',
'access_control_allow_origin' => '*',
'access_control_allow_credentials' => false,
'access_control_allow_methods' => array(
'OPTIONS',
'HEAD',
'GET',
'POST',
'PUT',
'PATCH',
'DELETE'
),
'access_control_allow_headers' => array(
'Content-Type',
'Content-Range',
'Content-Disposition'
),
// By default, allow redirects to the referer protocol+host:
'redirect_allow_target' => '/^'.preg_quote(
parse_url($this->get_server_var('HTTP_REFERER'), PHP_URL_SCHEME)
.'://'
.parse_url($this->get_server_var('HTTP_REFERER'), PHP_URL_HOST)
.'/', // Trailing slash to not match subdomains by mistake
'/' // preg_quote delimiter param
).'/',
// Enable to provide file downloads via GET requests to the PHP script:
// 1. Set to 1 to download files via readfile method through PHP
// 2. Set to 2 to send a X-Sendfile header for lighttpd/Apache
// 3. Set to 3 to send a X-Accel-Redirect header for nginx
// If set to 2 or 3, adjust the upload_url option to the base path of
// the redirect parameter, e.g. '/files/'.
'download_via_php' => false,
// Read files in chunks to avoid memory limits when download_via_php
// is enabled, set to 0 to disable chunked reading of files:
'readfile_chunk_size' => 10 * 1024 * 1024, // 10 MiB
// Defines which files can be displayed inline when downloaded:
'inline_file_types' => '/\.(gif|jpe?g|png)$/i',
// Defines which files (based on their names) are accepted for upload.
// By default, only allows file uploads with image file extensions.
// Only change this setting after making sure that any allowed file
// types cannot be executed by the webserver in the files directory,
// e.g. PHP scripts, nor executed by the browser when downloaded,
// e.g. HTML files with embedded JavaScript code.
// Please also read the SECURITY.md document in this repository.
'accept_file_types' => '/\.(gif|jpe?g|png)$/i',
// Replaces dots in filenames with the given string.
// Can be disabled by setting it to false or an empty string.
// Note that this is a security feature for servers that support
// multiple file extensions, e.g. the Apache AddHandler Directive:
// https://httpd.apache.org/docs/current/mod/mod_mime.html#addhandler
// Before disabling it, make sure that files uploaded with multiple
// extensions cannot be executed by the webserver, e.g.
// "example.php.png" with embedded PHP code, nor executed by the
// browser when downloaded, e.g. "example.html.gif" with embedded
// JavaScript code.
'replace_dots_in_filenames' => '-',
// The php.ini settings upload_max_filesize and post_max_size
// take precedence over the following max_file_size setting:
'max_file_size' => null,
'min_file_size' => 1,
// The maximum number of files for the upload directory:
'max_number_of_files' => null,
// Reads first file bytes to identify and correct file extensions:
'correct_image_extensions' => false,
// Image resolution restrictions:
'max_width' => null,
'max_height' => null,
'min_width' => 1,
'min_height' => 1,
// Set the following option to false to enable resumable uploads:
'discard_aborted_uploads' => true,
// Set to 0 to use the GD library to scale and orient images,
// set to 1 to use imagick (if installed, falls back to GD),
// set to 2 to use the ImageMagick convert binary directly:
'image_library' => 1,
// Uncomment the following to define an array of resource limits
// for imagick:
/*
'imagick_resource_limits' => array(
imagick::RESOURCETYPE_MAP => 32,
imagick::RESOURCETYPE_MEMORY => 32
),
*/
// Command or path for to the ImageMagick convert binary:
'convert_bin' => 'convert',
// Uncomment the following to add parameters in front of each
// ImageMagick convert call (the limit constraints seem only
// to have an effect if put in front):
/*
'convert_params' => '-limit memory 32MiB -limit map 32MiB',
*/
// Command or path for to the ImageMagick identify binary:
'identify_bin' => 'identify',
'image_versions' => array(
// The empty image version key defines options for the original image.
// Keep in mind: these image manipulations are inherited by all other image versions from this point onwards.
// Also note that the property 'no_cache' is not inherited, since it's not a manipulation.
'' => array(
// Automatically rotate images based on EXIF meta data:
'auto_orient' => true
),
// You can add arrays to generate different versions.
// The name of the key is the name of the version (example: 'medium').
// the array contains the options to apply.
/*
'medium' => array(
'max_width' => 800,
'max_height' => 600
),
*/
'thumbnail' => array(
// Uncomment the following to use a defined directory for the thumbnails
// instead of a subdirectory based on the version identifier.
// Make sure that this directory doesn't allow execution of files if you
// don't pose any restrictions on the type of uploaded files, e.g. by
// copying the .htaccess file from the files directory for Apache:
//'upload_dir' => dirname($this->get_server_var('SCRIPT_FILENAME')).'/thumb/',
//'upload_url' => $this->get_full_url().'/thumb/',
// Uncomment the following to force the max
// dimensions and e.g. create square thumbnails:
// 'auto_orient' => true,
// 'crop' => true,
// 'jpeg_quality' => 70,
// 'no_cache' => true, (there's a caching option, but this remembers thumbnail sizes from a previous action!)
// 'strip' => true, (this strips EXIF tags, such as geolocation)
'max_width' => 80, // either specify width, or set to 0. Then width is automatically adjusted - keeping aspect ratio to a specified max_height.
'max_height' => 80 // either specify height, or set to 0. Then height is automatically adjusted - keeping aspect ratio to a specified max_width.
)
),
'print_response' => true
);
if ($options) {
$this->options = $options + $this->options;
}
if ($error_messages) {
$this->error_messages = $error_messages + $this->error_messages;
}
if ($initialize) {
$this->initialize();
}
}
protected function initialize() {
switch ($this->get_server_var('REQUEST_METHOD')) {
case 'OPTIONS':
case 'HEAD':
$this->head();
break;
case 'GET':
$this->get($this->options['print_response']);
break;
case 'PATCH':
case 'PUT':
case 'POST':
$this->post($this->options['print_response']);
break;
case 'DELETE':
$this->delete($this->options['print_response']);
break;
default:
$this->header('HTTP/1.1 405 Method Not Allowed');
}
}
protected function get_full_url() {
$https = !empty($_SERVER['HTTPS']) && strcasecmp($_SERVER['HTTPS'], 'on') === 0 ||
!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
strcasecmp($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') === 0;
return
($https ? 'https://' : 'http://').
(!empty($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'].'@' : '').
(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME'].
($https && $_SERVER['SERVER_PORT'] === 443 ||
$_SERVER['SERVER_PORT'] === 80 ? '' : ':'.$_SERVER['SERVER_PORT']))).
substr($_SERVER['SCRIPT_NAME'],0, strrpos($_SERVER['SCRIPT_NAME'], '/'));
}
protected function get_user_id() {
@session_start();
return session_id();
}
protected function get_user_path() {
if ($this->options['user_dirs']) {
return $this->get_user_id().'/';
}
return '';
}
protected function get_upload_path($file_name = null, $version = null) {
$file_name = $file_name ? $file_name : '';
if (empty($version)) {
$version_path = '';
} else {
$version_dir = @$this->options['image_versions'][$version]['upload_dir'];
if ($version_dir) {
return $version_dir.$this->get_user_path().$file_name;
}
$version_path = $version.'/';
}
return $this->options['upload_dir'].$this->get_user_path()
.$version_path.$file_name;
}
protected function get_query_separator($url) {
return strpos($url, '?') === false ? '?' : '&';
}
protected function get_download_url($file_name, $version = null, $direct = false) {
if (!$direct && $this->options['download_via_php']) {
$url = $this->options['script_url']
.$this->get_query_separator($this->options['script_url'])
.$this->get_singular_param_name()
.'='.rawurlencode($file_name);
if ($version) {
$url .= '&version='.rawurlencode($version);
}
return $url.'&download=1';
}
if (empty($version)) {
$version_path = '';
} else {
$version_url = @$this->options['image_versions'][$version]['upload_url'];
if ($version_url) {
return $version_url.$this->get_user_path().rawurlencode($file_name);
}
$version_path = rawurlencode($version).'/';
}
return $this->options['upload_url'].$this->get_user_path()
.$version_path.rawurlencode($file_name);
}
protected function set_additional_file_properties($file) {
$file->deleteUrl = $this->options['script_url']
.$this->get_query_separator($this->options['script_url'])
.$this->get_singular_param_name()
.'='.rawurlencode($file->name);
$file->deleteType = $this->options['delete_type'];
if ($file->deleteType !== 'DELETE') {
$file->deleteUrl .= '&_method=DELETE';
}
if ($this->options['access_control_allow_credentials']) {
$file->deleteWithCredentials = true;
}
}
// Fix for overflowing signed 32 bit integers,
// works for sizes up to 2^32-1 bytes (4 GiB - 1):
protected function fix_integer_overflow($size) {
if ($size < 0) {
$size += 2.0 * (PHP_INT_MAX + 1);
}
return $size;
}
protected function get_file_size($file_path, $clear_stat_cache = false) {
if ($clear_stat_cache) {
if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
clearstatcache(true, $file_path);
} else {
clearstatcache();
}
}
return $this->fix_integer_overflow(filesize($file_path));
}
protected function is_valid_file_object($file_name) {
$file_path = $this->get_upload_path($file_name);
if (strlen($file_name) > 0 && $file_name[0] !== '.' && is_file($file_path)) {
return true;
}
return false;
}
protected function get_file_object($file_name) {
if ($this->is_valid_file_object($file_name)) {
$file = new \stdClass();
$file->name = $file_name;
$file->size = $this->get_file_size(
$this->get_upload_path($file_name)
);
$file->url = $this->get_download_url($file->name);
foreach ($this->options['image_versions'] as $version => $options) {
if (!empty($version)) {
if (is_file($this->get_upload_path($file_name, $version))) {
$file->{$version.'Url'} = $this->get_download_url(
$file->name,
$version
);
}
}
}
$this->set_additional_file_properties($file);
return $file;
}
return null;
}
protected function get_file_objects($iteration_method = 'get_file_object') {
$upload_dir = $this->get_upload_path();
if (!is_dir($upload_dir)) {
return array();
}
return array_values(array_filter(array_map(
array($this, $iteration_method),
scandir($upload_dir)
)));
}
protected function count_file_objects() {
return count($this->get_file_objects('is_valid_file_object'));
}
protected function get_error_message($error) {
return isset($this->error_messages[$error]) ?
$this->error_messages[$error] : $error;
}
public function get_config_bytes($val) {
$val = trim($val);
$last = strtolower($val[strlen($val)-1]);
if (is_numeric($val)) {
$val = (int)$val;
} else {
$val = (int)substr($val, 0, -1);
}
switch ($last) {
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
case 'k':
$val *= 1024;
}
return $this->fix_integer_overflow($val);
}
protected function validate_image_file($uploaded_file, $file, $error, $index) {
if ($this->imagetype($uploaded_file) !== $this->get_file_type($file->name)) {
$file->error = $this->get_error_message('invalid_file_type');
return false;
}
$max_width = @$this->options['max_width'];
$max_height = @$this->options['max_height'];
$min_width = @$this->options['min_width'];
$min_height = @$this->options['min_height'];
if ($max_width || $max_height || $min_width || $min_height) {
list($img_width, $img_height) = $this->get_image_size($uploaded_file);
// If we are auto rotating the image by default, do the checks on
// the correct orientation
if (
@$this->options['image_versions']['']['auto_orient'] &&
function_exists('exif_read_data') &&
($exif = @exif_read_data($uploaded_file)) &&
(((int) @$exif['Orientation']) >= 5)
) {
$tmp = $img_width;
$img_width = $img_height;
$img_height = $tmp;
unset($tmp);
}
if (!empty($img_width) && !empty($img_height)) {
if ($max_width && $img_width > $max_width) {
$file->error = $this->get_error_message('max_width');
return false;
}
if ($max_height && $img_height > $max_height) {
$file->error = $this->get_error_message('max_height');
return false;
}
if ($min_width && $img_width < $min_width) {
$file->error = $this->get_error_message('min_width');
return false;
}
if ($min_height && $img_height < $min_height) {
$file->error = $this->get_error_message('min_height');
return false;
}
}
}
return true;
}
protected function validate($uploaded_file, $file, $error, $index, $content_range) {
if ($error) {
$file->error = $this->get_error_message($error);
return false;
}
$content_length = $this->fix_integer_overflow(
(int)$this->get_server_var('CONTENT_LENGTH')
);
$post_max_size = $this->get_config_bytes(ini_get('post_max_size'));
if ($post_max_size && ($content_length > $post_max_size)) {
$file->error = $this->get_error_message('post_max_size');
return false;
}
if (!preg_match($this->options['accept_file_types'], $file->name)) {
$file->error = $this->get_error_message('accept_file_types');
return false;
}
if ($uploaded_file && is_uploaded_file($uploaded_file)) {
$file_size = $this->get_file_size($uploaded_file);
} else {
$file_size = $content_length;
}
if ($this->options['max_file_size'] && (
$file_size > $this->options['max_file_size'] ||
$file->size > $this->options['max_file_size'])
) {
$file->error = $this->get_error_message('max_file_size');
return false;
}
if ($this->options['min_file_size'] &&
$file_size < $this->options['min_file_size']) {
$file->error = $this->get_error_message('min_file_size');
return false;
}
if (is_int($this->options['max_number_of_files']) &&
($this->count_file_objects() >= $this->options['max_number_of_files']) &&
// Ignore additional chunks of existing files:
!is_file($this->get_upload_path($file->name))) {
$file->error = $this->get_error_message('max_number_of_files');
return false;
}
if (!$content_range && $this->has_image_file_extension($file->name)) {
return $this->validate_image_file($uploaded_file, $file, $error, $index);
}
return true;
}
protected function upcount_name_callback($matches) {
$index = isset($matches[1]) ? ((int)$matches[1]) + 1 : 1;
$ext = isset($matches[2]) ? $matches[2] : '';
return ' ('.$index.')'.$ext;
}
protected function upcount_name($name) {
return preg_replace_callback(
'/(?:(?: \(([\d]+)\))?(\.[^.]+))?$/',
array($this, 'upcount_name_callback'),
$name,
1
);
}
protected function get_unique_filename($file_path, $name, $size, $type, $error,
$index, $content_range) {
while(is_dir($this->get_upload_path($name))) {
$name = $this->upcount_name($name);
}
// Keep an existing filename if this is part of a chunked upload:
$uploaded_bytes = $this->fix_integer_overflow((int)@$content_range[1]);
while (is_file($this->get_upload_path($name))) {
if ($uploaded_bytes === $this->get_file_size(
$this->get_upload_path($name))) {
break;
}
$name = $this->upcount_name($name);
}
return $name;
}
protected function get_valid_image_extensions($file_path) {
switch ($this->imagetype($file_path)) {
case self::IMAGETYPE_JPEG:
return array('jpg', 'jpeg');
case self::IMAGETYPE_PNG:
return array('png');
case self::IMAGETYPE_GIF:
return array('gif');
}
}
protected function fix_file_extension($file_path, $name, $size, $type, $error,
$index, $content_range) {
// Add missing file extension for known image types:
if (strpos($name, '.') === false &&
preg_match('/^image\/(gif|jpe?g|png)/', $type, $matches)) {
$name .= '.'.$matches[1];
}
if ($this->options['correct_image_extensions']) {
$extensions = $this->get_valid_image_extensions($file_path);
// Adjust incorrect image file extensions:
if (!empty($extensions)) {
$parts = explode('.', $name);
$extIndex = count($parts) - 1;
$ext = strtolower(@$parts[$extIndex]);
if (!in_array($ext, $extensions)) {
$parts[$extIndex] = $extensions[0];
$name = implode('.', $parts);
}
}
}
return $name;
}
protected function trim_file_name($file_path, $name, $size, $type, $error,
$index, $content_range) {
// Remove path information and dots around the filename, to prevent uploading
// into different directories or replacing hidden system files.
// Also remove control characters and spaces (\x00..\x20) around the filename:
$name = trim($this->basename(stripslashes($name)), ".\x00..\x20");
// Replace dots in filenames to avoid security issues with servers
// that interpret multiple file extensions, e.g. "example.php.png":
$replacement = $this->options['replace_dots_in_filenames'];
if (!empty($replacement)) {
$parts = explode('.', $name);
if (count($parts) > 2) {
$ext = array_pop($parts);
$name = implode($replacement, $parts).'.'.$ext;
}
}
// Use a timestamp for empty filenames:
if (!$name) {
$name = str_replace('.', '-', microtime(true));
}
return $name;
}
protected function get_file_name($file_path, $name, $size, $type, $error,
$index, $content_range) {
$name = $this->trim_file_name($file_path, $name, $size, $type, $error,
$index, $content_range);
return $this->get_unique_filename(
$file_path,
$this->fix_file_extension($file_path, $name, $size, $type, $error,
$index, $content_range),
$size,
$type,
$error,
$index,
$content_range
);
}
protected function get_scaled_image_file_paths($file_name, $version) {
$file_path = $this->get_upload_path($file_name);
if (!empty($version)) {
$version_dir = $this->get_upload_path(null, $version);
if (!is_dir($version_dir)) {
mkdir($version_dir, $this->options['mkdir_mode'], true);
}
$new_file_path = $version_dir.'/'.$file_name;
} else {
$new_file_path = $file_path;
}
return array($file_path, $new_file_path);
}
protected function gd_get_image_object($file_path, $func, $no_cache = false) {
if (empty($this->image_objects[$file_path]) || $no_cache) {
$this->gd_destroy_image_object($file_path);
$this->image_objects[$file_path] = $func($file_path);
}
return $this->image_objects[$file_path];
}
protected function gd_set_image_object($file_path, $image) {
$this->gd_destroy_image_object($file_path);
$this->image_objects[$file_path] = $image;
}
protected function gd_destroy_image_object($file_path) {
$image = (isset($this->image_objects[$file_path])) ? $this->image_objects[$file_path] : null ;
return $image && imagedestroy($image);
}
protected function gd_imageflip($image, $mode) {
if (function_exists('imageflip')) {
return imageflip($image, $mode);
}
$new_width = $src_width = imagesx($image);
$new_height = $src_height = imagesy($image);
$new_img = imagecreatetruecolor($new_width, $new_height);
$src_x = 0;
$src_y = 0;
switch ($mode) {
case '1': // flip on the horizontal axis
$src_y = $new_height - 1;
$src_height = -$new_height;
break;
case '2': // flip on the vertical axis
$src_x = $new_width - 1;
$src_width = -$new_width;
break;
case '3': // flip on both axes
$src_y = $new_height - 1;
$src_height = -$new_height;
$src_x = $new_width - 1;
$src_width = -$new_width;
break;
default:
return $image;
}
imagecopyresampled(
$new_img,
$image,
0,
0,
$src_x,
$src_y,
$new_width,
$new_height,
$src_width,
$src_height
);
return $new_img;
}
protected function gd_orient_image($file_path, $src_img) {
if (!function_exists('exif_read_data')) {
return false;
}
$exif = @exif_read_data($file_path);
if ($exif === false) {
return false;
}
$orientation = (int)@$exif['Orientation'];
if ($orientation < 2 || $orientation > 8) {
return false;
}
switch ($orientation) {
case 2:
$new_img = $this->gd_imageflip(
$src_img,
defined('IMG_FLIP_VERTICAL') ? IMG_FLIP_VERTICAL : 2
);
break;
case 3:
$new_img = imagerotate($src_img, 180, 0);
break;
case 4:
$new_img = $this->gd_imageflip(
$src_img,
defined('IMG_FLIP_HORIZONTAL') ? IMG_FLIP_HORIZONTAL : 1
);
break;
case 5:
$tmp_img = $this->gd_imageflip(
$src_img,
defined('IMG_FLIP_HORIZONTAL') ? IMG_FLIP_HORIZONTAL : 1
);
$new_img = imagerotate($tmp_img, 270, 0);
imagedestroy($tmp_img);
break;
case 6:
$new_img = imagerotate($src_img, 270, 0);
break;
case 7:
$tmp_img = $this->gd_imageflip(
$src_img,
defined('IMG_FLIP_VERTICAL') ? IMG_FLIP_VERTICAL : 2
);
$new_img = imagerotate($tmp_img, 270, 0);
imagedestroy($tmp_img);
break;
case 8:
$new_img = imagerotate($src_img, 90, 0);
break;
default:
return false;
}
$this->gd_set_image_object($file_path, $new_img);
return true;
}
protected function gd_create_scaled_image($file_name, $version, $options) {
if (!function_exists('imagecreatetruecolor')) {
error_log('Function not found: imagecreatetruecolor');
return false;
}
list($file_path, $new_file_path) =
$this->get_scaled_image_file_paths($file_name, $version);
$type = strtolower(substr(strrchr($file_name, '.'), 1));
switch ($type) {
case 'jpg':
case 'jpeg':
$src_func = 'imagecreatefromjpeg';
$write_func = 'imagejpeg';
$image_quality = isset($options['jpeg_quality']) ?
$options['jpeg_quality'] : 75;
break;
case 'gif':
$src_func = 'imagecreatefromgif';
$write_func = 'imagegif';
$image_quality = null;
break;
case 'png':
$src_func = 'imagecreatefrompng';
$write_func = 'imagepng';
$image_quality = isset($options['png_quality']) ?
$options['png_quality'] : 9;
break;
default:
return false;
}
$src_img = $this->gd_get_image_object(
$file_path,
$src_func,
!empty($options['no_cache'])
);
$image_oriented = false;
if (!empty($options['auto_orient']) && $this->gd_orient_image(
$file_path,
$src_img
)) {
$image_oriented = true;
$src_img = $this->gd_get_image_object(
$file_path,
$src_func
);
}
$max_width = $img_width = imagesx($src_img);
$max_height = $img_height = imagesy($src_img);
if (!empty($options['max_width'])) {
$max_width = $options['max_width'];
}
if (!empty($options['max_height'])) {
$max_height = $options['max_height'];
}
$scale = min(
$max_width / $img_width,
$max_height / $img_height
);
if ($scale >= 1) {
if ($image_oriented) {
return $write_func($src_img, $new_file_path, $image_quality);
}
if ($file_path !== $new_file_path) {
return copy($file_path, $new_file_path);
}
return true;
}
if (empty($options['crop'])) {
$new_width = $img_width * $scale;
$new_height = $img_height * $scale;
$dst_x = 0;
$dst_y = 0;
$new_img = imagecreatetruecolor($new_width, $new_height);
} else {
if (($img_width / $img_height) >= ($max_width / $max_height)) {
$new_width = $img_width / ($img_height / $max_height);
| php | MIT | 0e92a4d4613d4ed5231ee0d8513519f2e04f99ba | 2026-01-04T15:02:34.243643Z | true |
blueimp/jQuery-File-Upload | https://github.com/blueimp/jQuery-File-Upload/blob/0e92a4d4613d4ed5231ee0d8513519f2e04f99ba/server/php/index.php | server/php/index.php | <?php
/*
* jQuery File Upload Plugin PHP Example
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2010, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* https://opensource.org/licenses/MIT
*/
error_reporting(E_ALL | E_STRICT);
require('UploadHandler.php');
$upload_handler = new UploadHandler();
| php | MIT | 0e92a4d4613d4ed5231ee0d8513519f2e04f99ba | 2026-01-04T15:02:34.243643Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/src/Whoops/Run.php | src/Whoops/Run.php | <?php
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
*/
namespace Whoops;
use InvalidArgumentException;
use Throwable;
use Whoops\Exception\ErrorException;
use Whoops\Handler\CallbackHandler;
use Whoops\Handler\Handler;
use Whoops\Handler\HandlerInterface;
use Whoops\Inspector\CallableInspectorFactory;
use Whoops\Inspector\InspectorFactory;
use Whoops\Inspector\InspectorFactoryInterface;
use Whoops\Inspector\InspectorInterface;
use Whoops\Util\Misc;
use Whoops\Util\SystemFacade;
final class Run implements RunInterface
{
/**
* @var bool
*/
private $isRegistered;
/**
* @var bool
*/
private $allowQuit = true;
/**
* @var bool
*/
private $sendOutput = true;
/**
* @var integer|false
*/
private $sendHttpCode = 500;
/**
* @var integer|false
*/
private $sendExitCode = 1;
/**
* @var HandlerInterface[]
*/
private $handlerStack = [];
/**
* @var array
* @psalm-var list<array{patterns: string, levels: int}>
*/
private $silencedPatterns = [];
/**
* @var SystemFacade
*/
private $system;
/**
* In certain scenarios, like in shutdown handler, we can not throw exceptions.
*
* @var bool
*/
private $canThrowExceptions = true;
/**
* The inspector factory to create inspectors.
*
* @var InspectorFactoryInterface
*/
private $inspectorFactory;
/**
* @var array<callable>
*/
private $frameFilters = [];
public function __construct(?SystemFacade $system = null)
{
$this->system = $system ?: new SystemFacade;
$this->inspectorFactory = new InspectorFactory();
}
public function __destruct()
{
$this->unregister();
}
/**
* Explicitly request your handler runs as the last of all currently registered handlers.
*
* @param callable|HandlerInterface $handler
*
* @return Run
*/
public function appendHandler($handler)
{
array_unshift($this->handlerStack, $this->resolveHandler($handler));
return $this;
}
/**
* Explicitly request your handler runs as the first of all currently registered handlers.
*
* @param callable|HandlerInterface $handler
*
* @return Run
*/
public function prependHandler($handler)
{
return $this->pushHandler($handler);
}
/**
* Register your handler as the last of all currently registered handlers (to be executed first).
* Prefer using appendHandler and prependHandler for clarity.
*
* @param callable|HandlerInterface $handler
*
* @return Run
*
* @throws InvalidArgumentException If argument is not callable or instance of HandlerInterface.
*/
public function pushHandler($handler)
{
$this->handlerStack[] = $this->resolveHandler($handler);
return $this;
}
/**
* Removes and returns the last handler pushed to the handler stack.
*
* @see Run::removeFirstHandler(), Run::removeLastHandler()
*
* @return HandlerInterface|null
*/
public function popHandler()
{
return array_pop($this->handlerStack);
}
/**
* Removes the first handler.
*
* @return void
*/
public function removeFirstHandler()
{
array_pop($this->handlerStack);
}
/**
* Removes the last handler.
*
* @return void
*/
public function removeLastHandler()
{
array_shift($this->handlerStack);
}
/**
* Returns an array with all handlers, in the order they were added to the stack.
*
* @return array
*/
public function getHandlers()
{
return $this->handlerStack;
}
/**
* Clears all handlers in the handlerStack, including the default PrettyPage handler.
*
* @return Run
*/
public function clearHandlers()
{
$this->handlerStack = [];
return $this;
}
public function getFrameFilters()
{
return $this->frameFilters;
}
public function clearFrameFilters()
{
$this->frameFilters = [];
return $this;
}
/**
* Registers this instance as an error handler.
*
* @return Run
*/
public function register()
{
if (!$this->isRegistered) {
// Workaround PHP bug 42098
// https://bugs.php.net/bug.php?id=42098
class_exists("\\Whoops\\Exception\\ErrorException");
class_exists("\\Whoops\\Exception\\FrameCollection");
class_exists("\\Whoops\\Exception\\Frame");
class_exists("\\Whoops\\Exception\\Inspector");
class_exists("\\Whoops\\Inspector\\InspectorFactory");
$this->system->setErrorHandler([$this, self::ERROR_HANDLER]);
$this->system->setExceptionHandler([$this, self::EXCEPTION_HANDLER]);
$this->system->registerShutdownFunction([$this, self::SHUTDOWN_HANDLER]);
$this->isRegistered = true;
}
return $this;
}
/**
* Unregisters all handlers registered by this Whoops\Run instance.
*
* @return Run
*/
public function unregister()
{
if ($this->isRegistered) {
$this->system->restoreExceptionHandler();
$this->system->restoreErrorHandler();
$this->isRegistered = false;
}
return $this;
}
/**
* Should Whoops allow Handlers to force the script to quit?
*
* @param bool|int $exit
*
* @return bool
*/
public function allowQuit($exit = null)
{
if (func_num_args() == 0) {
return $this->allowQuit;
}
return $this->allowQuit = (bool) $exit;
}
/**
* Silence particular errors in particular files.
*
* @param array|string $patterns List or a single regex pattern to match.
* @param int $levels Defaults to E_STRICT | E_DEPRECATED.
*
* @return Run
*/
public function silenceErrorsInPaths($patterns, $levels = 10240)
{
$this->silencedPatterns = array_merge(
$this->silencedPatterns,
array_map(
function ($pattern) use ($levels) {
return [
"pattern" => $pattern,
"levels" => $levels,
];
},
(array) $patterns
)
);
return $this;
}
/**
* Returns an array with silent errors in path configuration.
*
* @return array
*/
public function getSilenceErrorsInPaths()
{
return $this->silencedPatterns;
}
/**
* Should Whoops send HTTP error code to the browser if possible?
* Whoops will by default send HTTP code 500, but you may wish to
* use 502, 503, or another 5xx family code.
*
* @param bool|int $code
*
* @return int|false
*
* @throws InvalidArgumentException
*/
public function sendHttpCode($code = null)
{
if (func_num_args() == 0) {
return $this->sendHttpCode;
}
if (!$code) {
return $this->sendHttpCode = false;
}
if ($code === true) {
$code = 500;
}
if ($code < 400 || 600 <= $code) {
throw new InvalidArgumentException(
"Invalid status code '$code', must be 4xx or 5xx"
);
}
return $this->sendHttpCode = $code;
}
/**
* Should Whoops exit with a specific code on the CLI if possible?
* Whoops will exit with 1 by default, but you can specify something else.
*
* @param int $code
*
* @return int
*
* @throws InvalidArgumentException
*/
public function sendExitCode($code = null)
{
if (func_num_args() == 0) {
return $this->sendExitCode;
}
if ($code < 0 || 255 <= $code) {
throw new InvalidArgumentException(
"Invalid status code '$code', must be between 0 and 254"
);
}
return $this->sendExitCode = (int) $code;
}
/**
* Should Whoops push output directly to the client?
* If this is false, output will be returned by handleException.
*
* @param bool|int $send
*
* @return bool
*/
public function writeToOutput($send = null)
{
if (func_num_args() == 0) {
return $this->sendOutput;
}
return $this->sendOutput = (bool) $send;
}
/**
* Handles an exception, ultimately generating a Whoops error page.
*
* @param Throwable $exception
*
* @return string Output generated by handlers.
*/
public function handleException($exception)
{
// Walk the registered handlers in the reverse order
// they were registered, and pass off the exception
$inspector = $this->getInspector($exception);
// Capture output produced while handling the exception,
// we might want to send it straight away to the client,
// or return it silently.
$this->system->startOutputBuffering();
// Just in case there are no handlers:
$handlerResponse = null;
$handlerContentType = null;
try {
foreach (array_reverse($this->handlerStack) as $handler) {
$handler->setRun($this);
$handler->setInspector($inspector);
$handler->setException($exception);
// The HandlerInterface does not require an Exception passed to handle()
// and neither of our bundled handlers use it.
// However, 3rd party handlers may have already relied on this parameter,
// and removing it would be possibly breaking for users.
$handlerResponse = $handler->handle($exception);
// Collect the content type for possible sending in the headers.
$handlerContentType = method_exists($handler, 'contentType') ? $handler->contentType() : null;
if (in_array($handlerResponse, [Handler::LAST_HANDLER, Handler::QUIT])) {
// The Handler has handled the exception in some way, and
// wishes to quit execution (Handler::QUIT), or skip any
// other handlers (Handler::LAST_HANDLER). If $this->allowQuit
// is false, Handler::QUIT behaves like Handler::LAST_HANDLER
break;
}
}
$willQuit = $handlerResponse == Handler::QUIT && $this->allowQuit();
} finally {
$output = $this->system->cleanOutputBuffer();
}
// If we're allowed to, send output generated by handlers directly
// to the output, otherwise, and if the script doesn't quit, return
// it so that it may be used by the caller
if ($this->writeToOutput()) {
// @todo Might be able to clean this up a bit better
if ($willQuit) {
// Cleanup all other output buffers before sending our output:
while ($this->system->getOutputBufferLevel() > 0) {
$this->system->endOutputBuffering();
}
// Send any headers if needed:
if (Misc::canSendHeaders() && $handlerContentType) {
header("Content-Type: {$handlerContentType}");
}
}
$this->writeToOutputNow($output);
}
if ($willQuit) {
// HHVM fix for https://github.com/facebook/hhvm/issues/4055
$this->system->flushOutputBuffer();
$this->system->stopExecution(
$this->sendExitCode()
);
}
return $output;
}
/**
* Converts generic PHP errors to \ErrorException instances, before passing them off to be handled.
*
* This method MUST be compatible with set_error_handler.
*
* @param int $level
* @param string $message
* @param string|null $file
* @param int|null $line
*
* @return bool
*
* @throws ErrorException
*/
public function handleError($level, $message, $file = null, $line = null)
{
if ($level & $this->system->getErrorReportingLevel()) {
foreach ($this->silencedPatterns as $entry) {
$pathMatches = (bool) preg_match($entry["pattern"], $file);
$levelMatches = $level & $entry["levels"];
if ($pathMatches && $levelMatches) {
// Ignore the error, abort handling
// See https://github.com/filp/whoops/issues/418
return true;
}
}
// XXX we pass $level for the "code" param only for BC reasons.
// see https://github.com/filp/whoops/issues/267
$exception = new ErrorException($message, /*code*/ $level, /*severity*/ $level, $file, $line);
if ($this->canThrowExceptions) {
throw $exception;
} else {
$this->handleException($exception);
}
// Do not propagate errors which were already handled by Whoops.
return true;
}
// Propagate error to the next handler, allows error_get_last() to
// work on silenced errors.
return false;
}
/**
* Special case to deal with Fatal errors and the like.
*
* @return void
*/
public function handleShutdown()
{
// If we reached this step, we are in shutdown handler.
// An exception thrown in a shutdown handler will not be propagated
// to the exception handler. Pass that information along.
$this->canThrowExceptions = false;
// If we are not currently registered, we should not do anything
if (!$this->isRegistered) {
return;
}
$error = $this->system->getLastError();
if ($error && Misc::isLevelFatal($error['type'])) {
// If there was a fatal error,
// it was not handled in handleError yet.
$this->allowQuit = false;
$this->handleError(
$error['type'],
$error['message'],
$error['file'],
$error['line']
);
}
}
/**
* @param InspectorFactoryInterface $factory
*
* @return void
*/
public function setInspectorFactory(InspectorFactoryInterface $factory)
{
$this->inspectorFactory = $factory;
}
public function addFrameFilter($filterCallback)
{
if (!is_callable($filterCallback)) {
throw new \InvalidArgumentException(sprintf(
"A frame filter must be of type callable, %s type given.",
gettype($filterCallback)
));
}
$this->frameFilters[] = $filterCallback;
return $this;
}
/**
* @param Throwable $exception
*
* @return InspectorInterface
*/
private function getInspector($exception)
{
return $this->inspectorFactory->create($exception);
}
/**
* Resolves the giving handler.
*
* @param callable|HandlerInterface $handler
*
* @return HandlerInterface
*
* @throws InvalidArgumentException
*/
private function resolveHandler($handler)
{
if (is_callable($handler)) {
$handler = new CallbackHandler($handler);
}
if (!$handler instanceof HandlerInterface) {
throw new InvalidArgumentException(
"Handler must be a callable, or instance of "
. "Whoops\\Handler\\HandlerInterface"
);
}
return $handler;
}
/**
* Echo something to the browser.
*
* @param string $output
*
* @return Run
*/
private function writeToOutputNow($output)
{
if ($this->sendHttpCode() && Misc::canSendHeaders()) {
$this->system->setHttpResponseCode(
$this->sendHttpCode()
);
}
echo $output;
return $this;
}
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/src/Whoops/RunInterface.php | src/Whoops/RunInterface.php | <?php
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
*/
namespace Whoops;
use InvalidArgumentException;
use Whoops\Exception\ErrorException;
use Whoops\Handler\HandlerInterface;
interface RunInterface
{
const EXCEPTION_HANDLER = "handleException";
const ERROR_HANDLER = "handleError";
const SHUTDOWN_HANDLER = "handleShutdown";
/**
* Pushes a handler to the end of the stack
*
* @throws InvalidArgumentException If argument is not callable or instance of HandlerInterface
* @param Callable|HandlerInterface $handler
* @return Run
*/
public function pushHandler($handler);
/**
* Removes the last handler in the stack and returns it.
* Returns null if there"s nothing else to pop.
*
* @return null|HandlerInterface
*/
public function popHandler();
/**
* Returns an array with all handlers, in the
* order they were added to the stack.
*
* @return array
*/
public function getHandlers();
/**
* Clears all handlers in the handlerStack, including
* the default PrettyPage handler.
*
* @return Run
*/
public function clearHandlers();
/**
* @return array<callable>
*/
public function getFrameFilters();
/**
* @return Run
*/
public function clearFrameFilters();
/**
* Registers this instance as an error handler.
*
* @return Run
*/
public function register();
/**
* Unregisters all handlers registered by this Whoops\Run instance
*
* @return Run
*/
public function unregister();
/**
* Should Whoops allow Handlers to force the script to quit?
*
* @param bool|int $exit
* @return bool
*/
public function allowQuit($exit = null);
/**
* Silence particular errors in particular files
*
* @param array|string $patterns List or a single regex pattern to match
* @param int $levels Defaults to E_STRICT | E_DEPRECATED
* @return \Whoops\Run
*/
public function silenceErrorsInPaths($patterns, $levels = 10240);
/**
* Should Whoops send HTTP error code to the browser if possible?
* Whoops will by default send HTTP code 500, but you may wish to
* use 502, 503, or another 5xx family code.
*
* @param bool|int $code
* @return int|false
*/
public function sendHttpCode($code = null);
/**
* Should Whoops exit with a specific code on the CLI if possible?
* Whoops will exit with 1 by default, but you can specify something else.
*
* @param int $code
* @return int
*/
public function sendExitCode($code = null);
/**
* Should Whoops push output directly to the client?
* If this is false, output will be returned by handleException
*
* @param bool|int $send
* @return bool
*/
public function writeToOutput($send = null);
/**
* Handles an exception, ultimately generating a Whoops error
* page.
*
* @param \Throwable $exception
* @return string Output generated by handlers
*/
public function handleException($exception);
/**
* Converts generic PHP errors to \ErrorException
* instances, before passing them off to be handled.
*
* This method MUST be compatible with set_error_handler.
*
* @param int $level
* @param string $message
* @param string $file
* @param int $line
*
* @return bool
* @throws ErrorException
*/
public function handleError($level, $message, $file = null, $line = null);
/**
* Special case to deal with Fatal errors and the like.
*/
public function handleShutdown();
/**
* Registers a filter callback in the frame filters stack.
*
* @param callable $filterCallback
* @return \Whoops\Run
*/
public function addFrameFilter($filterCallback);
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/src/Whoops/Inspector/InspectorInterface.php | src/Whoops/Inspector/InspectorInterface.php | <?php
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
*/
namespace Whoops\Inspector;
interface InspectorInterface
{
/**
* @return \Throwable
*/
public function getException();
/**
* @return string
*/
public function getExceptionName();
/**
* @return string
*/
public function getExceptionMessage();
/**
* @return string[]
*/
public function getPreviousExceptionMessages();
/**
* @return int[]
*/
public function getPreviousExceptionCodes();
/**
* Returns a url to the php-manual related to the underlying error - when available.
*
* @return string|null
*/
public function getExceptionDocrefUrl();
/**
* Does the wrapped Exception has a previous Exception?
* @return bool
*/
public function hasPreviousException();
/**
* Returns an Inspector for a previous Exception, if any.
* @todo Clean this up a bit, cache stuff a bit better.
* @return InspectorInterface
*/
public function getPreviousExceptionInspector();
/**
* Returns an array of all previous exceptions for this inspector's exception
* @return \Throwable[]
*/
public function getPreviousExceptions();
/**
* Returns an iterator for the inspected exception's
* frames.
*
* @param array<callable> $frameFilters
*
* @return \Whoops\Exception\FrameCollection
*/
public function getFrames(array $frameFilters = []);
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/src/Whoops/Inspector/InspectorFactory.php | src/Whoops/Inspector/InspectorFactory.php | <?php
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
*/
namespace Whoops\Inspector;
use Whoops\Exception\Inspector;
class InspectorFactory implements InspectorFactoryInterface
{
/**
* @param \Throwable $exception
* @return InspectorInterface
*/
public function create($exception)
{
return new Inspector($exception, $this);
}
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/src/Whoops/Inspector/InspectorFactoryInterface.php | src/Whoops/Inspector/InspectorFactoryInterface.php | <?php
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
*/
namespace Whoops\Inspector;
interface InspectorFactoryInterface
{
/**
* @param \Throwable $exception
* @return InspectorInterface
*/
public function create($exception);
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/src/Whoops/Handler/XmlResponseHandler.php | src/Whoops/Handler/XmlResponseHandler.php | <?php
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
*/
namespace Whoops\Handler;
use SimpleXMLElement;
use Whoops\Exception\Formatter;
/**
* Catches an exception and converts it to an XML
* response. Additionally can also return exception
* frames for consumption by an API.
*/
class XmlResponseHandler extends Handler
{
/**
* @var bool
*/
private $returnFrames = false;
/**
* @param bool|null $returnFrames
* @return bool|static
*/
public function addTraceToOutput($returnFrames = null)
{
if (func_num_args() == 0) {
return $this->returnFrames;
}
$this->returnFrames = (bool) $returnFrames;
return $this;
}
/**
* @return int
*/
public function handle()
{
$response = [
'error' => Formatter::formatExceptionAsDataArray(
$this->getInspector(),
$this->addTraceToOutput(),
$this->getRun()->getFrameFilters()
),
];
echo self::toXml($response);
return Handler::QUIT;
}
/**
* @return string
*/
public function contentType()
{
return 'application/xml';
}
/**
* @param SimpleXMLElement $node Node to append data to, will be modified in place
* @param array|\Traversable $data
* @return SimpleXMLElement The modified node, for chaining
*/
private static function addDataToNode(\SimpleXMLElement $node, $data)
{
assert(is_array($data) || $data instanceof Traversable);
foreach ($data as $key => $value) {
if (is_numeric($key)) {
// Convert the key to a valid string
$key = "unknownNode_". (string) $key;
}
// Delete any char not allowed in XML element names
$key = preg_replace('/[^a-z0-9\-\_\.\:]/i', '', $key);
if (is_array($value)) {
$child = $node->addChild($key);
self::addDataToNode($child, $value);
} else {
$value = str_replace('&', '&', print_r($value, true));
$node->addChild($key, $value);
}
}
return $node;
}
/**
* The main function for converting to an XML document.
*
* @param array|\Traversable $data
* @return string XML
*/
private static function toXml($data)
{
assert(is_array($data) || $data instanceof Traversable);
$node = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><root />");
return self::addDataToNode($node, $data)->asXML();
}
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/src/Whoops/Handler/Handler.php | src/Whoops/Handler/Handler.php | <?php
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
*/
namespace Whoops\Handler;
use Whoops\Inspector\InspectorInterface;
use Whoops\RunInterface;
/**
* Abstract implementation of a Handler.
*/
abstract class Handler implements HandlerInterface
{
/*
Return constants that can be returned from Handler::handle
to message the handler walker.
*/
const DONE = 0x10; // returning this is optional, only exists for
// semantic purposes
/**
* The Handler has handled the Throwable in some way, and wishes to skip any other Handler.
* Execution will continue.
*/
const LAST_HANDLER = 0x20;
/**
* The Handler has handled the Throwable in some way, and wishes to quit/stop execution
*/
const QUIT = 0x30;
/**
* @var RunInterface
*/
private $run;
/**
* @var InspectorInterface $inspector
*/
private $inspector;
/**
* @var \Throwable $exception
*/
private $exception;
/**
* @param RunInterface $run
*/
public function setRun(RunInterface $run)
{
$this->run = $run;
}
/**
* @return RunInterface
*/
protected function getRun()
{
return $this->run;
}
/**
* @param InspectorInterface $inspector
*/
public function setInspector(InspectorInterface $inspector)
{
$this->inspector = $inspector;
}
/**
* @return InspectorInterface
*/
protected function getInspector()
{
return $this->inspector;
}
/**
* @param \Throwable $exception
*/
public function setException($exception)
{
$this->exception = $exception;
}
/**
* @return \Throwable
*/
protected function getException()
{
return $this->exception;
}
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/src/Whoops/Handler/CallbackHandler.php | src/Whoops/Handler/CallbackHandler.php | <?php
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
*/
namespace Whoops\Handler;
use InvalidArgumentException;
/**
* Wrapper for Closures passed as handlers. Can be used
* directly, or will be instantiated automagically by Whoops\Run
* if passed to Run::pushHandler
*/
class CallbackHandler extends Handler
{
/**
* @var callable
*/
protected $callable;
/**
* @throws InvalidArgumentException If argument is not callable
* @param callable $callable
*/
public function __construct($callable)
{
if (!is_callable($callable)) {
throw new InvalidArgumentException(
'Argument to ' . __METHOD__ . ' must be valid callable'
);
}
$this->callable = $callable;
}
/**
* @return int|null
*/
public function handle()
{
$exception = $this->getException();
$inspector = $this->getInspector();
$run = $this->getRun();
$callable = $this->callable;
// invoke the callable directly, to get simpler stacktraces (in comparison to call_user_func).
// this assumes that $callable is a properly typed php-callable, which we check in __construct().
return $callable($exception, $inspector, $run);
}
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/src/Whoops/Handler/PlainTextHandler.php | src/Whoops/Handler/PlainTextHandler.php | <?php
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
* Plaintext handler for command line and logs.
* @author Pierre-Yves Landuré <https://howto.biapy.com/>
*/
namespace Whoops\Handler;
use InvalidArgumentException;
use Psr\Log\LoggerInterface;
use Whoops\Exception\Frame;
/**
* Handler outputing plaintext error messages. Can be used
* directly, or will be instantiated automagically by Whoops\Run
* if passed to Run::pushHandler
*/
class PlainTextHandler extends Handler
{
const VAR_DUMP_PREFIX = ' | ';
/**
* @var \Psr\Log\LoggerInterface
*/
protected $logger;
/**
* @var callable
*/
protected $dumper;
/**
* @var bool
*/
private $addTraceToOutput = true;
/**
* @var bool|integer
*/
private $addTraceFunctionArgsToOutput = false;
/**
* @var integer
*/
private $traceFunctionArgsOutputLimit = 1024;
/**
* @var bool
*/
private $addPreviousToOutput = true;
/**
* @var bool
*/
private $loggerOnly = false;
/**
* Constructor.
* @throws InvalidArgumentException If argument is not null or a LoggerInterface
* @param \Psr\Log\LoggerInterface|null $logger
*/
public function __construct($logger = null)
{
$this->setLogger($logger);
}
/**
* Set the output logger interface.
* @throws InvalidArgumentException If argument is not null or a LoggerInterface
* @param \Psr\Log\LoggerInterface|null $logger
*/
public function setLogger($logger = null)
{
if (! (is_null($logger)
|| $logger instanceof LoggerInterface)) {
throw new InvalidArgumentException(
'Argument to ' . __METHOD__ .
" must be a valid Logger Interface (aka. Monolog), " .
get_class($logger) . ' given.'
);
}
$this->logger = $logger;
}
/**
* @return \Psr\Log\LoggerInterface|null
*/
public function getLogger()
{
return $this->logger;
}
/**
* Set var dumper callback function.
*
* @param callable $dumper
* @return static
*/
public function setDumper(callable $dumper)
{
$this->dumper = $dumper;
return $this;
}
/**
* Add error trace to output.
* @param bool|null $addTraceToOutput
* @return bool|static
*/
public function addTraceToOutput($addTraceToOutput = null)
{
if (func_num_args() == 0) {
return $this->addTraceToOutput;
}
$this->addTraceToOutput = (bool) $addTraceToOutput;
return $this;
}
/**
* Add previous exceptions to output.
* @param bool|null $addPreviousToOutput
* @return bool|static
*/
public function addPreviousToOutput($addPreviousToOutput = null)
{
if (func_num_args() == 0) {
return $this->addPreviousToOutput;
}
$this->addPreviousToOutput = (bool) $addPreviousToOutput;
return $this;
}
/**
* Add error trace function arguments to output.
* Set to True for all frame args, or integer for the n first frame args.
* @param bool|integer|null $addTraceFunctionArgsToOutput
* @return static|bool|integer
*/
public function addTraceFunctionArgsToOutput($addTraceFunctionArgsToOutput = null)
{
if (func_num_args() == 0) {
return $this->addTraceFunctionArgsToOutput;
}
if (! is_integer($addTraceFunctionArgsToOutput)) {
$this->addTraceFunctionArgsToOutput = (bool) $addTraceFunctionArgsToOutput;
} else {
$this->addTraceFunctionArgsToOutput = $addTraceFunctionArgsToOutput;
}
return $this;
}
/**
* Set the size limit in bytes of frame arguments var_dump output.
* If the limit is reached, the var_dump output is discarded.
* Prevent memory limit errors.
* @param int $traceFunctionArgsOutputLimit
* @return static
*/
public function setTraceFunctionArgsOutputLimit($traceFunctionArgsOutputLimit)
{
$this->traceFunctionArgsOutputLimit = (int) $traceFunctionArgsOutputLimit;
return $this;
}
/**
* Create plain text response and return it as a string
* @return string
*/
public function generateResponse()
{
$exception = $this->getException();
$message = $this->getExceptionOutput($exception);
if ($this->addPreviousToOutput) {
$previous = $exception->getPrevious();
while ($previous) {
$message .= "\n\nCaused by\n" . $this->getExceptionOutput($previous);
$previous = $previous->getPrevious();
}
}
return $message . $this->getTraceOutput() . "\n";
}
/**
* Get the size limit in bytes of frame arguments var_dump output.
* If the limit is reached, the var_dump output is discarded.
* Prevent memory limit errors.
* @return integer
*/
public function getTraceFunctionArgsOutputLimit()
{
return $this->traceFunctionArgsOutputLimit;
}
/**
* Only output to logger.
* @param bool|null $loggerOnly
* @return static|bool
*/
public function loggerOnly($loggerOnly = null)
{
if (func_num_args() == 0) {
return $this->loggerOnly;
}
$this->loggerOnly = (bool) $loggerOnly;
return $this;
}
/**
* Test if handler can output to stdout.
* @return bool
*/
private function canOutput()
{
return !$this->loggerOnly();
}
/**
* Get the frame args var_dump.
* @param \Whoops\Exception\Frame $frame [description]
* @param integer $line [description]
* @return string
*/
private function getFrameArgsOutput(Frame $frame, $line)
{
if ($this->addTraceFunctionArgsToOutput() === false
|| $this->addTraceFunctionArgsToOutput() < $line) {
return '';
}
// Dump the arguments:
ob_start();
$this->dump($frame->getArgs());
if (ob_get_length() > $this->getTraceFunctionArgsOutputLimit()) {
// The argument var_dump is to big.
// Discarded to limit memory usage.
ob_clean();
return sprintf(
"\n%sArguments dump length greater than %d Bytes. Discarded.",
self::VAR_DUMP_PREFIX,
$this->getTraceFunctionArgsOutputLimit()
);
}
return sprintf(
"\n%s",
preg_replace('/^/m', self::VAR_DUMP_PREFIX, ob_get_clean())
);
}
/**
* Dump variable.
*
* @param mixed $var
* @return void
*/
protected function dump($var)
{
if ($this->dumper) {
call_user_func($this->dumper, $var);
} else {
var_dump($var);
}
}
/**
* Get the exception trace as plain text.
* @return string
*/
private function getTraceOutput()
{
if (! $this->addTraceToOutput()) {
return '';
}
$inspector = $this->getInspector();
$frames = $inspector->getFrames($this->getRun()->getFrameFilters());
$response = "\nStack trace:";
$line = 1;
foreach ($frames as $frame) {
/** @var Frame $frame */
$class = $frame->getClass();
$template = "\n%3d. %s->%s() %s:%d%s";
if (! $class) {
// Remove method arrow (->) from output.
$template = "\n%3d. %s%s() %s:%d%s";
}
$response .= sprintf(
$template,
$line,
$class,
$frame->getFunction(),
$frame->getFile(),
$frame->getLine(),
$this->getFrameArgsOutput($frame, $line)
);
$line++;
}
return $response;
}
/**
* Get the exception as plain text.
* @param \Throwable $exception
* @return string
*/
private function getExceptionOutput($exception)
{
return sprintf(
"%s: %s in file %s on line %d",
get_class($exception),
$exception->getMessage(),
$exception->getFile(),
$exception->getLine()
);
}
/**
* @return int
*/
public function handle()
{
$response = $this->generateResponse();
if ($this->getLogger()) {
$this->getLogger()->error($response);
}
if (! $this->canOutput()) {
return Handler::DONE;
}
echo $response;
return Handler::QUIT;
}
/**
* @return string
*/
public function contentType()
{
return 'text/plain';
}
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/src/Whoops/Handler/JsonResponseHandler.php | src/Whoops/Handler/JsonResponseHandler.php | <?php
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
*/
namespace Whoops\Handler;
use Whoops\Exception\Formatter;
/**
* Catches an exception and converts it to a JSON
* response. Additionally can also return exception
* frames for consumption by an API.
*/
class JsonResponseHandler extends Handler
{
/**
* @var bool
*/
private $returnFrames = false;
/**
* @var bool
*/
private $jsonApi = false;
/**
* Returns errors[[]] instead of error[] to be in compliance with the json:api spec
* @param bool $jsonApi Default is false
* @return static
*/
public function setJsonApi($jsonApi = false)
{
$this->jsonApi = (bool) $jsonApi;
return $this;
}
/**
* @param bool|null $returnFrames
* @return bool|static
*/
public function addTraceToOutput($returnFrames = null)
{
if (func_num_args() == 0) {
return $this->returnFrames;
}
$this->returnFrames = (bool) $returnFrames;
return $this;
}
/**
* @return int
*/
public function handle()
{
if ($this->jsonApi === true) {
$response = [
'errors' => [
Formatter::formatExceptionAsDataArray(
$this->getInspector(),
$this->addTraceToOutput(),
$this->getRun()->getFrameFilters()
),
]
];
} else {
$response = [
'error' => Formatter::formatExceptionAsDataArray(
$this->getInspector(),
$this->addTraceToOutput(),
$this->getRun()->getFrameFilters()
),
];
}
echo json_encode($response, defined('JSON_PARTIAL_OUTPUT_ON_ERROR') ? JSON_PARTIAL_OUTPUT_ON_ERROR : 0);
return Handler::QUIT;
}
/**
* @return string
*/
public function contentType()
{
return 'application/json';
}
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/src/Whoops/Handler/HandlerInterface.php | src/Whoops/Handler/HandlerInterface.php | <?php
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
*/
namespace Whoops\Handler;
use Whoops\Inspector\InspectorInterface;
use Whoops\RunInterface;
interface HandlerInterface
{
/**
* @return int|null A handler may return nothing, or a Handler::HANDLE_* constant
*/
public function handle();
/**
* @param RunInterface $run
* @return void
*/
public function setRun(RunInterface $run);
/**
* @param \Throwable $exception
* @return void
*/
public function setException($exception);
/**
* @param InspectorInterface $inspector
* @return void
*/
public function setInspector(InspectorInterface $inspector);
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/src/Whoops/Handler/PrettyPageHandler.php | src/Whoops/Handler/PrettyPageHandler.php | <?php
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
*/
namespace Whoops\Handler;
use InvalidArgumentException;
use RuntimeException;
use Symfony\Component\VarDumper\Cloner\AbstractCloner;
use Symfony\Component\VarDumper\Cloner\VarCloner;
use UnexpectedValueException;
use Whoops\Exception\Formatter;
use Whoops\Util\Misc;
use Whoops\Util\TemplateHelper;
class PrettyPageHandler extends Handler
{
const EDITOR_SUBLIME = "sublime";
const EDITOR_TEXTMATE = "textmate";
const EDITOR_EMACS = "emacs";
const EDITOR_MACVIM = "macvim";
const EDITOR_PHPSTORM = "phpstorm";
const EDITOR_IDEA = "idea";
const EDITOR_VSCODE = "vscode";
const EDITOR_ATOM = "atom";
const EDITOR_ESPRESSO = "espresso";
const EDITOR_XDEBUG = "xdebug";
const EDITOR_NETBEANS = "netbeans";
const EDITOR_CURSOR = "cursor";
/**
* Search paths to be scanned for resources.
*
* Stored in the reverse order they're declared.
*
* @var array
*/
private $searchPaths = [];
/**
* Fast lookup cache for known resource locations.
*
* @var array
*/
private $resourceCache = [];
/**
* The name of the custom css file.
*
* @var string|null
*/
private $customCss = null;
/**
* The name of the custom js file.
*
* @var string|null
*/
private $customJs = null;
/**
* @var array[]
*/
private $extraTables = [];
/**
* @var bool
*/
private $handleUnconditionally = false;
/**
* @var string
*/
private $pageTitle = "Whoops! There was an error.";
/**
* @var array[]
*/
private $applicationPaths;
/**
* @var array[]
*/
private $blacklist = [
'_GET' => [],
'_POST' => [],
'_FILES' => [],
'_COOKIE' => [],
'_SESSION' => [],
'_SERVER' => [],
'_ENV' => [],
];
/**
* An identifier for a known IDE/text editor.
*
* Either a string, or a calalble that resolves a string, that can be used
* to open a given file in an editor. If the string contains the special
* substrings %file or %line, they will be replaced with the correct data.
*
* @example
* "txmt://open?url=%file&line=%line"
*
* @var callable|string $editor
*/
protected $editor;
/**
* A list of known editor strings.
*
* @var array
*/
protected $editors = [
"sublime" => "subl://open?url=file://%file&line=%line",
"textmate" => "txmt://open?url=file://%file&line=%line",
"emacs" => "emacs://open?url=file://%file&line=%line",
"macvim" => "mvim://open/?url=file://%file&line=%line",
"phpstorm" => "phpstorm://open?file=%file&line=%line",
"idea" => "idea://open?file=%file&line=%line",
"vscode" => "vscode://file/%file:%line",
"atom" => "atom://core/open/file?filename=%file&line=%line",
"espresso" => "x-espresso://open?filepath=%file&lines=%line",
"netbeans" => "netbeans://open/?f=%file:%line",
"cursor" => "cursor://file/%file:%line",
];
/**
* @var TemplateHelper
*/
protected $templateHelper;
/**
* Constructor.
*
* @return void
*/
public function __construct()
{
if (ini_get('xdebug.file_link_format') || get_cfg_var('xdebug.file_link_format')) {
// Register editor using xdebug's file_link_format option.
$this->editors['xdebug'] = function ($file, $line) {
return str_replace(['%f', '%l'], [$file, $line], ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format'));
};
// If xdebug is available, use it as default editor.
$this->setEditor('xdebug');
}
// Add the default, local resource search path:
$this->searchPaths[] = __DIR__ . "/../Resources";
// blacklist php provided auth based values
$this->blacklist('_SERVER', 'PHP_AUTH_PW');
$this->templateHelper = new TemplateHelper();
if (class_exists('Symfony\Component\VarDumper\Cloner\VarCloner')) {
$cloner = new VarCloner();
// Only dump object internals if a custom caster exists for performance reasons
// https://github.com/filp/whoops/pull/404
$cloner->addCasters(['*' => function ($obj, $a, $stub, $isNested, $filter = 0) {
$class = $stub->class;
$classes = [$class => $class] + class_parents($obj) + class_implements($obj);
foreach ($classes as $class) {
if (isset(AbstractCloner::$defaultCasters[$class])) {
return $a;
}
}
// Remove all internals
return [];
}]);
$this->templateHelper->setCloner($cloner);
}
}
/**
* @return int|null
*
* @throws \Exception
*/
public function handle()
{
if (!$this->handleUnconditionally()) {
// Check conditions for outputting HTML:
// @todo: Make this more robust
if (PHP_SAPI === 'cli') {
// Help users who have been relying on an internal test value
// fix their code to the proper method
if (isset($_ENV['whoops-test'])) {
throw new \Exception(
'Use handleUnconditionally instead of whoops-test'
.' environment variable'
);
}
return Handler::DONE;
}
}
$templateFile = $this->getResource("views/layout.html.php");
$cssFile = $this->getResource("css/whoops.base.css");
$zeptoFile = $this->getResource("js/zepto.min.js");
$prismJs = $this->getResource("js/prism.js");
$prismCss = $this->getResource("css/prism.css");
$clipboard = $this->getResource("js/clipboard.min.js");
$jsFile = $this->getResource("js/whoops.base.js");
if ($this->customCss) {
$customCssFile = $this->getResource($this->customCss);
}
if ($this->customJs) {
$customJsFile = $this->getResource($this->customJs);
}
$inspector = $this->getInspector();
$frames = $this->getExceptionFrames();
$code = $this->getExceptionCode();
// List of variables that will be passed to the layout template.
$vars = [
"page_title" => $this->getPageTitle(),
// @todo: Asset compiler
"stylesheet" => file_get_contents($cssFile),
"zepto" => file_get_contents($zeptoFile),
"prismJs" => file_get_contents($prismJs),
"prismCss" => file_get_contents($prismCss),
"clipboard" => file_get_contents($clipboard),
"javascript" => file_get_contents($jsFile),
// Template paths:
"header" => $this->getResource("views/header.html.php"),
"header_outer" => $this->getResource("views/header_outer.html.php"),
"frame_list" => $this->getResource("views/frame_list.html.php"),
"frames_description" => $this->getResource("views/frames_description.html.php"),
"frames_container" => $this->getResource("views/frames_container.html.php"),
"panel_details" => $this->getResource("views/panel_details.html.php"),
"panel_details_outer" => $this->getResource("views/panel_details_outer.html.php"),
"panel_left" => $this->getResource("views/panel_left.html.php"),
"panel_left_outer" => $this->getResource("views/panel_left_outer.html.php"),
"frame_code" => $this->getResource("views/frame_code.html.php"),
"env_details" => $this->getResource("views/env_details.html.php"),
"title" => $this->getPageTitle(),
"name" => explode("\\", $inspector->getExceptionName()),
"message" => $inspector->getExceptionMessage(),
"previousMessages" => $inspector->getPreviousExceptionMessages(),
"docref_url" => $inspector->getExceptionDocrefUrl(),
"code" => $code,
"previousCodes" => $inspector->getPreviousExceptionCodes(),
"plain_exception" => Formatter::formatExceptionPlain($inspector),
"frames" => $frames,
"has_frames" => !!count($frames),
"handler" => $this,
"handlers" => $this->getRun()->getHandlers(),
"active_frames_tab" => count($frames) && $frames->offsetGet(0)->isApplication() ? 'application' : 'all',
"has_frames_tabs" => $this->getApplicationPaths(),
"tables" => [
"GET Data" => $this->masked($_GET, '_GET'),
"POST Data" => $this->masked($_POST, '_POST'),
"Files" => isset($_FILES) ? $this->masked($_FILES, '_FILES') : [],
"Cookies" => $this->masked($_COOKIE, '_COOKIE'),
"Session" => isset($_SESSION) ? $this->masked($_SESSION, '_SESSION') : [],
"Server/Request Data" => $this->masked($_SERVER, '_SERVER'),
"Environment Variables" => $this->masked($_ENV, '_ENV'),
],
];
if (isset($customCssFile)) {
$vars["stylesheet"] .= file_get_contents($customCssFile);
}
if (isset($customJsFile)) {
$vars["javascript"] .= file_get_contents($customJsFile);
}
// Add extra entries list of data tables:
// @todo: Consolidate addDataTable and addDataTableCallback
$extraTables = array_map(function ($table) use ($inspector) {
return $table instanceof \Closure ? $table($inspector) : $table;
}, $this->getDataTables());
$vars["tables"] = array_merge($extraTables, $vars["tables"]);
$plainTextHandler = new PlainTextHandler();
$plainTextHandler->setRun($this->getRun());
$plainTextHandler->setException($this->getException());
$plainTextHandler->setInspector($this->getInspector());
$vars["preface"] = "<!--\n\n\n" . $this->templateHelper->escape($plainTextHandler->generateResponse()) . "\n\n\n\n\n\n\n\n\n\n\n-->";
$this->templateHelper->setVariables($vars);
$this->templateHelper->render($templateFile);
return Handler::QUIT;
}
/**
* Get the stack trace frames of the exception currently being handled.
*
* @return \Whoops\Exception\FrameCollection
*/
protected function getExceptionFrames()
{
$frames = $this->getInspector()->getFrames($this->getRun()->getFrameFilters());
if ($this->getApplicationPaths()) {
foreach ($frames as $frame) {
foreach ($this->getApplicationPaths() as $path) {
if (strpos($frame->getFile(), $path) === 0) {
$frame->setApplication(true);
break;
}
}
}
}
return $frames;
}
/**
* Get the code of the exception currently being handled.
*
* @return string
*/
protected function getExceptionCode()
{
$exception = $this->getException();
$code = $exception->getCode();
if ($exception instanceof \ErrorException) {
// ErrorExceptions wrap the php-error types within the 'severity' property
$code = Misc::translateErrorCode($exception->getSeverity());
}
return (string) $code;
}
/**
* @return string
*/
public function contentType()
{
return 'text/html';
}
/**
* Adds an entry to the list of tables displayed in the template.
*
* The expected data is a simple associative array. Any nested arrays
* will be flattened with `print_r`.
*
* @param string $label
*
* @return static
*/
public function addDataTable($label, array $data)
{
$this->extraTables[$label] = $data;
return $this;
}
/**
* Lazily adds an entry to the list of tables displayed in the table.
*
* The supplied callback argument will be called when the error is
* rendered, it should produce a simple associative array. Any nested
* arrays will be flattened with `print_r`.
*
* @param string $label
* @param callable $callback Callable returning an associative array
*
* @throws InvalidArgumentException If $callback is not callable
*
* @return static
*/
public function addDataTableCallback($label, /* callable */ $callback)
{
if (!is_callable($callback)) {
throw new InvalidArgumentException('Expecting callback argument to be callable');
}
$this->extraTables[$label] = function (?\Whoops\Inspector\InspectorInterface $inspector = null) use ($callback) {
try {
$result = call_user_func($callback, $inspector);
// Only return the result if it can be iterated over by foreach().
return is_array($result) || $result instanceof \Traversable ? $result : [];
} catch (\Exception $e) {
// Don't allow failure to break the rendering of the original exception.
return [];
}
};
return $this;
}
/**
* Returns all the extra data tables registered with this handler.
*
* Optionally accepts a 'label' parameter, to only return the data table
* under that label.
*
* @param string|null $label
*
* @return array[]|callable
*/
public function getDataTables($label = null)
{
if ($label !== null) {
return isset($this->extraTables[$label]) ?
$this->extraTables[$label] : [];
}
return $this->extraTables;
}
/**
* Set whether to handle unconditionally.
*
* Allows to disable all attempts to dynamically decide whether to handle
* or return prematurely. Set this to ensure that the handler will perform,
* no matter what.
*
* @param bool|null $value
*
* @return bool|static
*/
public function handleUnconditionally($value = null)
{
if (func_num_args() == 0) {
return $this->handleUnconditionally;
}
$this->handleUnconditionally = (bool) $value;
return $this;
}
/**
* Adds an editor resolver.
*
* Either a string, or a closure that resolves a string, that can be used
* to open a given file in an editor. If the string contains the special
* substrings %file or %line, they will be replaced with the correct data.
*
* @example
* $run->addEditor('macvim', "mvim://open?url=file://%file&line=%line")
* @example
* $run->addEditor('remove-it', function($file, $line) {
* unlink($file);
* return "http://stackoverflow.com";
* });
*
* @param string $identifier
* @param string|callable $resolver
*
* @return static
*/
public function addEditor($identifier, $resolver)
{
$this->editors[$identifier] = $resolver;
return $this;
}
/**
* Set the editor to use to open referenced files.
*
* Pass either the name of a configured editor, or a closure that directly
* resolves an editor string.
*
* @example
* $run->setEditor(function($file, $line) { return "file:///{$file}"; });
* @example
* $run->setEditor('sublime');
*
* @param string|callable $editor
*
* @throws InvalidArgumentException If invalid argument identifier provided
*
* @return static
*/
public function setEditor($editor)
{
if (!is_callable($editor) && !isset($this->editors[$editor])) {
throw new InvalidArgumentException(
"Unknown editor identifier: $editor. Known editors:" .
implode(",", array_keys($this->editors))
);
}
$this->editor = $editor;
return $this;
}
/**
* Get the editor href for a given file and line, if available.
*
* @param string $filePath
* @param int $line
*
* @throws InvalidArgumentException If editor resolver does not return a string
*
* @return string|bool
*/
public function getEditorHref($filePath, $line)
{
$editor = $this->getEditor($filePath, $line);
if (empty($editor)) {
return false;
}
// Check that the editor is a string, and replace the
// %line and %file placeholders:
if (!isset($editor['url']) || !is_string($editor['url'])) {
throw new UnexpectedValueException(
__METHOD__ . " should always resolve to a string or a valid editor array; got something else instead."
);
}
$editor['url'] = str_replace("%line", rawurlencode($line), $editor['url']);
$editor['url'] = str_replace("%file", rawurlencode($filePath), $editor['url']);
return $editor['url'];
}
/**
* Determine if the editor link should act as an Ajax request.
*
* @param string $filePath
* @param int $line
*
* @throws UnexpectedValueException If editor resolver does not return a boolean
*
* @return bool
*/
public function getEditorAjax($filePath, $line)
{
$editor = $this->getEditor($filePath, $line);
// Check that the ajax is a bool
if (!isset($editor['ajax']) || !is_bool($editor['ajax'])) {
throw new UnexpectedValueException(
__METHOD__ . " should always resolve to a bool; got something else instead."
);
}
return $editor['ajax'];
}
/**
* Determines both the editor and if ajax should be used.
*
* @param string $filePath
* @param int $line
*
* @return array
*/
protected function getEditor($filePath, $line)
{
if (!$this->editor || (!is_string($this->editor) && !is_callable($this->editor))) {
return [];
}
if (is_string($this->editor) && isset($this->editors[$this->editor]) && !is_callable($this->editors[$this->editor])) {
return [
'ajax' => false,
'url' => $this->editors[$this->editor],
];
}
if (is_callable($this->editor) || (isset($this->editors[$this->editor]) && is_callable($this->editors[$this->editor]))) {
if (is_callable($this->editor)) {
$callback = call_user_func($this->editor, $filePath, $line);
} else {
$callback = call_user_func($this->editors[$this->editor], $filePath, $line);
}
if (empty($callback)) {
return [];
}
if (is_string($callback)) {
return [
'ajax' => false,
'url' => $callback,
];
}
return [
'ajax' => isset($callback['ajax']) ? $callback['ajax'] : false,
'url' => isset($callback['url']) ? $callback['url'] : $callback,
];
}
return [];
}
/**
* Set the page title.
*
* @param string $title
*
* @return static
*/
public function setPageTitle($title)
{
$this->pageTitle = (string) $title;
return $this;
}
/**
* Get the page title.
*
* @return string
*/
public function getPageTitle()
{
return $this->pageTitle;
}
/**
* Adds a path to the list of paths to be searched for resources.
*
* @param string $path
*
* @throws InvalidArgumentException If $path is not a valid directory
*
* @return static
*/
public function addResourcePath($path)
{
if (!is_dir($path)) {
throw new InvalidArgumentException(
"'$path' is not a valid directory"
);
}
array_unshift($this->searchPaths, $path);
return $this;
}
/**
* Adds a custom css file to be loaded.
*
* @param string|null $name
*
* @return static
*/
public function addCustomCss($name)
{
$this->customCss = $name;
return $this;
}
/**
* Adds a custom js file to be loaded.
*
* @param string|null $name
*
* @return static
*/
public function addCustomJs($name)
{
$this->customJs = $name;
return $this;
}
/**
* @return array
*/
public function getResourcePaths()
{
return $this->searchPaths;
}
/**
* Finds a resource, by its relative path, in all available search paths.
*
* The search is performed starting at the last search path, and all the
* way back to the first, enabling a cascading-type system of overrides for
* all resources.
*
* @param string $resource
*
* @throws RuntimeException If resource cannot be found in any of the available paths
*
* @return string
*/
protected function getResource($resource)
{
// If the resource was found before, we can speed things up
// by caching its absolute, resolved path:
if (isset($this->resourceCache[$resource])) {
return $this->resourceCache[$resource];
}
// Search through available search paths, until we find the
// resource we're after:
foreach ($this->searchPaths as $path) {
$fullPath = $path . "/$resource";
if (is_file($fullPath)) {
// Cache the result:
$this->resourceCache[$resource] = $fullPath;
return $fullPath;
}
}
// If we got this far, nothing was found.
throw new RuntimeException(
"Could not find resource '$resource' in any resource paths."
. "(searched: " . join(", ", $this->searchPaths). ")"
);
}
/**
* @deprecated
*
* @return string
*/
public function getResourcesPath()
{
$allPaths = $this->getResourcePaths();
// Compat: return only the first path added
return end($allPaths) ?: null;
}
/**
* @deprecated
*
* @param string $resourcesPath
*
* @return static
*/
public function setResourcesPath($resourcesPath)
{
$this->addResourcePath($resourcesPath);
return $this;
}
/**
* Return the application paths.
*
* @return array
*/
public function getApplicationPaths()
{
return $this->applicationPaths;
}
/**
* Set the application paths.
*
* @return void
*/
public function setApplicationPaths(array $applicationPaths)
{
$this->applicationPaths = $applicationPaths;
}
/**
* Set the application root path.
*
* @param string $applicationRootPath
*
* @return void
*/
public function setApplicationRootPath($applicationRootPath)
{
$this->templateHelper->setApplicationRootPath($applicationRootPath);
}
/**
* blacklist a sensitive value within one of the superglobal arrays.
* Alias for the hideSuperglobalKey method.
*
* @param string $superGlobalName The name of the superglobal array, e.g. '_GET'
* @param string $key The key within the superglobal
* @see hideSuperglobalKey
*
* @return static
*/
public function blacklist($superGlobalName, $key)
{
$this->blacklist[$superGlobalName][] = $key;
return $this;
}
/**
* Hide a sensitive value within one of the superglobal arrays.
*
* @param string $superGlobalName The name of the superglobal array, e.g. '_GET'
* @param string $key The key within the superglobal
* @return static
*/
public function hideSuperglobalKey($superGlobalName, $key)
{
return $this->blacklist($superGlobalName, $key);
}
/**
* Checks all values within the given superGlobal array.
*
* Blacklisted values will be replaced by a equal length string containing
* only '*' characters for string values.
* Non-string values will be replaced with a fixed asterisk count.
* We intentionally dont rely on $GLOBALS as it depends on the 'auto_globals_jit' php.ini setting.
*
* @param array|\ArrayAccess $superGlobal One of the superglobal arrays
* @param string $superGlobalName The name of the superglobal array, e.g. '_GET'
*
* @return array $values without sensitive data
*/
private function masked($superGlobal, $superGlobalName)
{
$blacklisted = $this->blacklist[$superGlobalName];
$values = $superGlobal;
foreach ($blacklisted as $key) {
if (isset($superGlobal[$key])) {
$values[$key] = str_repeat('*', is_string($superGlobal[$key]) ? strlen($superGlobal[$key]) : 3);
}
}
return $values;
}
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/src/Whoops/Util/TemplateHelper.php | src/Whoops/Util/TemplateHelper.php | <?php
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
*/
namespace Whoops\Util;
use Symfony\Component\VarDumper\Caster\Caster;
use Symfony\Component\VarDumper\Cloner\AbstractCloner;
use Symfony\Component\VarDumper\Cloner\VarCloner;
use Symfony\Component\VarDumper\Dumper\HtmlDumper;
use Whoops\Exception\Frame;
/**
* Exposes useful tools for working with/in templates
*/
class TemplateHelper
{
/**
* An array of variables to be passed to all templates
* @var array
*/
private $variables = [];
/**
* @var HtmlDumper
*/
private $htmlDumper;
/**
* @var HtmlDumperOutput
*/
private $htmlDumperOutput;
/**
* @var AbstractCloner
*/
private $cloner;
/**
* @var string
*/
private $applicationRootPath;
public function __construct()
{
// root path for ordinary composer projects
$this->applicationRootPath = dirname(dirname(dirname(dirname(dirname(dirname(__DIR__))))));
}
/**
* Escapes a string for output in an HTML document
*
* @param string $raw
* @return string
*/
public function escape($raw)
{
$flags = ENT_QUOTES;
// HHVM has all constants defined, but only ENT_IGNORE
// works at the moment
if (defined("ENT_SUBSTITUTE") && !defined("HHVM_VERSION")) {
$flags |= ENT_SUBSTITUTE;
} else {
// This is for 5.3.
// The documentation warns of a potential security issue,
// but it seems it does not apply in our case, because
// we do not blacklist anything anywhere.
$flags |= ENT_IGNORE;
}
$raw = str_replace(chr(9), ' ', $raw);
return htmlspecialchars($raw, $flags, "UTF-8");
}
/**
* Escapes a string for output in an HTML document, but preserves
* URIs within it, and converts them to clickable anchor elements.
*
* @param string $raw
* @return string
*/
public function escapeButPreserveUris($raw)
{
$escaped = $this->escape($raw);
return preg_replace(
"@([A-z]+?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@",
"<a href=\"$1\" target=\"_blank\" rel=\"noreferrer noopener\">$1</a>",
$escaped
);
}
/**
* Makes sure that the given string breaks on the delimiter.
*
* @param string $delimiter
* @param string $s
* @return string
*/
public function breakOnDelimiter($delimiter, $s)
{
$parts = explode($delimiter, $s);
foreach ($parts as &$part) {
$part = '<span class="delimiter">' . $part . '</span>';
}
return implode($delimiter, $parts);
}
/**
* Replace the part of the path that all files have in common.
*
* @param string $path
* @return string
*/
public function shorten($path)
{
if ($this->applicationRootPath != "/") {
$path = str_replace($this->applicationRootPath, '…', $path);
}
return $path;
}
private function getDumper()
{
if (!$this->htmlDumper && class_exists('Symfony\Component\VarDumper\Cloner\VarCloner')) {
$this->htmlDumperOutput = new HtmlDumperOutput();
// re-use the same var-dumper instance, so it won't re-render the global styles/scripts on each dump.
$this->htmlDumper = new HtmlDumper($this->htmlDumperOutput);
$styles = [
'default' => 'color:#FFFFFF; line-height:normal; font:12px "Inconsolata", "Fira Mono", "Source Code Pro", Monaco, Consolas, "Lucida Console", monospace !important; word-wrap: break-word; white-space: pre-wrap; position:relative; z-index:99999; word-break: normal',
'num' => 'color:#BCD42A',
'const' => 'color: #4bb1b1;',
'str' => 'color:#BCD42A',
'note' => 'color:#ef7c61',
'ref' => 'color:#A0A0A0',
'public' => 'color:#FFFFFF',
'protected' => 'color:#FFFFFF',
'private' => 'color:#FFFFFF',
'meta' => 'color:#FFFFFF',
'key' => 'color:#BCD42A',
'index' => 'color:#ef7c61',
];
$this->htmlDumper->setStyles($styles);
}
return $this->htmlDumper;
}
/**
* Format the given value into a human readable string.
*
* @param mixed $value
* @return string
*/
public function dump($value)
{
$dumper = $this->getDumper();
if ($dumper) {
// re-use the same DumpOutput instance, so it won't re-render the global styles/scripts on each dump.
// exclude verbose information (e.g. exception stack traces)
if (class_exists('Symfony\Component\VarDumper\Caster\Caster')) {
$cloneVar = $this->getCloner()->cloneVar($value, Caster::EXCLUDE_VERBOSE);
// Symfony VarDumper 2.6 Caster class dont exist.
} else {
$cloneVar = $this->getCloner()->cloneVar($value);
}
$dumper->dump(
$cloneVar,
$this->htmlDumperOutput
);
$output = $this->htmlDumperOutput->getOutput();
$this->htmlDumperOutput->clear();
return $output;
}
return htmlspecialchars(print_r($value, true));
}
/**
* Format the args of the given Frame as a human readable html string
*
* @param Frame $frame
* @return string the rendered html
*/
public function dumpArgs(Frame $frame)
{
// we support frame args only when the optional dumper is available
if (!$this->getDumper()) {
return '';
}
$html = '';
$numFrames = count($frame->getArgs());
if ($numFrames > 0) {
$html = '<ol class="linenums">';
foreach ($frame->getArgs() as $j => $frameArg) {
$html .= '<li>'. $this->dump($frameArg) .'</li>';
}
$html .= '</ol>';
}
return $html;
}
/**
* Convert a string to a slug version of itself
*
* @param string $original
* @return string
*/
public function slug($original)
{
$slug = str_replace(" ", "-", $original);
$slug = preg_replace('/[^\w\d\-\_]/i', '', $slug);
return strtolower($slug);
}
/**
* Given a template path, render it within its own scope. This
* method also accepts an array of additional variables to be
* passed to the template.
*
* @param string $template
*/
public function render($template, ?array $additionalVariables = null)
{
$variables = $this->getVariables();
// Pass the helper to the template:
$variables["tpl"] = $this;
if ($additionalVariables !== null) {
$variables = array_replace($variables, $additionalVariables);
}
call_user_func(function () {
extract(func_get_arg(1));
require func_get_arg(0);
}, $template, $variables);
}
/**
* Sets the variables to be passed to all templates rendered
* by this template helper.
*/
public function setVariables(array $variables)
{
$this->variables = $variables;
}
/**
* Sets a single template variable, by its name:
*
* @param string $variableName
* @param mixed $variableValue
*/
public function setVariable($variableName, $variableValue)
{
$this->variables[$variableName] = $variableValue;
}
/**
* Gets a single template variable, by its name, or
* $defaultValue if the variable does not exist
*
* @param string $variableName
* @param mixed $defaultValue
* @return mixed
*/
public function getVariable($variableName, $defaultValue = null)
{
return isset($this->variables[$variableName]) ?
$this->variables[$variableName] : $defaultValue;
}
/**
* Unsets a single template variable, by its name
*
* @param string $variableName
*/
public function delVariable($variableName)
{
unset($this->variables[$variableName]);
}
/**
* Returns all variables for this helper
*
* @return array
*/
public function getVariables()
{
return $this->variables;
}
/**
* Set the cloner used for dumping variables.
*
* @param AbstractCloner $cloner
*/
public function setCloner($cloner)
{
$this->cloner = $cloner;
}
/**
* Get the cloner used for dumping variables.
*
* @return AbstractCloner
*/
public function getCloner()
{
if (!$this->cloner) {
$this->cloner = new VarCloner();
}
return $this->cloner;
}
/**
* Set the application root path.
*
* @param string $applicationRootPath
*/
public function setApplicationRootPath($applicationRootPath)
{
$this->applicationRootPath = $applicationRootPath;
}
/**
* Return the application root path.
*
* @return string
*/
public function getApplicationRootPath()
{
return $this->applicationRootPath;
}
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/src/Whoops/Util/SystemFacade.php | src/Whoops/Util/SystemFacade.php | <?php
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
*/
namespace Whoops\Util;
class SystemFacade
{
/**
* Turns on output buffering.
*
* @return bool
*/
public function startOutputBuffering()
{
return ob_start();
}
/**
* @param callable $handler
* @param int $types
*
* @return callable|null
*/
public function setErrorHandler(callable $handler, $types = 'use-php-defaults')
{
// Since PHP 5.4 the constant E_ALL contains all errors (even E_STRICT)
if ($types === 'use-php-defaults') {
$types = E_ALL;
}
return set_error_handler($handler, $types);
}
/**
* @param callable $handler
*
* @return callable|null
*/
public function setExceptionHandler(callable $handler)
{
return set_exception_handler($handler);
}
/**
* @return void
*/
public function restoreExceptionHandler()
{
restore_exception_handler();
}
/**
* @return void
*/
public function restoreErrorHandler()
{
restore_error_handler();
}
/**
* @param callable $function
*
* @return void
*/
public function registerShutdownFunction(callable $function)
{
register_shutdown_function($function);
}
/**
* @return string|false
*/
public function cleanOutputBuffer()
{
return ob_get_clean();
}
/**
* @return int
*/
public function getOutputBufferLevel()
{
return ob_get_level();
}
/**
* @return bool
*/
public function endOutputBuffering()
{
return ob_end_clean();
}
/**
* @return void
*/
public function flushOutputBuffer()
{
flush();
}
/**
* @return int
*/
public function getErrorReportingLevel()
{
return error_reporting();
}
/**
* @return array|null
*/
public function getLastError()
{
return error_get_last();
}
/**
* @param int $httpCode
*
* @return int
*/
public function setHttpResponseCode($httpCode)
{
if (!headers_sent()) {
// Ensure that no 'location' header is present as otherwise this
// will override the HTTP code being set here, and mask the
// expected error page.
header_remove('location');
}
return http_response_code($httpCode);
}
/**
* @param int $exitStatus
*/
public function stopExecution($exitStatus)
{
exit($exitStatus);
}
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/src/Whoops/Util/HtmlDumperOutput.php | src/Whoops/Util/HtmlDumperOutput.php | <?php
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
*/
namespace Whoops\Util;
/**
* Used as output callable for Symfony\Component\VarDumper\Dumper\HtmlDumper::dump()
*
* @see TemplateHelper::dump()
*/
class HtmlDumperOutput
{
private $output;
public function __invoke($line, $depth)
{
// A negative depth means "end of dump"
if ($depth >= 0) {
// Adds a two spaces indentation to the line
$this->output .= str_repeat(' ', $depth) . $line . "\n";
}
}
public function getOutput()
{
return $this->output;
}
public function clear()
{
$this->output = null;
}
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/src/Whoops/Util/Misc.php | src/Whoops/Util/Misc.php | <?php
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
*/
namespace Whoops\Util;
class Misc
{
/**
* Can we at this point in time send HTTP headers?
*
* Currently this checks if we are even serving an HTTP request,
* as opposed to running from a command line.
*
* If we are serving an HTTP request, we check if it's not too late.
*
* @return bool
*/
public static function canSendHeaders()
{
return isset($_SERVER["REQUEST_URI"]) && !headers_sent();
}
public static function isAjaxRequest()
{
return (
!empty($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
}
/**
* Check, if possible, that this execution was triggered by a command line.
* @return bool
*/
public static function isCommandLine()
{
return PHP_SAPI == 'cli';
}
/**
* Translate ErrorException code into the represented constant.
*
* @param int $error_code
* @return string
*/
public static function translateErrorCode($error_code)
{
$constants = get_defined_constants(true);
if (array_key_exists('Core', $constants)) {
foreach ($constants['Core'] as $constant => $value) {
if (substr($constant, 0, 2) == 'E_' && $value == $error_code) {
return $constant;
}
}
}
return "E_UNKNOWN";
}
/**
* Determine if an error level is fatal (halts execution)
*
* @param int $level
* @return bool
*/
public static function isLevelFatal($level)
{
$errors = E_ERROR;
$errors |= E_PARSE;
$errors |= E_CORE_ERROR;
$errors |= E_CORE_WARNING;
$errors |= E_COMPILE_ERROR;
$errors |= E_COMPILE_WARNING;
return ($level & $errors) > 0;
}
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/src/Whoops/Exception/Frame.php | src/Whoops/Exception/Frame.php | <?php
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
*/
namespace Whoops\Exception;
use InvalidArgumentException;
use Serializable;
class Frame implements Serializable
{
/**
* @var array
*/
protected $frame;
/**
* @var string
*/
protected $fileContentsCache;
/**
* @var array[]
*/
protected $comments = [];
/**
* @var bool
*/
protected $application;
public function __construct(array $frame)
{
$this->frame = $frame;
}
/**
* @param bool $shortened
* @return string|null
*/
public function getFile($shortened = false)
{
if (empty($this->frame['file'])) {
return null;
}
$file = $this->frame['file'];
// Check if this frame occurred within an eval().
// @todo: This can be made more reliable by checking if we've entered
// eval() in a previous trace, but will need some more work on the upper
// trace collector(s).
if (preg_match('/^(.*)\((\d+)\) : (?:eval\(\)\'d|assert) code$/', $file, $matches)) {
$file = $this->frame['file'] = $matches[1];
$this->frame['line'] = (int) $matches[2];
}
if ($shortened && is_string($file)) {
// Replace the part of the path that all frames have in common, and add 'soft hyphens' for smoother line-breaks.
$dirname = dirname(dirname(dirname(dirname(dirname(dirname(__DIR__))))));
if ($dirname !== '/') {
$file = str_replace($dirname, "…", $file);
}
$file = str_replace("/", "/­", $file);
}
return $file;
}
/**
* @return int|null
*/
public function getLine()
{
return isset($this->frame['line']) ? $this->frame['line'] : null;
}
/**
* @return string|null
*/
public function getClass()
{
return isset($this->frame['class']) ? $this->frame['class'] : null;
}
/**
* @return string|null
*/
public function getFunction()
{
return isset($this->frame['function']) ? $this->frame['function'] : null;
}
/**
* @return array
*/
public function getArgs()
{
return isset($this->frame['args']) ? (array) $this->frame['args'] : [];
}
/**
* Returns the full contents of the file for this frame,
* if it's known.
* @return string|null
*/
public function getFileContents()
{
if ($this->fileContentsCache === null && $filePath = $this->getFile()) {
// Leave the stage early when 'Unknown' or '[internal]' is passed
// this would otherwise raise an exception when
// open_basedir is enabled.
if ($filePath === "Unknown" || $filePath === '[internal]') {
return null;
}
try {
$this->fileContentsCache = file_get_contents($filePath);
} catch (ErrorException $exception) {
// Internal file paths of PHP extensions cannot be opened
}
}
return $this->fileContentsCache;
}
/**
* Adds a comment to this frame, that can be received and
* used by other handlers. For example, the PrettyPage handler
* can attach these comments under the code for each frame.
*
* An interesting use for this would be, for example, code analysis
* & annotations.
*
* @param string $comment
* @param string $context Optional string identifying the origin of the comment
*/
public function addComment($comment, $context = 'global')
{
$this->comments[] = [
'comment' => $comment,
'context' => $context,
];
}
/**
* Returns all comments for this frame. Optionally allows
* a filter to only retrieve comments from a specific
* context.
*
* @param string $filter
* @return array[]
*/
public function getComments($filter = null)
{
$comments = $this->comments;
if ($filter !== null) {
$comments = array_filter($comments, function ($c) use ($filter) {
return $c['context'] == $filter;
});
}
return $comments;
}
/**
* Returns the array containing the raw frame data from which
* this Frame object was built
*
* @return array
*/
public function getRawFrame()
{
return $this->frame;
}
/**
* Returns the contents of the file for this frame as an
* array of lines, and optionally as a clamped range of lines.
*
* NOTE: lines are 0-indexed
*
* @example
* Get all lines for this file
* $frame->getFileLines(); // => array( 0 => '<?php', 1 => '...', ...)
* @example
* Get one line for this file, starting at line 10 (zero-indexed, remember!)
* $frame->getFileLines(9, 1); // array( 9 => '...' )
*
* @throws InvalidArgumentException if $length is less than or equal to 0
* @param int $start
* @param int $length
* @return string[]|null
*/
public function getFileLines($start = 0, $length = null)
{
if (null !== ($contents = $this->getFileContents())) {
$lines = explode("\n", $contents);
// Get a subset of lines from $start to $end
if ($length !== null) {
$start = (int) $start;
$length = (int) $length;
if ($start < 0) {
$start = 0;
}
if ($length <= 0) {
throw new InvalidArgumentException(
"\$length($length) cannot be lower or equal to 0"
);
}
$lines = array_slice($lines, $start, $length, true);
}
return $lines;
}
}
/**
* Implements the Serializable interface, with special
* steps to also save the existing comments.
*
* @see Serializable::serialize
* @return string
*/
public function serialize()
{
$frame = $this->frame;
if (!empty($this->comments)) {
$frame['_comments'] = $this->comments;
}
return serialize($frame);
}
public function __serialize()
{
$frame = $this->frame;
if (!empty($this->comments)) {
$frame['_comments'] = $this->comments;
}
return $frame;
}
/**
* Unserializes the frame data, while also preserving
* any existing comment data.
*
* @see Serializable::unserialize
* @param string $serializedFrame
*/
public function unserialize($serializedFrame)
{
$frame = unserialize($serializedFrame);
if (!empty($frame['_comments'])) {
$this->comments = $frame['_comments'];
unset($frame['_comments']);
}
$this->frame = $frame;
}
public function __unserialize($frame)
{
if (!empty($frame['_comments'])) {
$this->comments = $frame['_comments'];
unset($frame['_comments']);
}
$this->frame = $frame;
}
/**
* Compares Frame against one another
* @param Frame $frame
* @return bool
*/
public function equals(Frame $frame)
{
if (!$this->getFile() || $this->getFile() === 'Unknown' || !$this->getLine()) {
return false;
}
return $frame->getFile() === $this->getFile() && $frame->getLine() === $this->getLine();
}
/**
* Returns whether this frame belongs to the application or not.
*
* @return boolean
*/
public function isApplication()
{
return $this->application;
}
/**
* Mark as an frame belonging to the application.
*
* @param boolean $application
*/
public function setApplication($application)
{
$this->application = $application;
}
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/src/Whoops/Exception/FrameCollection.php | src/Whoops/Exception/FrameCollection.php | <?php
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
*/
namespace Whoops\Exception;
use ArrayAccess;
use ArrayIterator;
use Countable;
use IteratorAggregate;
use ReturnTypeWillChange;
use Serializable;
use UnexpectedValueException;
/**
* Exposes a fluent interface for dealing with an ordered list
* of stack-trace frames.
*/
class FrameCollection implements ArrayAccess, IteratorAggregate, Serializable, Countable
{
/**
* @var array[]
*/
private $frames;
public function __construct(array $frames)
{
$this->frames = array_map(function ($frame) {
return new Frame($frame);
}, $frames);
}
/**
* Filters frames using a callable, returns the same FrameCollection
*
* @param callable $callable
* @return FrameCollection
*/
public function filter($callable)
{
$this->frames = array_values(array_filter($this->frames, $callable));
return $this;
}
/**
* Map the collection of frames
*
* @param callable $callable
* @return FrameCollection
*/
public function map($callable)
{
// Contain the map within a higher-order callable
// that enforces type-correctness for the $callable
$this->frames = array_map(function ($frame) use ($callable) {
$frame = call_user_func($callable, $frame);
if (!$frame instanceof Frame) {
throw new UnexpectedValueException(
"Callable to " . __CLASS__ . "::map must return a Frame object"
);
}
return $frame;
}, $this->frames);
return $this;
}
/**
* Returns an array with all frames, does not affect
* the internal array.
*
* @todo If this gets any more complex than this,
* have getIterator use this method.
* @see FrameCollection::getIterator
* @return array
*/
public function getArray()
{
return $this->frames;
}
/**
* @see IteratorAggregate::getIterator
* @return ArrayIterator
*/
#[ReturnTypeWillChange]
public function getIterator()
{
return new ArrayIterator($this->frames);
}
/**
* @see ArrayAccess::offsetExists
* @param int $offset
*/
#[ReturnTypeWillChange]
public function offsetExists($offset)
{
return isset($this->frames[$offset]);
}
/**
* @see ArrayAccess::offsetGet
* @param int $offset
*/
#[ReturnTypeWillChange]
public function offsetGet($offset)
{
return $this->frames[$offset];
}
/**
* @see ArrayAccess::offsetSet
* @param int $offset
*/
#[ReturnTypeWillChange]
public function offsetSet($offset, $value)
{
throw new \Exception(__CLASS__ . ' is read only');
}
/**
* @see ArrayAccess::offsetUnset
* @param int $offset
*/
#[ReturnTypeWillChange]
public function offsetUnset($offset)
{
throw new \Exception(__CLASS__ . ' is read only');
}
/**
* @see Countable::count
* @return int
*/
#[ReturnTypeWillChange]
public function count()
{
return count($this->frames);
}
/**
* Count the frames that belongs to the application.
*
* @return int
*/
public function countIsApplication()
{
return count(array_filter($this->frames, function (Frame $f) {
return $f->isApplication();
}));
}
/**
* @see Serializable::serialize
* @return string
*/
#[ReturnTypeWillChange]
public function serialize()
{
return serialize($this->frames);
}
/**
* @see Serializable::unserialize
* @param string $serializedFrames
*/
#[ReturnTypeWillChange]
public function unserialize($serializedFrames)
{
$this->frames = unserialize($serializedFrames);
}
public function __serialize()
{
return $this->frames;
}
public function __unserialize(array $serializedFrames)
{
$this->frames = $serializedFrames;
}
/**
* @param Frame[] $frames Array of Frame instances, usually from $e->getPrevious()
*/
public function prependFrames(array $frames)
{
$this->frames = array_merge($frames, $this->frames);
}
/**
* Gets the innermost part of stack trace that is not the same as that of outer exception
*
* @param FrameCollection $parentFrames Outer exception frames to compare tail against
* @return Frame[]
*/
public function topDiff(FrameCollection $parentFrames)
{
$diff = $this->frames;
$parentFrames = $parentFrames->getArray();
$p = count($parentFrames)-1;
for ($i = count($diff)-1; $i >= 0 && $p >= 0; $i--) {
/** @var Frame $tailFrame */
$tailFrame = $diff[$i];
if ($tailFrame->equals($parentFrames[$p])) {
unset($diff[$i]);
}
$p--;
}
return $diff;
}
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.