Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[2.x] Add HasApiTokens contract to complement trait #270

Merged
merged 2 commits into from
Apr 16, 2021
Merged

[2.x] Add HasApiTokens contract to complement trait #270

merged 2 commits into from
Apr 16, 2021

Conversation

wimski
Copy link
Contributor

@wimski wimski commented Apr 16, 2021

In a recent project using Sanctum I wanted to check if the User/Model/Authenticatable/whatever uses the HasApiTokens trait. Currently this can only be achieved by one of the following options:

// A. check trait usage
if (! in_array(HasApiTokens::class, class_uses($user)) {
    throw new Exception();
}

// B. check method existence
if (! method_exists($user, 'currentAccessToken')) {
    throw new Exception();
}
  • Option A will work, but static analysis will not understand that $user has a specific set of methods.
  • Option B does support static analysis, but is messy, because it doesn't really check for the trait (or specific contract).

Therefore I've added a contract to complement the trait.

use Laravel\Sanctum\Contracts\HasApiTokens as HasApiTokensContract;

if (! $user instanceof HasApiTokensContract::class) {
    throw new Exception();
}

This contract is not required for general use of Sanctum and is not a breaking change.

@wimski wimski marked this pull request as ready for review April 16, 2021 09:54
@wimski wimski changed the title Add HasApiTokens contract to complement trait [2.x] Add HasApiTokens contract to complement trait Apr 16, 2021
@taylorotwell taylorotwell merged commit 84f02a7 into laravel:2.x Apr 16, 2021
@wimski
Copy link
Contributor Author

wimski commented Apr 19, 2021

Thanks for merging!

When can I expect the next release containing this merge?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants