-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
f36f14b
commit 268c41f
Showing
1 changed file
with
90 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
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 []; | ||
} | ||
} |