[Actualiza] foto y fondo de perfi en edición de perfil y agrega validación de imágenes

This commit is contained in:
Ricardo García Jiménez 2022-01-24 01:27:56 -06:00
parent 0d0491b9d2
commit 45f9e19d2b
4 changed files with 120 additions and 3 deletions

View File

@ -102,8 +102,10 @@ class profilesController {
$validations = new validations(NABU_ROUTES['edit-profile']);
$form = array_merge($_POST, $_FILES);
// Valida el formulario de edición de perfil.
$data = $validations -> validate($_POST, array(
$data = $validations -> validate($form, array(
array('field' => 'avatar', 'type' => 'image', 'optional' => true),
array('field' => 'background', 'type' => 'image', 'optional' => true),
array('field' => 'description', 'trim_all' => true, 'min_length' => 1, 'max_length' => 255, 'optional' => true),
@ -212,6 +214,32 @@ class profilesController {
}
}
// Valida si hay cambios en la foto de perfil.
if (isset($data['avatar'])) {
$update['avatar'] = utils::update_image('profilesModel', 'avatar', $profile['avatar'], $data['avatar']);
if ($update['avatar'] === false) {
messages::add('¡Lo sentimos mucho! 😞, por el momento no podemos actualizar tu foto de perfil');
unset($update['avatar']);
}
else
messages::add('Tu foto de perfil se ha actualizado correctamente');
}
// Valida si hay cambios en el fondo de perfil.
if (isset($data['background'])) {
$update['background'] = utils::update_image('profilesModel', 'background', $profile['background'], $data['background']);
if ($update['background'] === false) {
messages::add('¡Lo sentimos mucho! 😞, por el momento no podemos actualizar el fondo de tu perfil');
unset($update['background']);
}
else
messages::add('El fondo de tu perfil se ha actualizado correctamente');
}
// Actualiza los datos de perfil de un usuario en la base de datos.
if (!empty($update))
$profilesModel -> update($id, $update);

View File

@ -58,9 +58,47 @@ class utils {
$url = NABU_DEFAULT[$category];
if (!empty($filename))
if (file_exists(NABU_DIRECTORY['storage_' . $category . 's'] . '/' . $filename))
if (file_exists(NABU_DIRECTORY['storage-' . $category . 's'] . '/' . $filename))
$url = NABU_DIRECTORY[$category . 's'] . '/' . $filename;
return $url;
}
// @return el nombre de una imagen y reemplaza una imagen por otra.
public static function update_image(string $model, string $category, $original, array $replacement) {
$extension = explode('/', $replacement['type'])[1];
if ($extension == 'svg+xml')
$extension = 'svg';
require_once 'models/' . $model . '.php';
$Model = new $model();
// Valida si el nombre de la imagen es único.
do
$filename = bin2hex(random_bytes(32)) . '.' . $extension;
while(!empty($Model -> find_image($category, $filename)));
unset($Model);
$path = NABU_DIRECTORY['storage-' . $category . 's'] . '/';
$destination = $path . $filename;
// Mueve la imagen subida a la carpeta de almacenamiento de fotos de perfil.
if (move_uploaded_file($replacement['tmp_name'], $destination)) {
// Elimina la imagen anterior.
if (!empty($original)) {
$origin = $path . $original;
if (file_exists($origin))
unlink($origin);
}
return $filename;
}
return false;
}
}

View File

@ -66,6 +66,33 @@ class validations {
messages::add('El campo "' . $this -> field . '" contiene una dirección de correo electrónico no válido');
}
// Valida si la información de un archivo proviene de la variable global $_FILE.
private function is_file() {
$file = $this -> value;
return is_array($file) && !empty($file['tmp_name']);
}
// Valida si es una imagen.
private function is_image() {
$image = $this -> value;
// Valida el tamaño de la imagen.
if ($image['size'] > NABU_DEFAULT['image-size'])
messages::add('Por favor elija una imagen de menor peso');
$formats = explode(',', NABU_DEFAULT['image-formats']);
// Valida el formato de la imagen.
foreach ($formats as $format)
if (trim($format) == $image['type']) {
$extension = $format;
break;
}
if (empty($extension))
messages::add('Formato de imagen no válido');
}
// Valida si dos datos son iguales.
private function equal($foo) {
if ($this -> value !== $foo)
@ -116,7 +143,15 @@ class validations {
$this -> is_email();
}
elseif ($type == 'image') {
//
// Valida si el campo para subir imágenes es obligatorio u opcional.
if (!$this -> is_file()) {
if (empty($param['optional']))
messages::add('El campo "' . $this -> field . '" require obligatoriamente de un archivo de imagen');
continue;
}
$this -> is_image();
}
if (isset($param['equal']))

View File

@ -61,6 +61,22 @@ class profilesModel extends dbConnection {
}
}
// @return el id de un perfil si existe una imagen.
public function find_image(string $column, string $filename) {
$query = 'SELECT id FROM profiles WHERE ' . $column . ' = ? LIMIT 1';
try {
$prepare = $this -> pdo -> prepare($query);
$prepare -> execute(array($filename));
return $prepare -> fetch();
}
catch (PDOException $e) {
$this -> errors($e -> getMessage(), 'tuvimos un problema para buscar tus imágenes de perfil');
}
}
public function __destruct() {
parent::__destruct();
$this -> pdo = null;