1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Hechoenlaravel\JarvisFoundation\Entries\Middleware; |
4
|
|
|
|
5
|
|
|
use League\Tactician\Middleware; |
6
|
|
|
use Illuminate\Support\Facades\Validator; |
7
|
|
|
use Hechoenlaravel\JarvisFoundation\Exceptions\EntryValidationException; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Class ValidateEntryData |
11
|
|
|
* @package Hechoenlaravel\JarvisFoundation\Entries\Middleware |
12
|
|
|
*/ |
13
|
|
|
class ValidateEntryData implements Middleware |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* @var array |
17
|
|
|
*/ |
18
|
|
|
public $rules = []; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @param object $command |
22
|
|
|
* @param callable $next |
23
|
|
|
* @return mixed |
24
|
|
|
* @throws EntryValidationException |
25
|
|
|
*/ |
26
|
|
|
public function execute($command, callable $next) |
27
|
|
|
{ |
28
|
|
|
$this->prepareValidation($command)->performValidation($command); |
29
|
|
|
return $next($command); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @param $command |
34
|
|
|
* @return $this |
35
|
|
|
*/ |
36
|
|
|
protected function prepareValidation($command) |
37
|
|
|
{ |
38
|
|
|
$fields = $command->entity->fields; |
39
|
|
|
foreach ($fields as $field) { |
40
|
|
|
$this->setRulesForField($field); |
41
|
|
|
} |
42
|
|
|
return $this; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* Set the validation rules for the Field |
47
|
|
|
* @param $field |
48
|
|
|
*/ |
49
|
|
|
protected function setRulesForField($field) |
50
|
|
|
{ |
51
|
|
|
$this->rules[$field->slug] = []; |
52
|
|
|
if ((bool)$field->required === true) { |
53
|
|
|
array_push($this->rules[$field->slug], 'required'); |
54
|
|
|
} |
55
|
|
|
// Import the validation rules from the fieldtype Class |
56
|
|
|
$type = $field->getType(); |
57
|
|
|
$classValidationRules = isset($type->validationRules) ? $type->validationRules : []; |
58
|
|
|
foreach ($classValidationRules as $key => $rule) { |
59
|
|
|
$rule = (is_string($rule)) ? explode('|', $rule) : $rule; |
60
|
|
|
$this->rules[$field->slug] = array_merge($this->rules[$field->slug], $rule); |
61
|
|
|
} |
62
|
|
|
return $this; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* @param $command |
67
|
|
|
* @throws EntryValidationException |
68
|
|
|
*/ |
69
|
|
|
protected function performValidation($command) |
70
|
|
|
{ |
71
|
|
|
$validator = Validator::make($command->input, $this->rules); |
72
|
|
|
if ($validator->fails()) { |
73
|
|
|
throw new EntryValidationException($validator); |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|