Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created May 10, 2020 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parzibyte/f930ede226d5e68e32557856d015ebb2 to your computer and use it in GitHub Desktop.
Save parzibyte/f930ede226d5e68e32557856d015ebb2 to your computer and use it in GitHub Desktop.
<?php
private $nombreCarpetaFotos = "fotos";
private $nombreCarpetaAdjuntos = "adjuntos";
private $TIPO_ADJUNTOS_BAJA = "BAJA";
private $nombreFoto404 = "error_404.jpeg";
public function foto(Request $peticion)
{
$nombreFoto = $peticion->nombre;
$rutaDeImagen = storage_path("app/" . $this->nombreCarpetaFotos . "/" . $this->obtenerRutaSegura($nombreFoto));
return response()->file($rutaDeImagen);
}
public function descargar(Request $peticion)
{
$nombreFoto = $peticion->nombre;
$rutaDeImagen = storage_path("app/" . $this->nombreCarpetaFotos . "/" . $this->obtenerRutaSegura($nombreFoto));
return response()->download($rutaDeImagen);
}
public function eliminarFoto(Request $peticion)
{
$datosDecodificados = json_decode($peticion->getContent());
$nombreFoto = $this->obtenerRutaSegura($datosDecodificados->nombre);
if ($nombreFoto === $this->nombreFoto404) return [];
Storage::disk("local")->delete("fotos/$nombreFoto");
return response()->json([
"archivo" => Storage::disk("local")->delete("fotos/$nombreFoto"), // Eliminar el archivo físico
"bd" => FotoDeArticulo::where("ruta", "=", $nombreFoto)->delete() // y quitar el registro de la base de datos
]);
}
private function obtenerRutaSegura($rutaInsegura)
{
# Verifica si la ruta que se quiere leer realmente pertenece a un artículo, en caso de que sí, regresa la
#misma ruta pero tomada de la base de datos
$posibleRegistro = FotoDeArticulo::where("ruta", "=", $rutaInsegura)->first();
if ($posibleRegistro === null) return $this->nombreFoto404;
return $posibleRegistro->ruta;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment