|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Petecoop\LaravelActionsLighthouse; |
| 4 | + |
| 5 | +use Closure; |
| 6 | +use Nuwave\Lighthouse\Schema\Values\FieldValue; |
| 7 | +use Nuwave\Lighthouse\Schema\Directives\ValidationDirective; |
| 8 | +use ReflectionFunction; |
| 9 | + |
| 10 | +class ActionValidationDirective extends ValidationDirective |
| 11 | +{ |
| 12 | + protected array $rules = []; |
| 13 | + protected array $messages = []; |
| 14 | + |
| 15 | + /** |
| 16 | + * Gets the validation info from the action through reflection... |
| 17 | + * Not pretty but it works! |
| 18 | + */ |
| 19 | + public function handleField(FieldValue $fieldValue, Closure $next): FieldValue |
| 20 | + { |
| 21 | + $resolver = $fieldValue->getResolver(); |
| 22 | + |
| 23 | + $fieldValue->useDefaultResolver(); |
| 24 | + $actionClosure = $fieldValue->getResolver(); |
| 25 | + $fieldValue->setResolver($resolver); |
| 26 | + |
| 27 | + $reflect = new ReflectionFunction($actionClosure); |
| 28 | + $decorator = $reflect->getClosureThis(); |
| 29 | + $action = $decorator->getAction(); |
| 30 | + |
| 31 | + if (method_exists($action, 'rules')) { |
| 32 | + $this->rules = $action->rules(); |
| 33 | + } |
| 34 | + |
| 35 | + if (method_exists($action, 'getValidationMessages')) { |
| 36 | + $this->messages = $action->getValidationMessages(); |
| 37 | + } |
| 38 | + |
| 39 | + return parent::handleField($fieldValue, $next); |
| 40 | + } |
| 41 | + |
| 42 | + public function rules(): array |
| 43 | + { |
| 44 | + return $this->rules; |
| 45 | + } |
| 46 | + |
| 47 | + public function messages(): array |
| 48 | + { |
| 49 | + return $this->messages; |
| 50 | + } |
| 51 | +} |
0 commit comments