Created
April 26, 2020 12:14
-
-
Save PJZ9n/8c5f7c00de35bea49acac6e23fbb899e to your computer and use it in GitHub Desktop.
PHPのfilter_varをPMMPのコマンドで使う例
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); | |
$label = "pay";//送金コマンド | |
$args = [ | |
"hoge",//名前 | |
"-1"//金額 | |
]; | |
if ($label === "pay") {//送金コマンドだったら | |
//全ての引数が存在しているか確認 | |
if (!isset($args[0], $args[1])) {//$args[0,1,2,3...]と続く | |
//どれかが存在しない場合 | |
exit();//return false;などでも良い | |
} | |
$filteredArgs = []; | |
//名前のフィルター | |
$filteredArgs[0] = filter_var($args[0], FILTER_CALLBACK, [//コールバックでフィルター | |
"options" => function ($value) { | |
if (!is_string($value) && $value !== null) { | |
//文字列ではなくて、さらにnullでもない場合 | |
return false;//検証に失敗したことを返す | |
} | |
if (\pocketmine\Player::isValidUserName($value)) { | |
//有効なユーザー名だった場合 | |
return $value;//そのまま値を返す | |
} | |
//有効なユーザー名ではなかった場合 | |
return false;//検証に失敗したことを返す | |
}, | |
]); | |
//金額のフィルター | |
$filteredArgs[1] = filter_var($args[1], FILTER_VALIDATE_INT, [//int型でフィルター | |
"options" => [ | |
"min_range" => 1,//金額は最低でも1である必要がある | |
], | |
]); | |
var_dump($args);//フィルター前のパラメータ | |
/* | |
* array(2) { | |
* [0]=> | |
* string(4) "hoge" | |
* [1]=> | |
* string(6) "-1" | |
* } | |
*/ | |
var_dump($filteredArgs);//フィルター後のパラメータ | |
/* | |
* array(2) { | |
* [0]=> | |
* string(4) "hoge" | |
* [1]=> | |
* bool(false) | |
* } | |
*/ | |
//falseが返ってきた=検証に失敗した | |
if ($filteredArgs[0] === false || $filteredArgs[1] === false) {//!$args[]だと微妙(型の問題) | |
exit();//return false;などでも良い | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment