JsonArray.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. namespace App\Rules;
  3. use Illuminate\Contracts\Validation\Rule;
  4. use Illuminate\Support\Facades\Validator;
  5. /**
  6. * 检测json数组
  7. *
  8. * @author 刘相欣
  9. *
  10. */
  11. class JsonArray implements Rule
  12. {
  13. protected $rules = [];
  14. protected $errMsg = '';
  15. /**
  16. * Create a new rule instance.
  17. *
  18. * @return void
  19. */
  20. public function __construct($rules=[])
  21. {
  22. $this->rules = $rules;
  23. }
  24. /**
  25. * Determine if the validation rule passes.
  26. *
  27. * @param string $attribute
  28. * @param mixed $value
  29. * @return bool
  30. */
  31. public function passes($attribute, $value)
  32. {
  33. // 解析数据
  34. $list = json_decode($value, true);
  35. // 递归验证
  36. $result = $this->validatorJsonArray($list,$attribute);
  37. // 验证结果
  38. return $result;
  39. }
  40. /**
  41. * 递归处理json验证
  42. * @param Mixed $data 待验证数据
  43. * @return bool
  44. */
  45. public function validatorJsonArray($data)
  46. {
  47. // 获取规则
  48. $rules = $this->rules;
  49. // 如果验证规则为空
  50. if( !$rules ) return true;
  51. // 如果不是数组
  52. if ( !is_array($data) ) {
  53. // 告知格式错误
  54. $this->errMsg = 'json数据格式错误';
  55. // 返回结果
  56. return false;
  57. }
  58. // 如果是关联数组,进行验证
  59. if ( count(array_filter(array_keys($data), 'is_string')) > 0 ){
  60. // 进行字段验证
  61. $validator = Validator::make($data, $rules);
  62. // 如果失败
  63. if ( $validator->fails() ) {
  64. // 获取错误信息
  65. $errors = $validator->errors()->getMessages();
  66. // 获取一条信息
  67. $errors = array_shift($errors);
  68. $errors = array_shift($errors);
  69. // 如果不是json错误
  70. if ($errors != 'validation.j_s_o_n') $this->errMsg = $errors;
  71. // 返回错误
  72. return false;
  73. }
  74. }else {
  75. // 如果是索引数组,循环进行递归验证
  76. foreach ($data as $item) {
  77. // 如果不是数组
  78. if( !is_array($item) ) continue;
  79. // 递归验证
  80. $result = $this->validatorJsonArray($item);
  81. // 验证失败,返回失败
  82. if ($result === false) return false;
  83. }
  84. }
  85. // 验证成功返回
  86. return true;
  87. }
  88. /**
  89. * Get the validation error message.
  90. *
  91. * @return string
  92. */
  93. public function message()
  94. {
  95. return $this->errMsg;
  96. }
  97. }