1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84: 85: 86: 87: 88:
<?php
namespace MvcCore\Ext\Form\Validators;
require_once(__DIR__.'/../../Form.php');
require_once(__DIR__.'/../Core/Validator.php');
require_once(__DIR__.'/../Core/Field.php');
require_once(__DIR__.'/../Core/View.php');
use
MvcCore\Ext\Form,
MvcCore\Ext\Form\Core;
class ValueInOptions extends Core\Validator
{
public function Validate ($submitValue, $fieldName, \MvcCore\Ext\Form\Core\Field & $field) {
$safeValue = $this->completeSafeValueByOptions($submitValue, $field);
$safeValueType = gettype($safeValue);
$safeValueCount = count($safeValue);
$safeValueLen = is_array($safeValue) ? count($safeValue) : mb_strlen($safeValue);
if (
($safeValueType == 'array' && $safeValueCount !== count($submitValue)) ||
($safeValueType == 'string' && $safeValueLen !== mb_strlen($submitValue))
) {
$this->addError(
$field,
Form::$DefaultMessages[Form::VALID],
function ($msg, $args) {
return Core\View::Format($msg, $args);
}
);
}
return $safeValue;
}
protected function completeSafeValueByOptions ($submitValue, & $field) {
if (gettype($submitValue) == 'array') {
$submitValues = $submitValue;
$safeValue = array();
} else {
$submitValue = (string) $submitValue;
$submitValues = mb_strlen($submitValue) > 0 ? array($submitValue) : array();
$safeValue = '';
}
foreach ($submitValues as $submitValueItem) {
$submitValueItem = trim($submitValueItem);
$catched = 0;
$safeValueItem = '';
foreach ($field->Options as $key1 => $option1) {
if ($key1 == $submitValueItem) {
$catched = 1;
$safeValueItem = $key1;
break;
}
if (isset($option1['options']) && gettype($option1['options']) == 'array') {
foreach ($option1['options'] as $key2 => $option2) {
if ($key2 == $submitValueItem) {
$catched = 1;
$safeValueItem = $key2;
break;
}
}
}
if ($catched) break;
}
if ($catched) {
if (gettype($safeValue) == 'array') {
$safeValue[] = $safeValueItem;
} else {
$safeValue = $safeValueItem;
}
}
}
return $safeValue;
}
}