- First commit

This commit is contained in:
Dave Mc Nicoll 2021-08-27 18:08:35 +00:00
commit 2845badd40
5 changed files with 124 additions and 0 deletions

17
composer.json Normal file
View File

@ -0,0 +1,17 @@
{
"name": "mcnd/taxus",
"description": "A simple privilege library to handle an application's permissions.",
"keywords": ["mcnd","privilege","permission","taxus"],
"license": "MIT",
"authors": [
{
"name": "Dave Mc Nicoll",
"email": "dave.mcnicoll@cslsj.qc.ca"
}
],
"autoload": {
"psr-4": {
"Taxus\\": "src/"
}
}
}

View File

@ -0,0 +1,8 @@
<?php
namespace Taxus;
interface PermissionGrantInterface
{
}

27
src/Privilege.php Normal file
View File

@ -0,0 +1,27 @@
<?php
namespace Taxus;
class Privilege
{
public string $name;
public string $description;
public /* string|Callable|null */ $error;
public $success;
public $function;
public ? bool $granted = false;
public function __construct(string $name, string $description = "", ? Callable $function = null, ? Callable $success = null, ? Callable $error = null)
{
$this->name = $name;
$this->description = $description;
$this->function = $function;
$this->success = $success;
$this->error = $error;
}
}

50
src/Taxus.php Normal file
View File

@ -0,0 +1,50 @@
<?php
namespace Taxus;
class Taxus
{
protected PermissionGrantInterface $gate;
public function __construct(PermissionGrantInterface $gate)
{
$this->gate = $gate;
}
/**
* @var array
*/
protected $list;
public function add(...$privileges) : self
{
foreach($privileges as $item) {
$item = (array) $item;
if ( ! $item[0] instanceof Privilege ) {
throw new \InvalidArgumentException("First element must be an instance of '" . Privilege::class . "'");
}
if ( ( $item[1] ?? false ) && ! is_string($item[1]) ) {
throw new \InvalidArgumentException("Second element must be a callable function from your Permission Handler");
}
$this->list[ $item[0]->name ] = $item;
}
return $this;
}
public function granted($name, ...$arguments) : bool
{
if ( ! isset($this->list[$name]) ) {
throw new \InvalidArgumentException("Privilege '{$name}' could not be found. Did you forgot to add it to your Taxus object ?");
}
$obj = $this->list[$name][0];
$callback = $this->list[$name][1] ?? 'default';
return $this->gate->$callback(...$arguments);
}
}

22
src/UserEntityTrait.php Normal file
View File

@ -0,0 +1,22 @@
<?php
namespace Taxus;
trait UserEntityTrait
{
public ? Taxus $taxus;
public function can(string $privilegeName, ...$arguments) : bool
{
if (! $this->taxus) {
throw new \Exception("An instance of Taxus must be linked to this object.");
}
return $this->taxus->granted($privilegeName, ...$arguments);
}
public function cannot(string $privilegeName, ...$arguments) : bool
{
return ! $this->can($privilegeName, ...$arguments);
}
}