Last active
February 11, 2020 19:47
-
-
Save PJZ9n/7d00fc291571c2751d3d661c312742c8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| declare(strict_types=1); | |
| use Particle\Validator\Validator; | |
| //Example 1 | |
| $target = [ | |
| "max-players" => 50, | |
| "now-players" => 10, | |
| "item" => [ | |
| "value" => "abcdefghijkl", | |
| ], | |
| "hoge" => "fooabcdefgh",//これは検証しない(getValues()を試す) | |
| ]; | |
| $validator = new Validator(); | |
| $validator->required("max-players")->integer()->between(0, PHP_INT_MAX);//int型,0からPHP_INT_MAXまで | |
| $validator->required("now-players")->integer()->between(0, PHP_INT_MAX);//int型,0からPHP_INT_MAXまで | |
| $validator->required("item.value")->string()->lengthBetween(1, 10);//string型,1文字から5文字まで | |
| $result = $validator->validate($target);//検証開始 | |
| var_dump($result->isValid());//検証に成功したかどうか | |
| print_r($result->getValues());//検証に通った値 | |
| if ($result->isNotValid()) {//検証に失敗していたら | |
| $messages = []; | |
| foreach ($result->getFailures() as $failure) { | |
| $messages[] = $failure->format(); | |
| } | |
| echo "検証に失敗しました: " . implode(' | ', $messages) . PHP_EOL; | |
| } | |
| //Example 2 | |
| $target = [ | |
| "join-items" => [ | |
| [ | |
| "id" => 100, | |
| "damage" => 0, | |
| "amount" => 5, | |
| ], | |
| [ | |
| "id" => 150, | |
| "damage" => 8, | |
| "amount" => 111, | |
| ], | |
| [ | |
| "id" => 250, | |
| "damage" => 0, | |
| "amount" => 99, | |
| ], | |
| ], | |
| ]; | |
| $validator = new Validator(); | |
| $validator->required("join-items")->each(function (Validator $validator): void { | |
| $validator->required("id")->integer()->between(0, PHP_INT_MAX); | |
| $validator->required("damage")->integer()->between(0, PHP_INT_MAX); | |
| $validator->required("amount")->integer()->between(0, PHP_INT_MAX); | |
| }); | |
| $result = $validator->validate($target);//検証開始 | |
| var_dump($result->isValid());//検証に成功したかどうか | |
| print_r($result->getValues());//検証に通った値 | |
| if ($result->isNotValid()) {//検証に失敗していたら | |
| $messages = []; | |
| foreach ($result->getFailures() as $failure) { | |
| $messages[] = $failure->format(); | |
| } | |
| echo "検証に失敗しました: " . implode(' | ', $messages) . PHP_EOL; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment