. */ namespace SP\Services\Import; use SP\Core\Exceptions\SPException; use SP\Util\Util; defined('APP_ROOT') || die(); /** * Clase FileImport encargada el leer archivos para su importación * * @package SP */ class FileImport { /** * Contenido del archivo leído * * @var string|array */ protected $fileContent; /** * Archivo temporal utilizado en la subida HTML * * @var string */ protected $tmpFile; /** * Tipo Mime del archivo * * @var string */ protected $fileType; /** * FileImport constructor. * * @param array $fileData Datos del archivo a importar * @throws SPException */ public function __construct($fileData) { try { $this->checkFile($fileData); } catch (SPException $e) { throw $e; } } /** * Leer los datos del archivo. * * @param array $fileData con los datos del archivo * @throws SPException */ private function checkFile($fileData) { if (!is_array($fileData)) { throw new SPException( __u('Archivo no subido correctamente'), SPException::ERROR, __u('Verifique los permisos del usuario del servidor web') ); } if ($fileData['name']) { // Comprobamos la extensión del archivo $fileExtension = mb_strtoupper(pathinfo($fileData['name'], PATHINFO_EXTENSION)); if ($fileExtension !== 'CSV' && $fileExtension !== 'XML') { throw new SPException( __u('Tipo de archivo no soportado'), SPException::ERROR, __u('Compruebe la extensión del archivo') ); } } // Variables con información del archivo $this->tmpFile = $fileData['tmp_name']; $this->fileType = strtolower($fileData['type']); if (!file_exists($this->tmpFile) || !is_readable($this->tmpFile)) { // Registramos el máximo tamaño permitido por PHP debugLog('Max. upload size: ' . Util::getMaxUpload()); throw new SPException( __u('Error interno al leer el archivo'), SPException::ERROR, __u('Compruebe la configuración de PHP para subir archivos') ); } } /** * @return array */ public function getFileContent() { return $this->fileContent; } /** * @return string */ public function getTmpFile() { return $this->tmpFile; } /** * @return string */ public function getFileType() { return $this->fileType; } /** * Leer los datos de un archivo subido a un array * * @throws \SP\Core\Exceptions\SPException */ public function readFileToArray() { $this->autodetectEOL(); if (($this->fileContent = file($this->tmpFile, FILE_SKIP_EMPTY_LINES)) === false) { throw new SPException( __u('Error interno al leer el archivo'), SPException::ERROR, __u('Compruebe los permisos del directorio temporal') ); } } /** * Activar la autodetección de fin de línea */ protected function autodetectEOL() { ini_set('auto_detect_line_endings', true); } /** * Leer los datos de un archivo subido a una cadena * * @throws \SP\Core\Exceptions\SPException */ public function readFileToString() { $this->autodetectEOL(); if (($this->fileContent = file_get_contents($this->tmpFile)) === false) { throw new SPException( __u('Error interno al leer el archivo'), SPException::ERROR, __u('Compruebe los permisos del directorio temporal') ); } } }