ldc-dam/app/Rules/HasMinimumRole.php

92 lines
2.1 KiB
PHP
Raw Normal View History

2022-03-28 17:43:52 +02:00
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class HasMinimumRole implements Rule
{
/**
* The minimum role the user must have
* @var integer
*/
protected $minimumRole;
/**
* Ordre permettant une comparaison
* ! EN DUR est n'est pas la value de arcadia puisqu'il n'a pas de sens.
*
* @var array
*/
protected $roles = [
'ADMIN' => 1, 'REDACTEUR' => 2,
'CONTRIBUTEUR' => 3, 'LECTEUR' => 4
];
/**
* Create a new rule instance.
*
* @param string $role
* @throws \ErrorException If role is unknown.
*/
public function __construct(string $role)
{
if (!in_array(\intval($role), \array_keys($this->roles))) {
throw new \ErrorException("Unknown role $role");
}
$this->minimumRole = \intval($this->roles[$role]);
}
/**
* Convert Arcadia role to usable roles
*
* 1 (ADMIN) => 1
* 2 (LECTEUR) => 4
* 3 (ADMIN) => 3
* 4 (REDACTEUR) => 2
*
* Donc :
* 1 (ADMIN)
* 2 (REDACTEUR)
* 3 (ADMIN)
* 4 (LECTEUR)
*
* @param integer $value
* @return integer
*/
private function translateRoleValue(int $value): int
{
$translation = [2 => 4, 4 => 2];
return in_array($value, $translation) ? $translation[$value] : $value;
}
/**
* Determine if the validation rule passes.
*
* @param mixed $attribute
* @param mixed $value
* @return boolean
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInImplementedInterfaceBeforeLastUsed
* @phpcs:disable Squiz.Commenting.FunctionComment.TypeHintMissing
2022-03-28 17:43:52 +02:00
*/
public function passes($attribute, $value)
{
// phpcs:enable
2022-03-28 17:43:52 +02:00
if (!\ctype_digit(strval($value))) {
return false;
};
return $this->translateRoleValue(\intval($value)) <= $this->minimumRole;
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'L\'attribut :attribute :input n\'est pas suffisament élevé.';
}
}