VOOZH about

URL: https://deepwiki.com/hypervel/auth/5.6-gate-contract

⇱ Gate Contract | hypervel/auth | DeepWiki


Loading...
Menu

Gate Contract

The Gate Contract (Hypervel\Auth\Contracts\Gate) defines the interface for the authorization gate system in hypervel/auth. This contract specifies the methods that any gate implementation must provide for managing abilities, policies, authorization checks, and callback hooks.

For information about the concrete Gate implementation and its internal behavior, see Gate. For details on how policies work with the gate, see Policies and Abilities. For the authorization response object returned by gate methods, see Authorization Responses.

Sources: src/Access/Gate.php24 src/ConfigProvider.php10-22


Contract Overview

The Gate Contract serves as the central authorization interface for the package. It defines methods for:

  • Ability Definition - Registering authorization checks as named abilities
  • Policy Registration - Mapping model classes to policy classes
  • Authorization Checks - Evaluating whether actions are allowed or denied
  • Callback Hooks - Registering before/after hooks for all checks
  • Inspection - Examining authorization results without throwing exceptions

Implementations of this contract must integrate with the user resolver to obtain the current authenticated user and evaluate authorization logic through abilities and policies.

Sources: src/Access/Gate.php24-56 src/ConfigProvider.php22


Container Registration

The Gate Contract is bound in the dependency injection container via GateFactory:


Sources: src/ConfigProvider.php15-33


Contract Method Categories

Ability Check Methods

These methods evaluate authorization for one or more abilities:

MethodReturn TypeDescription
allows(string $ability, mixed $arguments)boolCheck if ability is granted
denies(string $ability, mixed $arguments)boolCheck if ability is denied
check(iterable|string $abilities, mixed $arguments)boolCheck all abilities pass
any(iterable|string $abilities, mixed $arguments)boolCheck any ability passes
none(iterable|string $abilities, mixed $arguments)boolCheck all abilities fail
authorize(string $ability, mixed $arguments)ResponseAuthorize or throw exception
inspect(string $ability, mixed $arguments)ResponseInspect authorization result
raw(string $ability, mixed $arguments)mixedGet raw callback result

Sources: src/Access/Gate.php230-334


Ability Definition Methods

These methods register authorization logic:

MethodReturn TypeDescription
has(array|string $ability)boolCheck if ability is defined
define(string $ability, callable|string $callback)staticDefine single ability
resource(string $name, string $class, ?array $abilities)staticDefine resource abilities

The define() method accepts three callback formats:

  • Callable: Direct function/closure
  • Class@method: String notation
  • [ClassName::class, 'method']: Array notation

Sources: src/Access/Gate.php61-160


Policy Management Methods

These methods handle policy registration and resolution:

MethodReturn TypeDescription
policy(string $class, string $policy)staticRegister policy for class
getPolicyFor(object|string $class)mixedGet policy instance for class
resolvePolicy(string $class)mixedResolve policy from container

Sources: src/Access/Gate.php200-540


Callback Hook Methods

These methods register global hooks that run before/after all authorization checks:

MethodReturn TypeDescription
before(callable $callback)staticRegister before callback
after(callable $callback)staticRegister after callback

Sources: src/Access/Gate.php208-225


Configuration Methods

These methods manage gate configuration and state:

MethodReturn TypeDescription
forUser(?Authenticatable $user)staticCreate gate for specific user
abilities()arrayGet all defined abilities
policies()arrayGet all registered policies
defaultDenialResponse(Response $response)staticSet default denial response

Sources: src/Access/Gate.php625-671


On-Demand Authorization Methods

These methods provide conditional authorization without pre-defined abilities:

MethodReturn TypeDescription
allowIf(bool|Closure|Response $condition, ?string $message, ?string $code)ResponseAllow if condition true
denyIf(bool|Closure|Response $condition, ?string $message, ?string $code)ResponseDeny if condition true

Sources: src/Access/Gate.php79-116


Authorization Flow Through Contract


Sources: src/Access/Gate.php274-334 src/Access/Gate.php400-482


Guest User Handling

The Gate Contract implementation must handle cases where no user is authenticated (guest users). The contract defines behavior for guest access through parameter inspection:


