data = $data; $this->rules = $rules; } /** * Definir dados para validação */ public function setData(array $data): self { $this->data = $data; return $this; } /** * Definir regras de validação */ public function setRules(array $rules): self { $this->rules = $rules; return $this; } /** * Definir mensagens customizadas */ public function setMessages(array $messages): self { $this->customMessages = $messages; return $this; } /** * Parar na primeira validação que falhar */ public function stopOnFirstError(bool $stop = true): self { $this->stopOnFirstError = $stop; return $this; } /** * Validar dados */ public function validate(): bool { $this->errors = []; foreach ($this->rules as $field => $fieldRules) { $value = $this->getFieldValue($field); $fieldRules = $this->parseRules($fieldRules); foreach ($fieldRules as $rule) { $ruleName = $rule['name']; $ruleParams = $rule['params']; if (!$this->applyRule($ruleName, $value, $ruleParams, $field)) { $this->addError($field, $ruleName, $ruleParams); if ($this->stopOnFirstError) { return false; } } } } return empty($this->errors); } /** * Obter erros de validação */ public function getErrors(): array { return $this->errors; } /** * Obter primeiro erro */ public function getFirstError(): ?string { if (empty($this->errors)) { return null; } $firstField = array_key_first($this->errors); return $this->errors[$firstField][0] ?? null; } /** * Verificar se campo tem erro */ public function hasError(string $field): bool { return isset($this->errors[$field]); } /** * Obter erros de um campo específico */ public function getFieldErrors(string $field): array { return $this->errors[$field] ?? []; } /** * Limpar erros */ public function clearErrors(): self { $this->errors = []; return $this; } /** * Obter valor do campo */ private function getFieldValue(string $field) { $keys = explode('.', $field); $value = $this->data; foreach ($keys as $key) { if (!isset($value[$key])) { return null; } $value = $value[$key]; } return $value; } /** * Parse das regras de validação */ private function parseRules(string $rules): array { $parsedRules = []; $ruleList = explode('|', $rules); foreach ($ruleList as $rule) { $rule = trim($rule); if (strpos($rule, ':') !== false) { [$ruleName, $params] = explode(':', $rule, 2); $ruleParams = explode(',', $params); } else { $ruleName = $rule; $ruleParams = []; } $parsedRules[] = [ 'name' => trim($ruleName), 'params' => array_map('trim', $ruleParams) ]; } return $parsedRules; } /** * Aplicar regra de validação */ private function applyRule(string $ruleName, $value, array $params, string $field): bool { $method = 'validate' . ucfirst($ruleName); if (method_exists($this, $method)) { return $this->$method($value, $params, $field); } // Tentar método estático na classe Validate if (method_exists(Validate::class, $ruleName)) { return call_user_func_array([Validate::class, $ruleName], array_merge([$value], $params)); } // Regra customizada return $this->validateCustom($ruleName, $value, $params, $field); } /** * Adicionar erro */ private function addError(string $field, string $rule, array $params = []): void { $message = $this->getErrorMessage($field, $rule, $params); if (!isset($this->errors[$field])) { $this->errors[$field] = []; } $this->errors[$field][] = $message; } /** * Obter mensagem de erro */ private function getErrorMessage(string $field, string $rule, array $params = []): string { $fieldKey = $field . '.' . $rule; // Mensagem customizada específica if (isset($this->customMessages[$fieldKey])) { return $this->customMessages[$fieldKey]; } // Mensagem customizada para o campo if (isset($this->customMessages[$field])) { return $this->customMessages[$field]; } // Mensagem padrão return $this->getDefaultMessage($field, $rule, $params); } /** * Obter mensagem padrão */ private function getDefaultMessage(string $field, string $rule, array $params = []): string { $fieldName = str_replace('_', ' ', $field); $fieldName = ucfirst($fieldName); $messages = [ 'required' => "O campo {$fieldName} é obrigatório.", 'email' => "O campo {$fieldName} deve ser um email válido.", 'min' => "O campo {$fieldName} deve ter pelo menos {$params[0]} caracteres.", 'max' => "O campo {$fieldName} deve ter no máximo {$params[0]} caracteres.", 'numeric' => "O campo {$fieldName} deve ser numérico.", 'integer' => "O campo {$fieldName} deve ser um número inteiro.", 'decimal' => "O campo {$fieldName} deve ser um número decimal.", 'url' => "O campo {$fieldName} deve ser uma URL válida.", 'phone' => "O campo {$fieldName} deve ser um telefone válido.", 'date' => "O campo {$fieldName} deve ser uma data válida.", 'alpha' => "O campo {$fieldName} deve conter apenas letras.", 'alphanumeric' => "O campo {$fieldName} deve conter apenas letras e números.", 'in' => "O campo {$fieldName} deve ser um dos valores: " . implode(', ', $params), 'not_in' => "O campo {$fieldName} não pode ser um dos valores: " . implode(', ', $params), 'unique' => "O valor do campo {$fieldName} já existe.", 'exists' => "O valor do campo {$fieldName} não existe.", 'confirmed' => "A confirmação do campo {$fieldName} não coincide.", 'different' => "O campo {$fieldName} deve ser diferente de {$params[0]}.", 'same' => "O campo {$fieldName} deve ser igual a {$params[0]}.", 'regex' => "O formato do campo {$fieldName} é inválido.", 'file' => "O campo {$fieldName} deve ser um arquivo válido.", 'image' => "O campo {$fieldName} deve ser uma imagem válida.", 'mimes' => "O campo {$fieldName} deve ser um arquivo do tipo: " . implode(', ', $params), 'size' => "O campo {$fieldName} deve ter no máximo {$params[0]} KB.", 'between' => "O campo {$fieldName} deve estar entre {$params[0]} e {$params[1]}.", 'min_value' => "O campo {$fieldName} deve ser pelo menos {$params[0]}.", 'max_value' => "O campo {$fieldName} deve ser no máximo {$params[0]}.", 'strong_password' => "O campo {$fieldName} deve ter pelo menos 8 caracteres, incluindo maiúscula, minúscula e número." ]; return $messages[$rule] ?? "O campo {$fieldName} é inválido."; } // ============================================================================= // REGRAS DE VALIDAÇÃO ESPECÍFICAS // ============================================================================= /** * Validar campo obrigatório */ private function validateRequired($value, array $params, string $field): bool { return Validate::required($value); } /** * Validar comprimento mínimo */ private function validateMin($value, array $params, string $field): bool { if (empty($params[0])) return true; return Validate::minLength($value, (int)$params[0]); } /** * Validar comprimento máximo */ private function validateMax($value, array $params, string $field): bool { if (empty($params[0])) return true; return Validate::maxLength($value, (int)$params[0]); } /** * Validar valor mínimo */ private function validateMinValue($value, array $params, string $field): bool { if (empty($params[0])) return true; return Validate::decimal($value, (float)$params[0]); } /** * Validar valor máximo */ private function validateMaxValue($value, array $params, string $field): bool { if (empty($params[0])) return true; return Validate::decimal($value, null, (float)$params[0]); } /** * Validar entre valores */ private function validateBetween($value, array $params, string $field): bool { if (count($params) < 2) return true; return Validate::decimal($value, (float)$params[0], (float)$params[1]); } /** * Validar valores permitidos */ private function validateIn($value, array $params, string $field): bool { return Validate::in($value, $params); } /** * Validar valores não permitidos */ private function validateNotIn($value, array $params, string $field): bool { return Validate::notIn($value, $params); } /** * Validar confirmação */ private function validateConfirmed($value, array $params, string $field): bool { $confirmationField = $field . '_confirmation'; $confirmationValue = $this->getFieldValue($confirmationField); return $value === $confirmationValue; } /** * Validar diferente de */ private function validateDifferent($value, array $params, string $field): bool { if (empty($params[0])) return true; $otherValue = $this->getFieldValue($params[0]); return $value !== $otherValue; } /** * Validar igual a */ private function validateSame($value, array $params, string $field): bool { if (empty($params[0])) return true; $otherValue = $this->getFieldValue($params[0]); return $value === $otherValue; } /** * Validar regex */ private function validateRegex($value, array $params, string $field): bool { if (empty($params[0])) return true; return Validate::pattern($value, $params[0]); } /** * Validar arquivo */ private function validateFile($value, array $params, string $field): bool { if (!is_array($value)) return false; return Validate::file($value); } /** * Validar imagem */ private function validateImage($value, array $params, string $field): bool { if (!is_array($value)) return false; $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']; return Validate::fileType($value, $allowedTypes); } /** * Validar tipos MIME */ private function validateMimes($value, array $params, string $field): bool { if (!is_array($value)) return false; return Validate::fileType($value, $params); } /** * Validar tamanho do arquivo */ private function validateSize($value, array $params, string $field): bool { if (!is_array($value)) return false; if (empty($params[0])) return true; $maxSize = (int)$params[0] * 1024; // Converter KB para bytes return Validate::fileSize($value, $maxSize); } /** * Validar password forte */ private function validateStrongPassword($value, array $params, string $field): bool { return Validate::strongPassword($value); } /** * Validar regra customizada */ private function validateCustom(string $ruleName, $value, array $params, string $field): bool { // Permitir extensão com regras customizadas $customMethod = 'validate' . ucfirst($ruleName); if (method_exists($this, $customMethod)) { return $this->$customMethod($value, $params, $field); } // Por padrão, aceitar se não encontrar regra return true; } // ============================================================================= // MÉTODOS ESTÁTICOS PARA FACILITAR USO // ============================================================================= /** * Validação rápida */ public static function make(array $data, array $rules, array $messages = []): self { $validator = new self($data, $rules); if (!empty($messages)) { $validator->setMessages($messages); } return $validator; } /** * Validação com resposta JSON */ public static function validateJson(array $data, array $rules, array $messages = []): array { $validator = self::make($data, $rules, $messages); $isValid = $validator->validate(); return [ 'valid' => $isValid, 'errors' => $validator->getErrors(), 'first_error' => $validator->getFirstError() ]; } /** * Validar e lançar exceção se falhar */ public static function validateOrFail(array $data, array $rules, array $messages = []): array { $validator = self::make($data, $rules, $messages); if (!$validator->validate()) { throw new \InvalidArgumentException( 'Validation failed: ' . $validator->getFirstError() ); } return $data; } }