86 lines
2.2 KiB
PHP
86 lines
2.2 KiB
PHP
<?php
|
|
|
|
namespace App\Lib\PolicySystem;
|
|
|
|
use App\Models\User;
|
|
use Exception;
|
|
use Closure;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
|
|
/**
|
|
* Generic Policiy Static Rules
|
|
*! Rules has to return boolean value
|
|
*/
|
|
abstract class StaticRules
|
|
{
|
|
/**
|
|
* Make a rule closure
|
|
*
|
|
* @param string $rulename
|
|
* @param mixed ...$args
|
|
* @return Closure
|
|
*/
|
|
public static function make(string $rulename, ...$args)
|
|
{
|
|
if (!method_exists(static::class, $rulename)) {
|
|
throw new Exception(sprintf('Unknown rule %s in Policies StaticRules', $rulename));
|
|
}
|
|
return function () use ($rulename, $args) {
|
|
return call_user_func_array([static::class, $rulename], $args);
|
|
};
|
|
}
|
|
|
|
public static function and(array $ruleClosures)
|
|
{
|
|
return function (User $user, Model $model = null) use ($ruleClosures) {
|
|
$nbRules = count($ruleClosures);
|
|
$out = true;
|
|
$i = 0;
|
|
do {
|
|
if (!($out = (self::handle($ruleClosures[$i++], $user, $model) && $out))) {
|
|
break;
|
|
}
|
|
} while ($i < $nbRules);
|
|
return $out;
|
|
};
|
|
}
|
|
|
|
public static function or(array $ruleClosures)
|
|
{
|
|
return function (User $user, Model $model = null) use ($ruleClosures) {
|
|
$nbRules = count($ruleClosures);
|
|
$out = false;
|
|
$i = 0;
|
|
do {
|
|
if ($out = (self::handle($ruleClosures[$i++], $user, $model) || $out)) {
|
|
break;
|
|
}
|
|
} while ($i < $nbRules);
|
|
return $out;
|
|
};
|
|
}
|
|
|
|
public static function handle($rule, User $user, Model $model = null)
|
|
{
|
|
if (is_array($rule)) {
|
|
$nbRule = count($rule);
|
|
$out = false;
|
|
$i = 0;
|
|
while ($i < $nbRule) {
|
|
if ($out = self::handle($rule[$i++], $user, $model)) {
|
|
break;
|
|
}
|
|
}
|
|
return $out;
|
|
}
|
|
if (!is_callable($rule)) {
|
|
throw new Exception('Rule has to ba callable.');
|
|
}
|
|
return (bool)$rule($user, $model);
|
|
}
|
|
|
|
protected static function anyone()
|
|
{
|
|
return true;
|
|
}
|
|
}
|