feat: Add #[UsePolicy] attribute for declarative policy binding
#328
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
This PR ports Laravel's
#[UsePolicy]attribute to Hypervel, allowing models to declare their authorization policy class using a PHP attribute instead of manual registration.Changes
New Files
src/core/src/Database/Eloquent/Attributes/UsePolicy.php- The attribute class that can be applied to model classes to declare their policyModified Files
src/auth/src/Access/Gate.php- AddedgetPolicyFromAttribute()method and updatedgetPolicyFor()to check for the attributeTest Files
tests/Auth/Access/GateTest.php- Added 5 new test casestests/Auth/Stub/DummyWithUsePolicy.php- Test model with attributetests/Auth/Stub/DummyWithUsePolicyPolicy.php- Test policy classtests/Auth/Stub/DummyWithoutUsePolicy.php- Test model without attributetests/Auth/Stub/SubDummyWithUsePolicy.php- Test subclass with attributeUsage
The Gate will now automatically resolve
PostPolicywhen authorizing actions onPostmodels:Policy Resolution Order
Gate::policy(Post::class, PostPolicy::class)takes precedence#[UsePolicy]attribute - Checked if no explicit policy is registeredKey Differences from
#[ObservedBy]/#[ScopedBy]ObservedBy/ScopedByUsePolicyThe
#[UsePolicy]attribute is simpler because the Gate reads the attribute via reflection at authorization time - no model trait or boot mechanism is required.Test Plan
#[UsePolicy]attribute