Skip to content

Commit

Permalink
表单验证
Browse files Browse the repository at this point in the history
  • Loading branch information
Joycezhangw committed May 7, 2021
1 parent f36f14b commit 268c41f
Showing 1 changed file with 90 additions and 0 deletions.
90 changes: 90 additions & 0 deletions src/Validation/AbstractValidator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
<?php


namespace JoyceZ\LaravelLib\Validation;


use Illuminate\Support\Arr;
use Illuminate\Validation\Factory;
use Illuminate\Validation\ValidationException;

/**
* 表单验证
* Class AbstractValidator
* @package JoyceZ\LaravelLib\Validation
*/
abstract class AbstractValidator
{
protected $validator;

protected $data;

public function __construct(Factory $validator)
{
$this->validator = $validator;
}

/**
* @param array $attributes
* @throws ValidationException
*/
public function valid(array $attributes)
{
$attributes = $this->existsValue($attributes, $this->haveToFields());

$this->data = $attributes;

$validator = $this->make($attributes);
if ($validator->fails()) {
throw new ValidationException($validator);
}
}

public function make(array $attributes)
{
$rules = Arr::only($this->getRules(), array_keys($attributes));

return $this->validator->make($attributes, $rules, $this->getMessages());
}

/**
* 循环必传值(当required为空时不循环)
*
* @param $attributes
* @param $required
* @return mixed
*/
public function existsValue($attributes, $required)
{
collect($required)->map(function ($item) use (&$attributes) {
if (!array_key_exists($item, $attributes)) {
$attributes[$item] = '';
}
});

return $attributes;
}

/**
* @return array
*/
abstract protected function getRules();

/**
* @return array
*/
protected function getMessages()
{
return [];
}

/**
* 必填字段值
*
* @return array
*/
protected function haveToFields()
{
return [];
}
}

0 comments on commit 268c41f

Please sign in to comment.