| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace Give\Framework\FieldsAPI\Actions; |
| 6 |
|
| 7 |
use Give\Vendors\StellarWP\Validation\Rules\ExcludeIf; |
| 8 |
use Give\Vendors\StellarWP\Validation\Rules\ExcludeUnless; |
| 9 |
use Give\Vendors\StellarWP\Validation\Rules\Optional; |
| 10 |
use Give\Vendors\StellarWP\Validation\ValidationRuleSet; |
| 11 |
|
| 12 |
class UpdateValidationRulesWithOptionalAsDefault |
| 13 |
{ |
| 14 |
/** |
| 15 |
* This adds the "optional" rule to fields that don't have a "required" rule. |
| 16 |
* This is to ensure that fields that are not required are not validated unless they have a value. |
| 17 |
* Additionally, this ensures that the "optional" rule is placed before the "exclude" rules to preserve the intended pipeline functionality. |
| 18 |
* |
| 19 |
* @since 3.0.0 |
| 20 |
*/ |
| 21 |
public function __invoke(ValidationRuleSet $rules): ValidationRuleSet |
| 22 |
{ |
| 23 |
if (!$rules->hasRules() || $rules->hasRule('optional')) { |
| 24 |
return $rules; |
| 25 |
} |
| 26 |
|
| 27 |
if (!$rules->hasRule('required')) { |
| 28 |
$rules->prependRule('optional'); |
| 29 |
} |
| 30 |
|
| 31 |
$excludeRuleIds = [ExcludeIf::id(), ExcludeUnless::id()]; |
| 32 |
|
| 33 |
foreach ($excludeRuleIds as $excludeRuleId) { |
| 34 |
// If the exclude rule is present, remove it and prepend it to the rules array so that optional comes after. |
| 35 |
if ($rules->hasRule($excludeRuleId) && $rules->getRules()[0] instanceof Optional) { |
| 36 |
$excludeRule = $rules->getRule($excludeRuleId); |
| 37 |
|
| 38 |
$rules->removeRuleWithId($excludeRuleId); |
| 39 |
$rules->prependRule($excludeRule); |
| 40 |
} |
| 41 |
} |
| 42 |
|
| 43 |
return $rules; |
| 44 |
} |
| 45 |
} |