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

[1.x] Gracefully handles unexpected null scope #31

Merged
merged 4 commits into from
Feb 15, 2023
Merged

[1.x] Gracefully handles unexpected null scope #31

merged 4 commits into from
Feb 15, 2023

Conversation

timacdonald
Copy link
Member

@timacdonald timacdonald commented Feb 14, 2023

This PR gracefully handles null scope when a feature definition / resolver has a non-nullable type declaration.

Feature::define('api-beta', fn (User $user) => true);

Auth::logout();

Feature::active('api-beta');

Instead of throwing a type exception when checking if the feature is active, we will now return false and dispatch the Laravel\Pennant\Events\UnexpectedNullScopeEncountered event.

This is a sensible default and is functionality already present in Laravel Authorisation Guards.

If an app wants to opt-out of this behaviour:

use Laravel\Pennant\Events\UnexpectedNullScopeEncountered;

Event::listen(UnexpectedNullScopeEncountered::class, fn () => abort(500));

Comment on lines 111 to 114
[$feature, $resolver] = with($this->container[$feature], fn ($featureClass) => [
$featureClass->name ?? $feature,
method_exists($featureClass, 'resolve') ? $featureClass->resolve(...) : $featureClass(...),
]);
Copy link
Member Author

@timacdonald timacdonald Feb 15, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This change means that the feature class stays in-memory once it is defined and isn't re-resolved each time it is checked (it was already being resolved here, however we didn't hold onto it, so it was garbage collected).

Depending on the context, this may actually be a performance gain, as the class isn't being re-resolved everytime the feature is checked - however this would probably have no real-world impact.

It is only really a concern if the user is mutating the class each time it is invoked - but there is an event for doing that kind of thing outside of the feature class.

@timacdonald timacdonald marked this pull request as ready for review February 15, 2023 00:21
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.

2 participants