Skip to content

Commit 65da08b

Browse files
authored
Merge pull request #29 from moufmouf/php8annotations
Making Validate annotation available as a PHP8 attribute
2 parents 1bf377a + 4f5ddaf commit 65da08b

File tree

2 files changed

+17
-7
lines changed

2 files changed

+17
-7
lines changed

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@
4444
},
4545
"extra": {
4646
"branch-alias": {
47-
"dev-master": "4.0.x-dev"
47+
"dev-master": "4.1.x-dev"
4848
},
4949
"laravel": {
5050
"providers": [

src/Annotations/Validate.php

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,11 @@
44

55
namespace TheCodingMachine\GraphQLite\Laravel\Annotations;
66

7+
use Attribute;
78
use BadMethodCallException;
89
use TheCodingMachine\GraphQLite\Annotations\MiddlewareAnnotationInterface;
910
use TheCodingMachine\GraphQLite\Annotations\ParameterAnnotationInterface;
11+
use function is_string;
1012
use function ltrim;
1113

1214
/**
@@ -19,6 +21,7 @@
1921
* @Attribute("rule", type = "string")
2022
* })
2123
*/
24+
#[Attribute(Attribute::TARGET_PARAMETER)]
2225
class Validate implements ParameterAnnotationInterface
2326
{
2427
/** @var string */
@@ -29,20 +32,27 @@ class Validate implements ParameterAnnotationInterface
2932
/**
3033
* @param array<string, mixed> $values
3134
*/
32-
public function __construct(array $values)
35+
public function __construct($rule = [])
3336
{
34-
if (! isset($values['for'])) {
35-
throw new BadMethodCallException('The @Validate annotation must be passed a target. For instance: "@Validate(for="$email", rule="email")"');
37+
$values = $rule;
38+
if (is_string($values)) {
39+
$this->rule = $values;
40+
} else {
41+
$this->rule = $values['rule'] ?? null;
42+
if (isset($values['for'])) {
43+
$this->for = ltrim($values['for'], '$');
44+
}
3645
}
3746
if (! isset($values['rule'])) {
38-
throw new BadMethodCallException('The @Validate annotation must be passed a rule. For instance: "@Validate(for="$email", rule="email")"');
47+
throw new BadMethodCallException('The @Validate annotation must be passed a rule. For instance: "#Validate("email")" in PHP 8+ or "@Validate(for="$email", rule="email")" in PHP 7+');
3948
}
40-
$this->for = ltrim($values['for'], '$');
41-
$this->rule = $values['rule'] ?? null;
4249
}
4350

4451
public function getTarget(): string
4552
{
53+
if ($this->for === null) {
54+
throw new BadMethodCallException('The @Validate annotation must be passed a target. For instance: "@Validate(for="$email", rule="email")"');
55+
}
4656
return $this->for;
4757
}
4858

0 commit comments

Comments
 (0)