/** * Apply rules to src data recursively. * * @param array $src * @param array $rules * @param string $prefix * @param RuleSet $injectedInstance * @return array mixed */ public static function filter($src, $rules, $prefix = null, RuleSet $injectedInstance = null) { $result = array(); $ruleSet = $injectedInstance ?: self::instance(); foreach ($rules as $key => $rule) { if (self::has($rule)) { if (self::isList($rule)) { if (is_array($src[$key])) { $size = count($src[$key]); if ($rule['max'] && $size > $rule['max']) { $ruleSet->handle($src[$key], self::buildKey($key, $prefix), self::MESSAGE_ARRAY_SIZE_TOO_LARGE); } elseif ($rule['min'] && $size < $rule['min']) { $ruleSet->handle($src[$key], self::buildKey($key, $prefix), self::MESSAGE_ARRAY_SIZE_TOO_SMALL); } else { foreach ($src[$key] as $srcKey => $srcValue) { $result[$key][$srcKey] = self::filter($srcValue, $rule['rules'], self::buildKey($key . "." . $srcKey, $prefix), $injectedInstance); } } } else { if ($rule['min']) { $ruleSet->handle(null, self::buildKey($key, $prefix), self::MESSAGE_ARRAY_IS_INVALID); } else { // skip } } } else { if (is_array($src[$key])) { $result[$key] = self::filter($src[$key], $rule['rules'], self::buildKey($key, $prefix), $injectedInstance); } else { if ($rule['required']) { $ruleSet->handle(null, self::buildKey($key, $prefix), self::MESSAGE_ARRAY_IS_INVALID); } else { // skip } } } } else { $objRule = Rule::instance(); $result[$key] = $objRule->load($rule)->apply($src[$key]); if (!Rule::isValid($result[$key])) { // Skip handle if default value is not null. if ($objRule->defaulted(null) !== null) { $result[$key] = $objRule->defaulted(null); } elseif ($objRule->required(null) || strlen(trim($src[$key])) > 0) { $ruleSet->handle($src[$key], self::buildKey($key, $prefix)); } } } } return $result; }