| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentForm\App\Modules\Form\Settings\Validator; |
| 4 |
|
| 5 |
use FluentValidator\Validator; |
| 6 |
use FluentForm\Framework\Helpers\ArrayHelper; |
| 7 |
|
| 8 |
class Notifications |
| 9 |
{ |
| 10 |
/** |
| 11 |
* Validates notifications settings data. |
| 12 |
* |
| 13 |
* @param array $data |
| 14 |
* |
| 15 |
* @return bool |
| 16 |
*/ |
| 17 |
public static function validate($data = []) |
| 18 |
{ |
| 19 |
// Prepare the validation rules & messages. |
| 20 |
list($rules, $messages) = static::validations(); |
| 21 |
|
| 22 |
// Make validator instance. |
| 23 |
$validator = Validator::make($data, $rules, $messages); |
| 24 |
|
| 25 |
// Add conditional validations if there's any. |
| 26 |
$validator = static::conditionalValidations($validator); |
| 27 |
|
| 28 |
// Validate and process response. |
| 29 |
if ($validator->validate()->fails()) { |
| 30 |
wp_send_json_error(['errors' => $validator->errors()], 423); |
| 31 |
} |
| 32 |
|
| 33 |
return true; |
| 34 |
} |
| 35 |
|
| 36 |
/** |
| 37 |
* Produce the necessary validation rules and corresponding messages |
| 38 |
* |
| 39 |
* @return array |
| 40 |
*/ |
| 41 |
public static function validations() |
| 42 |
{ |
| 43 |
return [ |
| 44 |
[ |
| 45 |
'sendTo.type' => 'required', |
| 46 |
'sendTo.email' => 'required_if:sendTo.type,email', |
| 47 |
'sendTo.field' => 'required_if:sendTo.type,field', |
| 48 |
'subject' => 'required', |
| 49 |
'message' => 'required', |
| 50 |
], |
| 51 |
[ |
| 52 |
'sendTo.type.required' => 'The Send To field is required.', |
| 53 |
'sendTo.email.required_if' => 'The Send to Email field is required.', |
| 54 |
'sendTo.field.required_if' => 'The Send to Field field is required.', |
| 55 |
'sendTo.routing.*.email.required' => 'Please fill all the routing rules above.', |
| 56 |
] |
| 57 |
]; |
| 58 |
} |
| 59 |
|
| 60 |
/** |
| 61 |
* Add conditional validations to the validator. |
| 62 |
* |
| 63 |
* @param \FluentValidator\Validator $validator |
| 64 |
* |
| 65 |
* @return \FluentValidator\Validator |
| 66 |
*/ |
| 67 |
public static function conditionalValidations(Validator $validator) |
| 68 |
{ |
| 69 |
$validator->sometimes('sendTo.routing.*.email', 'required', function ($input) { |
| 70 |
if (ArrayHelper::get($input, 'sendTo.type') !== 'routing') { |
| 71 |
return false; |
| 72 |
} |
| 73 |
|
| 74 |
$routingInputs = ArrayHelper::get($input, 'sendTo.routing'); |
| 75 |
|
| 76 |
$required = false; |
| 77 |
|
| 78 |
foreach ($routingInputs as $routingInput) { |
| 79 |
if (! $routingInput['email'] || ! $routingInput['field'] || ! $routingInput['value']) { |
| 80 |
$required = true; |
| 81 |
|
| 82 |
break; |
| 83 |
} |
| 84 |
} |
| 85 |
|
| 86 |
return $required; |
| 87 |
}); |
| 88 |
|
| 89 |
return $validator; |
| 90 |
} |
| 91 |
} |