Skip to content

Commit

Permalink
feat: add message parameter for costume error message using parameter (
Browse files Browse the repository at this point in the history
…#39)

- allowed add costume error message uing parameter in method `Validator::messages()`
  • Loading branch information
SonyPradana authored Feb 4, 2024
1 parent cb31546 commit b5e4006
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 4 deletions.
31 changes: 27 additions & 4 deletions src/Validator.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ final class Validator
/** @var bool Check rule validate has run or not */
private $has_run_validate = false;

/** @var MessagePool[] */
private $messages = [];

/**
* Create validation and filter.
*
Expand Down Expand Up @@ -406,15 +409,35 @@ private function closure_to_filter($rule_filter): FilterPool
;
}

/** @var MessagePool[] */
private $messages = [];
/**
* Helper to get costume message from Closure.
*
* @param callable(MessagePool=): (MessagePool|mixed) $rule_filter closure of MessagePool
*
* @return MessagePool Costume error Message
*/
private function closureToMessages($rule_filter): MessagePool
{
$pool = new MessagePool();

$return_closure = call_user_func_array($rule_filter, [$pool]);

return $return_closure instanceof MessagePool
? $return_closure
: $pool
;
}

/**
* Set field-rule specific error messages.
*
* @param callable(MessagePool=): (MessagePool|mixed) $pools Closure with param as MessagePool
*/
public function messages(): MessagePool
public function messages($pools = null): MessagePool
{
return $this->messages[] = new MessagePool();
$pools ??= static fn () => new MessagePool();

return $this->messages[] = $this->closureToMessages($pools);
}

/**
Expand Down
18 changes: 18 additions & 0 deletions tests/Unit/CostumeErrorValidation.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<?php

use Validator\Messages\MessagePool;
use Validator\Rule;
use Validator\Rule\ValidPool;
use Validator\Validator;
Expand Down Expand Up @@ -126,3 +127,20 @@
'costume required message'
);
});

it('can costume error message using messages with callback', function () {
$v = Validator::make()->validation(fn (ValidPool $v) => [
$v('test')->required(),
$v('test2')->required(),
]);
$v->messages(static function (MessagePool $message) {
$message->field('test')->required = 'costume required message';
})->field('test2')->required = 'costume required message';

expect($v->errors->test)->toEqual(
'costume required message'
);
expect($v->errors->test2)->toEqual(
'costume required message'
);
});

0 comments on commit b5e4006

Please sign in to comment.