Methods like canBeCalledWithUser(), methodAllowsGuests(), callbackAllowsGuests(), and parameterAllowsGuests() inspect callback signatures to determine if they can be invoked with a null user.

Sources: src/Access/Gate.php339-395 src/Access/Gate.php580-612


Policy Resolution Strategy

The Gate Contract defines a three-tier policy resolution strategy:


Policy Resolution Order:

  1. Direct Registration: Check $policies array for exact class match
  2. Attribute Discovery: Check for UsePolicy attribute on the class
  3. Parent Class Matching: Check if class extends any registered policy class

Sources: src/Access/Gate.php490-540


Ability Callback Resolution

The Gate Contract implementation resolves authorization callbacks using this precedence:


Sources: src/Access/Gate.php460-482 src/Access/Gate.php545-573


Response Types

Gate Contract methods return different types based on their purpose:

Method CategoryReturn TypeThrows ExceptionUse Case
allows(), denies(), check(), any(), none()boolNoSimple boolean checks
authorize()ResponseYes (on deny)Controller/middleware enforcement
inspect()ResponseNoExamine result with metadata
raw()mixedDepends on callbackAccess raw callback return value
allowIf(), denyIf()ResponseYes (based on condition)On-demand conditional checks

Sources: src/Access/Gate.php230-297


Implementation Requirements

Classes implementing the Gate Contract must:

  1. User Resolution: Accept a Closure user resolver in constructor that returns ?Authenticatable
  2. Container Integration: Accept ContainerInterface for resolving policy instances
  3. State Management: Maintain arrays for abilities, policies, before callbacks, and after callbacks
  4. Event Dispatching: Dispatch GateEvaluated events after each authorization check
  5. Fluent Interface: Return static from configuration methods for method chaining
  6. Guest Support: Inspect callback signatures to determine guest access eligibility
  7. Response Handling: Convert boolean/null results to Response objects with appropriate metadata

Sources: src/Access/Gate.php48-56 src/Access/Gate.php446-455


Key Contract Methods Detail

define(string $ability, callable|string $callback): static

Registers an authorization ability. Accepts three formats:

  • Direct callable: fn($user, $post) => $user->id === $post->author_id
  • Class@method string: 'PostPolicy@update'
  • Array callback: [PostPolicy::class, 'update']

String callbacks are stored separately in $stringCallbacks and converted to closures that resolve the policy, call before(), then call the method.

Sources: src/Access/Gate.php123-140 src/Access/Gate.php165-195


resource(string $name, string $class, ?array $abilities): static

Convenience method for defining standard CRUD abilities for a resource:


Default abilities: viewAny, view, create, update, delete. Custom abilities can be provided via third parameter.

Sources: src/Access/Gate.php145-160


raw(string $ability, mixed $arguments): mixed

Returns the raw result from authorization callbacks without wrapping in Response:

  1. Resolves the current user via $userResolver
  2. Calls all before callbacks - returns first non-null result
  3. If no before result, calls the ability/policy callback via callAuthCallback()
  4. Calls all after callbacks - uses their result if original was null
  5. Dispatches GateEvaluated event
  6. Returns raw result (bool, Response, null, or any callback return)

Sources: src/Access/Gate.php304-334


inspect(string $ability, mixed $arguments): Response

Evaluates authorization and returns a Response object without throwing exceptions:


Wraps raw() result: converts booleans to Response::allow()/Response::deny(), passes through existing Response objects, and catches AuthorizationException to convert to denied response.

Sources: src/Access/Gate.php282-297


forUser(?Authenticatable $user): static

Creates a new Gate instance for a specific user without modifying the current gate:


Creates new instance with same container, abilities, policies, and callbacks, but different user resolver that returns the specified user.

Sources: src/Access/Gate.php625-637


Integration with Other Components


Sources: src/Access/Gate.php48-56 src/ConfigProvider.php18-22


Thread Safety and Context

Gate implementations must be stateless regarding per-request data. The user is resolved dynamically via the $userResolver closure on each authorization check, allowing the gate to work correctly in:

  • Coroutine contexts: Each coroutine maintains its own context with a different authenticated user
  • CLI commands: Where no HTTP request exists
  • Queue workers: Processing jobs with different user contexts

The gate stores only configuration (abilities, policies, callbacks) and resolves the current user on-demand.

Sources: src/Access/Gate.php642-645