jcfrane / policy
A simple and naive policy implementation
Installs: 7
Dependents: 0
Suggesters: 0
Security: 0
Stars: 2
Watchers: 2
Forks: 0
Open Issues: 0
Type:project
Requires
- php: >=7.0
Requires (Dev)
- phpunit/phpunit: ^5.2
This package is not auto-updated.
Last update: 2024-09-26 17:21:07 UTC
README
A naive and simple implementation for Policy classes.
Benefits
- Avoid nested if's in your code.
- Aggregate conditional logic in once place.
How to use?
Create a class that extends AbstractPolicy
use JcFrane\Policy\AbstractPolicy; class BlogPolicy extends AbstractPolicy { }
Create methods inside the your Policy class that represent each conditional logic for the said policy.
use JcFrane\Policy\AbstractPolicy; class BlogPolicy extends AbstractPolicy { public function canCreate($subject) { $this->allow($subject->canCreate, 'Cannot create a subject.'); } public function canView($subject) { $this->allow($subject->canView, 'Cannot view the subject.'); } public function canDelete($subject) { $this->forbid($subject->canDelete, 'Cannot delete the subject.'); } public function canUpdate($subject) { $this->forbid($subject->canUpdate, 'Cannot update the subject'); } }
Evaluate your Policy Class
use JcFrane\Polcy\PolicyChecker; use Some\Namespace\BlogPolicy; $checker = new PolicyChecker(); $subject = new \stdClass(); $subject->canCreate = true; $subject->canView = false; $subject->canDelete = true; $subject->canUpdate = false; $result = $checker->check(BlogPolicy::class, $subject, 'create'); // returns true $result = $checker->check(BlogPolicy::class, $subject, 'view'); // throws JcFrane/PolicyViolationException $result = $checker->check(BlogPolicy::class, $subject, 'delete'); // returns true $result = $checker->check(BlogPolicy::class, $subject, 'update'); // throws JcFrane/PolicyViolationException
That's it! You can now create multiple policy classes that aggregates your conditional logic inside your code.
The allow() and forbid() methods
The allow() accepts a boolean and a violation message. If first argument is true, then the check() will return true. Otherwise, will throw a ViolationException.
The forbid() accepts a boolean and a violation message. If first argument is false, then the check() will throw a ViolationException. Otherwise, will return true.
Installation
$ composer install jcfrane/policy