Skip to content

Making Validate annotation available as a PHP8 attribute #29

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 3, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
},
"extra": {
"branch-alias": {
"dev-master": "4.0.x-dev"
"dev-master": "4.1.x-dev"
},
"laravel": {
"providers": [
Expand Down
22 changes: 16 additions & 6 deletions src/Annotations/Validate.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@

namespace TheCodingMachine\GraphQLite\Laravel\Annotations;

use Attribute;
use BadMethodCallException;
use TheCodingMachine\GraphQLite\Annotations\MiddlewareAnnotationInterface;
use TheCodingMachine\GraphQLite\Annotations\ParameterAnnotationInterface;
use function is_string;
use function ltrim;

/**
Expand All @@ -19,6 +21,7 @@
* @Attribute("rule", type = "string")
* })
*/
#[Attribute(Attribute::TARGET_PARAMETER)]
class Validate implements ParameterAnnotationInterface
{
/** @var string */
Expand All @@ -29,20 +32,27 @@ class Validate implements ParameterAnnotationInterface
/**
* @param array<string, mixed> $values
*/
public function __construct(array $values)
public function __construct($rule = [])
{
if (! isset($values['for'])) {
throw new BadMethodCallException('The @Validate annotation must be passed a target. For instance: "@Validate(for="$email", rule="email")"');
$values = $rule;
if (is_string($values)) {
$this->rule = $values;
} else {
$this->rule = $values['rule'] ?? null;
if (isset($values['for'])) {
$this->for = ltrim($values['for'], '$');
}
}
if (! isset($values['rule'])) {
throw new BadMethodCallException('The @Validate annotation must be passed a rule. For instance: "@Validate(for="$email", rule="email")"');
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+');
}
$this->for = ltrim($values['for'], '$');
$this->rule = $values['rule'] ?? null;
}

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

Expand Down