* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ /** * \file cfdixml/src/CFDIParametrosValidator.php * \ingroup cfdixml * \brief Clase para validar los parámetros requeridos en un CFDI */ class CFDIParametrosValidator { private $estructura; public function __construct($estructura) { $this->estructura = $estructura; } /** * Validates a specific node against the defined structure. * * This function checks if the given node exists in the structure and validates * its parameters according to the defined configuration. * * @param string $nombreNodo The name of the node to validate. * @param array $datos An associative array containing the data to validate. * * @return array An array of error messages. Empty if no errors were found. * * @throws Exception If the specified node is not defined in the structure. */ public function validarNodo($nombreNodo, $datos) { $errores = []; if (!isset($this->estructura[$nombreNodo])) { throw new Exception("Nodo no definido: $nombreNodo"); } foreach ($this->estructura[$nombreNodo] as $param => $config) { if ($config['requerido'] && !isset($datos[$param])) { $errores[] = "El parámetro $param es requerido en el nodo $nombreNodo"; continue; } if (isset($datos[$param])) { $validacion = $this->validarTipo( $datos[$param], $config['tipo'], "$nombreNodo.$param" ); if ($validacion !== true) { $errores[] = $validacion; } } } return $errores; } /** * Validates a value against a specified type. * * This function checks if the given value matches the expected type. * It supports validation for decimal, dateTime, and string types. * * @param mixed $valor The value to be validated * @param string $tipo The expected type of the value ('decimal', 'dateTime', or 'string') * @param string $campo The name of the field being validated (used for error messages) * * @return bool|string Returns true if the value is valid, or an error message string if invalid */ private function validarTipo($valor, $tipo, $campo) { switch ($tipo) { case 'decimal': if (!is_numeric($valor)) { return "El campo $campo debe ser numérico"; } break; case 'dateTime': if (!strtotime($valor)) { return "El campo $campo debe ser una fecha válida"; } break; case 'string': if (!is_string($valor)) { return "El campo $campo debe ser una cadena de texto"; } break; } return true; } }