VOOZH about

URL: https://deepwiki.com/hypervel/auth/2.3.4-guardhelpers-trait

⇱ GuardHelpers Trait | hypervel/auth | DeepWiki


Loading...
Menu

GuardHelpers Trait

Purpose and Scope

The GuardHelpers trait provides shared functionality that is common across all guard implementations in the authentication system. It implements core guard operations such as user verification, credential validation, and user provider management, eliminating code duplication between different guard types.

This document covers the reusable methods provided by the trait. For information about specific guard implementations that use this trait, see Guards. For the guard contracts that define the required interface methods, see Guard Contracts. For user provider operations referenced by this trait, see User Providers.

Sources: src/Guards/GuardHelpers.php1-115


Overview

The GuardHelpers trait contains methods that are typically identical across all guard implementations (JWT, Session, and Request guards). By extracting these methods into a shared trait, the codebase avoids duplication and ensures consistent behavior across guard types.

The trait assumes that any class using it will:

  • Implement the user() method that returns the currently authenticated user
  • Implement the login() method for stateful guards (optional, only used by loginUsingId())
  • Implement the attempt() method for credential-based authentication (optional, only used by validate())
  • Have a $provider property of type UserProvider

Sources: src/Guards/GuardHelpers.php11-14


Method Categories

The trait methods can be organized into four functional categories:

CategoryMethodsPurpose
User Status Checkscheck(), guest(), hasUser()Determine authentication state without throwing exceptions
User Retrievalauthenticate(), id()Retrieve authenticated user or identifier, with exception handling
Provider ManagementgetProvider(), setProvider()Access and configure the underlying user provider
Credential Operationsvalidate(), hasValidCredentials(), loginUsingId()Handle credential validation and login operations

Sources: src/Guards/GuardHelpers.php1-115


Method Dependency Graph


This diagram shows the method call relationships within the trait. Methods in the "Required by Implementing Class" section must be provided by guard implementations, while "External Dependencies" are injected or imported.

Sources: src/Guards/GuardHelpers.php1-115


User Status Check Methods

check()

Determines if a user is currently authenticated by checking if the user() method returns a non-null value.


Returns: true if authenticated, false otherwise

Implementation: src/Guards/GuardHelpers.php77-80

Usage Pattern:



guest()

Determines if the current user is a guest (not authenticated). This is the inverse of check().


Returns: true if user is a guest (not authenticated), false if authenticated

Implementation: src/Guards/GuardHelpers.php41-44

Usage Pattern:



hasUser()

Determines if the guard has a user instance cached or available. This is functionally equivalent to check() but provides clearer semantic meaning when checking for user existence rather than authentication status.


Returns: true if a user instance exists, false otherwise

Implementation: src/Guards/GuardHelpers.php33-36

Sources: src/Guards/GuardHelpers.php31-80


User Retrieval Methods

authenticate()

Retrieves the currently authenticated user or throws an AuthenticationException if no user is authenticated. This method is used when authentication is required and should fail loudly if unavailable.


Returns: The authenticated Authenticatable user instance

Throws: AuthenticationException when no user is authenticated

Implementation: src/Guards/GuardHelpers.php21-28

Usage Pattern:



id()

Retrieves the unique identifier for the currently authenticated user. Returns null if no user is authenticated.


Returns: User identifier (typically integer or string), or null if not authenticated

Implementation: src/Guards/GuardHelpers.php49-56

The method calls getAuthIdentifier() on the user instance, which is defined by the Authenticatable contract. See Authenticatable Contract for more details.

Sources: src/Guards/GuardHelpers.php17-56


Authentication Flow


This sequence diagram illustrates how the three primary authentication check methods (check(), authenticate(), and id()) interact with the underlying user() method and handle different authentication states.

Sources: src/Guards/GuardHelpers.php21-80


Provider Management Methods

getProvider()

Retrieves the user provider instance currently used by the guard. User providers are responsible for retrieving user records from storage.


Returns: The UserProvider instance

Implementation: src/Guards/GuardHelpers.php61-64


setProvider()

Sets a new user provider for the guard. This allows runtime reconfiguration of user storage mechanisms.


Parameters:

  • $provider: The new UserProvider instance to use

Implementation: src/Guards/GuardHelpers.php69-72

Usage Pattern:


Sources: src/Guards/GuardHelpers.php59-72


Credential Operations

validate()

Validates user credentials without establishing an authentication session. This is useful for verification purposes without actually logging in the user.


Parameters:

  • $credentials: Array of credential data (typically including username/email and password)

Returns: true if credentials are valid, false otherwise

Implementation: src/Guards/GuardHelpers.php99-102

The method delegates to the attempt() method with the second parameter set to false, indicating that authentication should be validated but not persisted. The implementing guard class must provide the attempt() method.


loginUsingId()

Logs in a user by their unique identifier without requiring credentials. This is useful for features like "remember me" tokens or administrative user impersonation.


Parameters:

  • $id: The unique identifier of the user to authenticate

