-
Notifications
You must be signed in to change notification settings - Fork 101
/
Copy pathSecurity.php
81 lines (68 loc) · 2.48 KB
/
Security.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
declare(strict_types=1);
namespace TheCodingMachine\GraphQLite\Annotations;
use Attribute;
use BadMethodCallException;
use function array_key_exists;
use function is_string;
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)]
class Security implements MiddlewareAnnotationInterface
{
/** @var string */
private $expression;
/** @var mixed */
private $failWith;
/** @var bool */
private $failWithIsSet = false;
/** @var int */
private $statusCode;
/** @var string */
private $message;
/**
* @param array<string, mixed>|string $data data array managed by the Doctrine Annotations library or the expression
*
* @throws BadMethodCallException
*/
public function __construct(array|string $data = [], string|null $expression = null, mixed $failWith = '__fail__with__magic__key__', string|null $message = null, int|null $statusCode = null)
{
if (is_string($data)) {
$data = ['expression' => $data];
}
$this->expression = $data['value'] ?? $data['expression'] ?? $expression;
if (! $this->expression) {
throw new BadMethodCallException('The #[Security] attribute must be passed an expression. For instance: "#[Security("is_granted(\'CAN_EDIT_STUFF\')")]"');
}
if (array_key_exists('failWith', $data)) {
$this->failWith = $data['failWith'];
$this->failWithIsSet = true;
} elseif ($failWith !== '__fail__with__magic__key__') {
$this->failWith = $failWith;
$this->failWithIsSet = true;
}
$this->message = $message ?? $data['message'] ?? 'Access denied.';
$this->statusCode = $statusCode ?? $data['statusCode'] ?? 403;
if ($this->failWithIsSet === true && (($message || isset($data['message'])) || ($statusCode || isset($data['statusCode'])))) {
throw new BadMethodCallException('A #[Security] attribute that has "failWith" attribute set cannot have a message or a statusCode attribute.');
}
}
public function getExpression(): string
{
return $this->expression;
}
public function isFailWithSet(): bool
{
return $this->failWithIsSet;
}
public function getFailWith(): mixed
{
return $this->failWith;
}
public function getStatusCode(): int
{
return $this->statusCode;
}
public function getMessage(): string
{
return $this->message;
}
}