2017 © Pedro Peláez
 

project policy

A simple and naive policy implementation

image

jcfrane/policy

A simple and naive policy implementation

  • Friday, May 11, 2018
  • by jcfrane
  • Repository
  • 1 Watchers
  • 2 Stars
  • 2 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 0 Forks
  • 0 Open issues
  • 2 Versions
  • 0 % Grown

The README.md

Policy

A naive and simple implementation for Policy classes., (*1)

Benefits

  • Avoid nested if's in your code.
  • Aggregate conditional logic in once place.

How to use?

Create a class that extends AbstractPolicy, (*2)

use JcFrane\Policy\AbstractPolicy;

class BlogPolicy extends AbstractPolicy
{

}

Create methods inside the your Policy class that represent each conditional logic for the said policy., (*3)

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, (*4)


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., (*5)

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., (*6)

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., (*7)

Installation

$ composer install jcfrane/policy

The Versions

11/05 2018

dev-master

9999999-dev

A simple and naive policy implementation

  Sources   Download

MIT

The Requires

  • php >=7.0

 

The Development Requires

by JC Frane

php policy

28/03 2018

v0.1.0

0.1.0.0

A simple and naive policy implementation

  Sources   Download

MIT

The Requires

  • php >=7.0

 

The Development Requires

by JC Frane

php policy