Returns: The Authenticatable user instance on success, false if user not found

Implementation: src/Guards/GuardHelpers.php85-94

Behavior:

  1. Retrieves the user from the provider using retrieveById()
  2. If found, calls the guard's login() method to establish authentication
  3. Returns the user instance on success, or false if user doesn't exist

hasValidCredentials()

Protected helper method that validates whether a user matches the provided credentials. This is used internally by guards during authentication attempts.


Parameters:

  • $user: The user instance to validate (can be null)
  • $credentials: Array of credential data to validate against

Returns: true if credentials match, false otherwise

Implementation: src/Guards/GuardHelpers.php107-114

The method delegates validation to the user provider's validateCredentials() method, which typically compares hashed passwords. See User Providers for details on credential validation.

Sources: src/Guards/GuardHelpers.php85-114


Credential Validation Flow


This flowchart shows how credential operations flow through the trait methods, the guard's implementation methods, and the user provider's validation methods.

Sources: src/Guards/GuardHelpers.php85-114


Integration with Guard Implementations

The GuardHelpers trait is used by all guard implementations in the authentication system. Each guard class includes the trait and implements the required abstract methods.

Required Methods

Guards using this trait must implement:

MethodSignatureUsed By Trait Methods
user()user(): ?Authenticatablecheck(), guest(), hasUser(), authenticate(), id()
login()login(Authenticatable $user): voidloginUsingId()
attempt()attempt(array $credentials, bool $login): boolvalidate()

Note: The login() and attempt() methods are only required if the guard supports those operations. Stateless guards like JwtGuard may not implement login(), and callback-based guards like RequestGuard may not implement attempt().

Property Requirements

The trait expects the implementing class to have:

  • protected UserProvider $provider - The user provider instance

Sources: src/Guards/GuardHelpers.php11-14


Guard Implementation Matrix


This diagram shows how the trait is used by different guard implementations and how they relate to the guard contracts. All guards use GuardHelpers to avoid code duplication.

Sources: src/Guards/GuardHelpers.php1-115


Method Summary Table

MethodVisibilityReturn TypeThrowsPurpose
authenticate()publicAuthenticatableAuthenticationExceptionGet user or throw exception
hasUser()publicbool-Check if user instance exists
guest()publicbool-Check if current user is guest
id()publicint|string|null-Get authenticated user ID
getProvider()publicUserProvider-Get current user provider
setProvider()publicvoid-Set new user provider
check()publicbool-Check if user is authenticated
loginUsingId()publicAuthenticatable|bool-Login user by ID
validate()publicbool-Validate credentials without login
hasValidCredentials()protectedbool-Internal credential validation

Sources: src/Guards/GuardHelpers.php1-115


Dependencies

The trait has the following dependencies:

Imported Classes

  • Hypervel\Auth\AuthenticationException - Thrown when authentication is required but fails
  • Hypervel\Auth\Contracts\Authenticatable - The user entity contract
  • Hypervel\Auth\Contracts\UserProvider - The user data retrieval contract

Sources: src/Guards/GuardHelpers.php7-9

External Method Calls

The trait makes calls to:

  • $this->user() - Must be implemented by guard (returns current authenticated user)
  • $this->login() - Must be implemented by stateful guards
  • $this->attempt() - Must be implemented by credential-supporting guards
  • $this->provider->retrieveById() - User provider method for ID-based retrieval
  • $this->provider->validateCredentials() - User provider method for credential validation
  • $user->getAuthIdentifier() - Authenticatable contract method for getting user ID

Sources: src/Guards/GuardHelpers.php1-115


Usage Considerations

Stateless vs Stateful Guards

The loginUsingId() method relies on the login() method, which is only available in stateful guards. Stateless guards like JwtGuard that don't maintain session state can still use this trait, but calling loginUsingId() may not behave as expected.

For guard type differences, see Guards.

Credential Validation

The validate() and hasValidCredentials() methods delegate to the user provider for actual credential verification. The provider typically uses the hashing service to compare password hashes securely.

For more information on credential validation, see User Providers.

Exception Handling

Only the authenticate() method throws an exception (AuthenticationException). All other methods return boolean values or null, allowing calling code to handle authentication failures gracefully.

For exception handling strategies, see AuthenticationException.

Sources: src/Guards/GuardHelpers.php1-115


Implementation Notes

PHPStan Suppression

The trait includes a PHPStan ignore comment at line 88 for the login() method call. This is because the trait cannot guarantee that implementing classes have this method (callback-based guards may not support login operations). The implementing class is responsible for ensuring the method exists if loginUsingId() is called.

Location: src/Guards/GuardHelpers.php88

Null Safety

All user-dependent methods safely handle null values returned by user(). Methods like check(), guest(), and hasUser() use null checks rather than exceptions, providing flexible authentication state queries.

Provider Dependency

The trait assumes a $provider property exists on the implementing class. This property must be initialized before any provider-dependent methods (loginUsingId(), hasValidCredentials()) are called.

Sources: src/Guards/GuardHelpers.php1-115