20. Relaciones a uno en la base de datos

Versión para imprimir.

A. Introducción

B. Diagrama entidad relación

Diagrama entidad relación

C. Diagrama relacional

Diagrama relacional

D. Diagrama de despliegue

Diagrama de despliegue

E. Hazlo funcionar (con videos)

  1. Prueba el ejemplo en http://srvauno.rf.gd/.

  2. Descarga el archivo /src/srvauno.zip y descompáctalo.

  3. Crea una cuenta de email pqra ti, por ejemplo, pepito@google.com. Si ya tienes un email, omite este paso.

  4. Crea una cuenta de GitHub usando el email anterior y selecciona el nombre de usuario unsando la parte inicial del correo electrónico, por ejemplo pepito. Si ya tienes una cuenta, omite este paso.

  5. Crea un repositorio nuevo. En el nombre del repositorio debes poner el nombre de tu sitio; por ejemplo devuelvejson

  6. Importa el proyecto de GitHub a Visual Studio Code

  7. Edita los archivos que desees.

  8. Prueba tu sitio localmente.

  9. Necesitas un hosting. En este ejemplo se muestra como usar el hosting. https://infinityfree.com/ Si no lo has usado, lo primero que tienes que hacer es entrar a registrar tu email con el botón Registrar. Si ya tienes tu email registrado, omite este paso.

  10. Crea una cuenta. Si ya tienes cuenta, entra a ella y crea un nuevo domino. En este ejemplo no se crean los archivos directamente en el hosting.

  11. Sube tus archivos al hosting usando ftp.

  12. Sube tus archivos a GitHub. En este ejemplo no hay archivo sw.js ni necesitas esperar 11 o más minutos.

F. Hazlo funcionar (texto)

  1. Prueba el ejemplo en http://srvauno.rf.gd/.

  2. Descarga el archivo /src/srvauno.zip y descompáctalo.

  3. Crea tu proyecto en GitHub:

    1. Crea una cuenta de email para tí, por ejemplo, pepito@google.com. Si ya tienes un email, omite este paso.

    2. Crea una cuenta de GitHub usando el email anterior y selecciona el nombre de usuario unsando la parte inicial del correo electrónico, por ejemplo pepito. Si ya tienes una cuenta, omite este paso.

    3. Crea un repositorio nuevo. En la página principal de GitHub cliquea 📘 New.

    4. En la página Create a new repository introduce los siguientes datos:

      • Proporciona el nombre de tu repositorio debajo de donde dice Repository name *.

      • Mantén la selección Public para que otros usuarios puedan ver tu proyecto.

      • Verifica la casilla Add a README file. En este archivo se muestra información sobre tu proyecto.

      • Cliquea License: None. y selecciona la licencia que consideres más adecuada para tu proyecto.

      • Cliquea Create repository.

  4. Importa el proyecto en GitHub:

    1. En la página principal de tu proyecto en GitHub, en la pestaña < > Code, cliquea < > Code y en la sección Branches y copia la dirección que está en HTTPS, debajo de Clone.

    2. En Visual Studio Code, usa el botón de la izquierda para Source Control.

      Imagen de Source Control
    3. Cliquea el botón Clone Repository.

    4. Pega la url que copiaste anteriormente hasta arriba, donde dice algo como Provide repository URL y presiona la teclea Intro.

    5. Selecciona la carpeta donde se guardará la carpeta del proyecto.

    6. Abre la carpeta del proyecto importado.

    7. Añade el contenido de la carpeta descompactada que contiene el código del ejemplo.

  5. Edita los archivos que desees.

  6. Haz clic derecho en index.html, selecciona PHP Server: serve project y se abre el navegador para que puedas probar localmente el ejemplo.

  7. Para depurar paso a paso haz lo siguiente:

    1. En el navegador, haz clic derecho en la página que deseas depurar y selecciona inspeccionar.

    2. Recarga la página, de preferencia haciendo clic derecho en el ícono de volver a cargar la página Ïmagen del ícono de recarga y seleccionando vaciar caché y volver a cargar de manera forzada (o algo parecido). Si no aparece un menú emergente, simplemente cliquea volver a cargar la página Ïmagen del ícono de recarga. Revisa que no aparezca ningún error ni en la pestañas Consola, ni en Red.

    3. Selecciona la pestaña Fuentes (o Sources si tu navegador está en Inglés).

    4. Selecciona el archivo donde vas a empezar a depurar.

    5. Haz clic en el número de la línea donde vas a empezar a depurar.

    6. En Visual Studio Code, abre el archivo de PHP donde vas a empezar a depurar.

    7. Haz clic en Run and Debug .

    8. Si no está configurada la depuración, haz clic en create a launch json file.

    9. Haz clic en la flechita RUN AND DEBUG, al lado de la cual debe decir Listen for Xdebug .

    10. Aparece un cuadro con los controles de depuración

    11. Selecciona otra vez el archivo de PHP y haz clic en el número de la línea donde vas a empezar a depurar.

    12. Regresa al navegador, recarga la página y empieza a usarla.

    13. Si se ejecuta alguna de las líneas de código seleccionadas, aparece resaltada en la pestaña de fuentes. Usa los controles de depuración para avanzar, como se muestra en este video.

  8. Sube el proyecto al hosting que elijas.

    1. Crea una nueva carpeta para crear un nuevo proyecto que estará conectado directamente al servidor web por ftp.

    2. Abre la nueva carpeta con Visual Studio Code.

    3. Tecle al mismo Mayúsculas+Control+P y selecciona SFTP: Config. Aparece un archivo de configuración de FTP. Llena los datos con la configuración de FTP de tu servidor, excepto la contraseña.

    4. Cliquea el botón de SFTP y luego haz clic en la URL de tu servidos. En la barra superior te pide la contraseña y ENTER.

    5. Pásate a la parte de archivos y coloca tus archivos.

    6. Cliquea con el botón derecho en la sección de archivos y selecciona Sync: Local -> Remote.

  9. Abre un navegador y prueba el proyecto en tu hosting.

  10. En el hosting InfinityFree, la primera vez que corres la página, puede marcar un mensaje de error, pero al recargar funciona correctamente. Puedes evitar este problema usando un dominio propio.

  11. Para subir el código a GitHub, en la sección de SOURCE CONTROL, en Message introduce un mensaje sobre los cambios que hiciste, por ejemplo index.html corregido, selecciona v y luego Commit & Push.

    Imagen de Commit & Push

G. Archivos

Haz clic en los triángulos para expandir las carpetas

H. index.html

1
<!DOCTYPE html>
2
<html lang="es">
3
4
<head>
5
6
 <meta charset="UTF-8">
7
 <meta name="viewport" content="width=device-width">
8
9
 <title>Relaciones a uno</title>
10
11
 <script type="module" src="js/lib/manejaErrores.js"></script>
12
13
</head>
14
15
<body>
16
17
 <h1>Relaciones a uno</h1>
18
19
 <p><a href="agrega.html">Agregar</a></p>
20
21
 <dl id="lista">
22
  <dt>Cargando…</dt>
23
  <dd><progress max="100">Cargando…</progress></dd>
24
 </dl>
25
26
 <script type="module">
27
28
  import { descargaVista } from "./js/lib/descargaVista.js"
29
30
  descargaVista("php/amigo-vista-index.php")
31
32
 </script>
33
34
</body>
35
36
</html>

I. agrega.html

1
<!DOCTYPE html>
2
<html lang="es">
3
4
<head>
5
6
 <meta charset="UTF-8">
7
 <meta name="viewport" content="width=device-width">
8
9
 <title>Agregar</title>
10
11
 <script type="module" src="js/lib/manejaErrores.js"></script>
12
13
</head>
14
15
<body>
16
17
 <form id="formulario">
18
19
  <h1>Agregar</h1>
20
21
  <p><a href="index.html">Cancelar</a></p>
22
23
  <p>
24
   <label>
25
    Nombre *
26
    <input name="nombre">
27
   </label>
28
  </p>
29
30
  <p>
31
   <label>
32
    Pasatiempo
33
    <select name="pasId">
34
     <option value="">Cargando…</option>
35
    </select>
36
   </label>
37
  </p>
38
39
  <p>* Obligatorio</p>
40
41
  <p><button type="submit">Agregar</button></p>
42
43
 </form>
44
45
 <script type="module">
46
47
  import { descargaVista } from "./js/lib/descargaVista.js"
48
  import { submitAccion } from "./js/lib/submitAccion.js"
49
50
  descargaDatos()
51
52
  async function descargaDatos() {
53
54
   await descargaVista("php/amigo-vista-agrega.php")
55
56
   formulario.addEventListener(
57
    "submit",
58
    event => submitAccion(
59
     event, "php/amigo-agrega.php", formulario, "index.html"
60
    )
61
   )
62
63
  }
64
65
 </script>
66
67
</body>
68
69
</html>

J. modifica.html

1
<!DOCTYPE html>
2
<html lang="es">
3
4
<head>
5
6
 <meta charset="UTF-8">
7
 <meta name="viewport" content="width=device-width">
8
9
 <title>Modificar</title>
10
11
 <script type="module" src="js/lib/manejaErrores.js"></script>
12
13
</head>
14
15
<body>
16
17
 <form id="formulario">
18
19
  <h1>Modificar</h1>
20
21
  <p><a href="index.html">Cancelar</a></p>
22
23
  <input type="hidden" name="id">
24
25
  <p>
26
   <label>
27
    Nombre *
28
    <input name="nombre" value="Cargando…">
29
   </label>
30
  </p>
31
32
  <p>
33
   <label>
34
    Pasatiempo
35
    <select name="pasId">
36
     <option value="">Cargando…</option>
37
    </select>
38
   </label>
39
  </p>
40
41
  <p>* Obligatorio</p>
42
43
  <p>
44
45
   <button type="submit">Guardar</button>
46
47
   <button id="botonEliminar" type="button">
48
    Eliminar
49
   </button>
50
51
  </p>
52
53
 </form>
54
55
 <script type="module">
56
57
  import { descargaVista } from "./js/lib/descargaVista.js"
58
  import { submitAccion } from "./js/lib/submitAccion.js"
59
  import { accionElimina } from "./js/lib/accionElimina.js"
60
61
  const params = new URL(location.href).searchParams
62
  descargaDatos()
63
64
  async function descargaDatos() {
65
66
   if (params.size > 0) {
67
68
    await descargaVista("php/amigo-vista-modifica.php?" + params)
69
70
    formulario.addEventListener(
71
     "submit",
72
     event => submitAccion(
73
      event, "php/amigo-modifica.php", formulario, "index.html"
74
     )
75
    )
76
77
    botonEliminar.addEventListener(
78
     "click",
79
     () => accionElimina(
80
      "php/amigo-elimina.php",
81
      formulario,
82
      "Confirma la eliminación",
83
      "index.html"
84
     )
85
    )
86
87
   }
88
89
  }
90
91
 </script>
92
93
</body>
94
95
</html>

K. Carpeta « php »

Versión para imprimir.

A. php / amigo-agrega.php

1
<?php
2
3
require_once __DIR__ . "/lib/manejaErrores.php";
4
require_once __DIR__ . "/lib/recibeEntero.php";
5
require_once __DIR__ . "/lib/recibeTextoObligatorio.php";
6
require_once __DIR__ . "/lib/recibeEnteroOpcional.php";
7
require_once __DIR__ . "/lib/devuelveCreated.php";
8
require_once __DIR__ . "/Bd.php";
9
require_once __DIR__ . "/pasatiempoOptions.php";
10
11
$nombre = recibeTextoObligatorio("nombre");
12
$pasId = recibeEnteroOpcional("pasId");
13
14
$pdo = Bd::pdo();
15
$stmt = $pdo->prepare(
16
 "INSERT INTO AMIGO (
17
   AMI_NOMBRE, PAS_ID
18
  ) values (
19
   :PAS_NOMBRE, :PAS_ID
20
  )"
21
);
22
$stmt->execute([
23
 ":PAS_NOMBRE" => $nombre,
24
 ":PAS_ID" => $pasId
25
]);
26
$id = $pdo->lastInsertId();
27
28
$encodeId = urlencode($id);
29
devuelveCreated(
30
 "/php/amigo-vista-modifica.php?id=$encodeId",
31
 [
32
  "id" => ["value" => $id],
33
  "nombre" => ["value" => $nombre],
34
  "pasId" => [
35
   "innerHTML" => pasatiempoOptons(),
36
   "value" => $pasId === null ? "" : $pasId
37
  ]
38
 ]
39
);
40

B. php / amigo-elimina.php

1
<?php
2
3
require_once __DIR__ . "/lib/manejaErrores.php";
4
require_once __DIR__ . "/lib/recibeEnteroObligatorio.php";
5
require_once __DIR__ . "/lib/devuelveNoContent.php";
6
require_once __DIR__ . "/Bd.php";
7
8
$id = recibeEnteroObligatorio("id");
9
10
$bd = Bd::pdo();
11
$stmt = $bd->prepare("DELETE FROM AMIGO WHERE AMI_ID = :AMI_ID");
12
$stmt->execute([":AMI_ID" => $id]);
13
14
devuelveNoContent();
15

C. php / amigo-modifica.php

1
<?php
2
3
require_once __DIR__ . "/lib/manejaErrores.php";
4
require_once __DIR__ . "/lib/recibeEnteroObligatorio.php";
5
require_once __DIR__ . "/lib/recibeTextoObligatorio.php";
6
require_once __DIR__ . "/lib/recibeEnteroOpcional.php";
7
require_once __DIR__ . "/lib/devuelveJson.php";
8
require_once __DIR__ . "/Bd.php";
9
require_once __DIR__ . "/pasatiempoOptions.php";
10
11
$id = recibeEnteroObligatorio("id");
12
$nombre = recibeTextoObligatorio("nombre");
13
$pasId = recibeEnteroOpcional("pasId");
14
15
$bd = Bd::pdo();
16
$stmt = $bd->prepare(
17
 "UPDATE AMIGO
18
   SET
19
    AMI_NOMBRE = :AMI_NOMBRE,
20
    PAS_ID = :PAS_ID
21
   WHERE
22
    AMI_ID = :AMI_ID"
23
);
24
$stmt->execute([
25
 ":AMI_NOMBRE" => $nombre,
26
 ":PAS_ID" => $pasId,
27
 ":AMI_ID" => $id,
28
]);
29
30
devuelveJson([
31
 "id" => ["value" => $id],
32
 "nombre" => ["value" => $nombre],
33
 "pasId" => [
34
  "innerHTML" => pasatiempoOptons(),
35
  "value" => $pasId === null ? "" : $pasId
36
 ]
37
]);
38

D. php / amigo-vista-agrega.php

1
<?php
2
3
require_once __DIR__ . "/lib/manejaErrores.php";
4
require_once __DIR__ . "/lib/devuelveJson.php";
5
require_once __DIR__ . "/pasatiempoOptions.php";
6
7
devuelveJson(["pasId" => ["innerHTML" => pasatiempoOptons()]]);
8

E. php / amigo-vista-index.php

1
<?php
2
3
require_once __DIR__ . "/lib/manejaErrores.php";
4
require_once __DIR__ . "/lib/devuelveJson.php";
5
require_once __DIR__ . "/Bd.php";
6
7
$bd = Bd::pdo();
8
$stmt = $bd->query(
9
 "SELECT
10
    A.AMI_ID,
11
    A.AMI_NOMBRE,
12
    P.PAS_NOMBRE
13
   FROM AMIGO A
14
    LEFT JOIN PASATIEMPO P
15
    ON A.PAS_ID = P.PAS_ID
16
   ORDER BY
17
    A.AMI_NOMBRE"
18
);
19
$lista = $stmt->fetchAll(PDO::FETCH_ASSOC);
20
21
$render = "";
22
foreach ($lista as $modelo) {
23
 $encodeAmiId = urlencode($modelo["AMI_ID"]);
24
 $amiId = htmlentities($encodeAmiId);
25
 $amiNombre = htmlentities($modelo["AMI_NOMBRE"]);
26
 $pasNombre = $modelo["PAS_NOMBRE"] === null
27
  ? "<em>-- Sin pasatiempo --</em>"
28
  : htmlentities($modelo["PAS_NOMBRE"]);
29
 $render .=
30
  "<dt><a href='modifica.html?id=$amiId'>$amiNombre</a></dt>
31
    <dd><a href='modifica.html?id=$amiId'>$pasNombre</a></dd>";
32
}
33
34
devuelveJson(["lista" => ["innerHTML" => $render]]);
35

F. php / amigo-vista-modifica.php

1
<?php
2
3
require_once __DIR__ . "/lib/manejaErrores.php";
4
require_once __DIR__ . "/lib/recibeEnteroObligatorio.php";
5
require_once __DIR__ . "/lib/validaEntidadObligatoria.php";
6
require_once __DIR__ . "/lib/devuelveJson.php";
7
require_once __DIR__ . "/Bd.php";
8
require_once __DIR__ . "/pasatiempoOptions.php";
9
10
$amiId = recibeEnteroObligatorio("id");
11
12
$bd = Bd::pdo();
13
$stmt = $bd->prepare("SELECT * FROM AMIGO WHERE AMI_ID = :AMI_ID");
14
$stmt->execute([":AMI_ID" => $amiId]);
15
$modelo = $stmt->fetch(PDO::FETCH_ASSOC);
16
17
$modelo = validaEntidadObligatoria("Amigo",  $modelo);
18
19
devuelveJson([
20
 "id" => ["value" => $amiId],
21
 "nombre" => ["value" => $modelo["AMI_NOMBRE"]],
22
 "pasId" => [
23
  "innerHTML" => pasatiempoOptons(),
24
  "value" => $modelo["PAS_ID"] === null ? "" : $modelo["PAS_ID"]
25
 ]
26
]);
27

G. php / Bd.php

1
<?php
2
3
class Bd
4
{
5
 private static ?PDO $pdo = null;
6
7
 static function pdo(): PDO
8
 {
9
  if (self::$pdo === null) {
10
11
   self::$pdo = new PDO(
12
    // cadena de conexión
13
    "sqlite:" . __DIR__ . "/srvauno.db",
14
    // usuario
15
    null,
16
    // contraseña
17
    null,
18
    // Opciones: pdos no persistentes y lanza excepciones.
19
    [PDO::ATTR_PERSISTENT => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
20
   );
21
22
   self::$pdo->exec(
23
    'CREATE TABLE IF NOT EXISTS PASATIEMPO (
24
      PAS_ID INTEGER,
25
      PAS_NOMBRE TEXT NOT NULL,
26
      CONSTRAINT PAS_PK
27
       PRIMARY KEY(PAS_ID),
28
      CONSTRAINT PAS_NOM_UNQ
29
       UNIQUE(PAS_NOMBRE),
30
      CONSTRAINT PAS_NOM_NV
31
       CHECK(LENGTH(PAS_NOMBRE) > 0)
32
     )'
33
   );
34
   self::$pdo->exec(
35
    'CREATE TABLE IF NOT EXISTS AMIGO (
36
      AMI_ID INTEGER,
37
      AMI_NOMBRE TEXT NOT NULL,
38
      PAS_ID INTEGER,
39
      CONSTRAINT AMI_PK
40
       PRIMARY KEY(AMI_ID),
41
      CONSTRAINT AMI_NOM_UNQ
42
       UNIQUE(AMI_NOMBRE),
43
      CONSTRAINT AMI_NOM_NV
44
       CHECK(LENGTH(AMI_NOMBRE) > 0),
45
      CONSTRAINT AMI_PAS_FK
46
       FOREIGN KEY (PAS_ID) REFERENCES PASATIEMPO(PAS_ID)
47
     )'
48
   );
49
50
   $cantidadDePasatiempos =
51
    self::$pdo->query("SELECT COUNT(PAS_ID) FROM PASATIEMPO")->fetchColumn(0);
52
53
   if ($cantidadDePasatiempos === 0) {
54
    self::$pdo->exec(
55
     "INSERT INTO PASATIEMPO (PAS_NOMBRE) VALUES ('Futbol'), ('Videojuegos')"
56
    );
57
   }
58
  }
59
60
  return self::$pdo;
61
 }
62
}
63

H. php / pasatiempoOptions.php

1
<?php
2
3
require_once __DIR__ . "/Bd.php";
4
5
function pasatiempoOptons()
6
{
7
 $bd = Bd::pdo();
8
 $stmt = $bd->query("SELECT * FROM PASATIEMPO ORDER BY PAS_NOMBRE");
9
 $lista = $stmt->fetchAll(PDO::FETCH_ASSOC);
10
11
 $render = "<option value=''>-- Sin pasatiempo --</option>";
12
 foreach ($lista as $modelo) {
13
  $id = htmlentities($modelo["PAS_ID"]);
14
  $nombre = htmlentities($modelo["PAS_NOMBRE"]);
15
  $render .= "<option value='$id'>{$nombre}</option>";
16
 }
17
18
 return $render;
19
}
20

I. Carpeta « php / lib »

1. php / lib / BAD_REQUEST.php

1
<?php
2
3
const BAD_REQUEST = 400;
4

2. php / lib / devuelveCreated.php

1
<?php
2
3
require_once __DIR__ . "/devuelveResultadoNoJson.php";
4
5
function devuelveCreated($urlDelNuevo, $resultado)
6
{
7
 $json = json_encode($resultado);
8
 if ($json === false) {
9
  devuelveResultadoNoJson();
10
 } else {
11
  http_response_code(201);
12
  header("Location: $urlDelNuevo");
13
  header("Content-Type: application/json; charset=utf-8");
14
  echo $json;
15
 }
16
}
17

3. php / lib / devuelveJson.php

1
<?php
2
3
require_once __DIR__ . "/devuelveResultadoNoJson.php";
4
5
function devuelveJson($resultado)
6
{
7
 $json = json_encode($resultado);
8
 if ($json === false) {
9
  devuelveResultadoNoJson();
10
 } else {
11
  header("Content-Type: application/json; charset=utf-8");
12
  echo $json;
13
 }
14
 exit();
15
}
16

4. php / lib / devuelveNoContent.php

1
<?php
2
3
function devuelveNoContent()
4
{
5
 http_response_code(204);
6
}
7

5. php / lib / devuelveResultadoNoJson.php

1
<?php
2
3
require_once __DIR__ . "/INTERNAL_SERVER_ERROR.php";
4
5
function devuelveResultadoNoJson()
6
{
7
 http_response_code(INTERNAL_SERVER_ERROR);
8
 header("Content-Type: application/problem+json; charset=utf-8");
9
10
 echo '{' .
11
  "status: " . INTERNAL_SERVER_ERROR .
12
  '"title": "El resultado no puede representarse como JSON."' .
13
  '"type": "/errors/resultadonojson.html"' .
14
  '}';
15
}
16

6. php / lib / INTERNAL_SERVER_ERROR.php

1
<?php
2
3
const INTERNAL_SERVER_ERROR = 500;

7. php / lib / manejaErrores.php

1
<?php
2
3
require_once __DIR__ . "/INTERNAL_SERVER_ERROR.php";
4
require_once __DIR__ . "/ProblemDetailsException.php";
5
6
// Hace que se lance una excepción automáticamente cuando se genere un error.
7
set_error_handler(function ($severity, $message, $file, $line) {
8
 throw new ErrorException($message, 0, $severity, $file, $line);
9
});
10
11
// Código cuando una excepción no es atrapada.
12
set_exception_handler(function (Throwable $excepcion) {
13
 if ($excepcion instanceof ProblemDetailsException) {
14
  devuelveProblemDetails($excepcion->problemDetails);
15
 } else {
16
  devuelveProblemDetails([
17
   "status" => INTERNAL_SERVER_ERROR,
18
   "title" => "Error interno del servidor",
19
   "detail" => $excepcion->getMessage(),
20
   "type" => "/errors/errorinterno.html",
21
  ]);
22
 }
23
 exit();
24
});
25
26
function devuelveProblemDetails(array $array)
27
{
28
 $json = json_encode($array);
29
 if ($json === false) {
30
  devuelveResultadoNoJson();
31
 } else {
32
  http_response_code(isset($array["status"]) ? $array["status"] : 500);
33
  header("Content-Type: application/problem+json; charset=utf-8");
34
  echo $json;
35
 }
36
}
37

8. php / lib / NOT_FOUND.php

1
<?php
2
3
const NOT_FOUND = 404;
4

9. php / lib / ProblemDetailsException.php

1
<?php
2
3
require_once __DIR__ . "/INTERNAL_SERVER_ERROR.php";
4
5
/**
6
 * Detalle de los errores devueltos por un servicio.
7
 */
8
class ProblemDetailsException extends Exception
9
{
10
11
 public array $problemDetails;
12
13
 public function __construct(
14
  array $problemDetails,
15
 ) {
16
  
17
  parent::__construct(
18
   isset($problemDetails["detail"])
19
    ? $problemDetails["detail"]
20
    : (isset($problemDetails["title"])
21
     ? $problemDetails["title"]
22
     : "Error"),
23
   $problemDetails["status"]
24
    ? $problemDetails["status"]
25
    : INTERNAL_SERVER_ERROR
26
  );
27
28
  $this->problemDetails = $problemDetails;
29
 }
30
}
31

10. php / lib / recibeEntero.php

1
<?php
2
3
require_once __DIR__ . "/recibeTexto.php";
4
5
/**
6
 * Devuelve el valor entero de un parámetro recibido en el
7
 * servidor por medio de GET, POST o cookie.
8
 * 
9
 * Si el parámetro no se recibe, devuelve false
10
 *
11
 * Si se recibe una cadena vacía, se devuelve null.
12
 * 
13
 * Si parámetro no se puede convertir a entero, se genera
14
 * un error.
15
 */
16
function recibeEntero(string $parametro): false|null|int
17
{
18
 $valor = recibeTexto($parametro);
19
 if ($valor === false) {
20
  return false;
21
 } else {
22
  $valor = trim($valor);
23
  if ($valor === "") {
24
   return null;
25
  } else {
26
   return (int) $valor;
27
  }
28
 }
29
}
30

11. php / lib / recibeEnteroObligatorio.php

1
<?php
2
3
require_once __DIR__ . "/BAD_REQUEST.php";
4
require_once __DIR__ . "/recibeEntero.php";
5
require_once __DIR__ . "/ProblemDetailsException.php";
6
7
function recibeEnteroObligatorio(string $parametro)
8
{
9
 $entero = recibeEntero($parametro);
10
11
 if ($entero === false)
12
  throw new ProblemDetailsException([
13
   "status" => BAD_REQUEST,
14
   "title" => "Falta el valor $parametro.",
15
   "type" => "/errors/faltavalor.html",
16
   "detail" => "La solicitud no tiene el valor de $parametro."
17
  ]);
18
19
 if ($entero === null)
20
  throw new ProblemDetailsException([
21
   "status" => BAD_REQUEST,
22
   "title" => "Campo $parametro en blanco.",
23
   "type" => "/errors/campoenteroenblanco.html",
24
   "detail" => "Pon un número entero en el campo $parametro."
25
  ]);
26
27
 return $entero;
28
}
29

12. php / lib / recibeEnteroOpcional.php

1
<?php
2
3
require_once __DIR__ . "/recibeEntero.php";
4
5
function recibeEnteroOpcional(string $parametro)
6
{
7
 $enteroOpcional = recibeEntero($parametro);
8
 return $enteroOpcional === false ? null : $enteroOpcional;
9
}
10

13. php / lib / recibeTexto.php

1
<?php
2
3
/**
4
 * Devuelve el texto de un parámetro enviado al
5
 * servidor por medio de GET, POST o cookie.
6
 * 
7
 * Si el parámetro no se recibe, devuelve false.
8
 */
9
function recibeTexto(string $parametro): false|string
10
{
11
 /* Si el parámetro está asignado en $_REQUEST,
12
  * devuelve su valor; de lo contrario, devuelve false.
13
  */
14
 $valor = isset($_REQUEST[$parametro])
15
  ? $_REQUEST[$parametro]
16
  : false;
17
 return $valor;
18
}
19

14. php / lib / recibeTextoObligatorio.php

1
<?php
2
3
require_once __DIR__ . "/BAD_REQUEST.php";
4
require_once __DIR__ . "/recibeTexto.php";
5
require_once __DIR__ . "/ProblemDetailsException.php";
6
7
function recibeTextoObligatorio(string $parametro)
8
{
9
 $texto = recibeTexto($parametro);
10
11
 if ($texto === false)
12
  throw new ProblemDetailsException([
13
   "status" => BAD_REQUEST,
14
   "title" => "Falta el valor $parametro.",
15
   "type" => "/errors/faltavalor.html",
16
   "detail" => "La solicitud no tiene el valor de $parametro."
17
  ]);
18
19
 $trimTexto = trim($texto);
20
21
 if ($trimTexto === "")
22
  throw new ProblemDetailsException([
23
   "status" => BAD_REQUEST,
24
   "title" => "Campo $parametro en blanco.",
25
   "type" => "/errors/campoenblanco.html",
26
   "detail" => "Pon texto en el campo $parametro."
27
  ]);
28
29
 return $trimTexto;
30
}
31

15. php / lib / validaEntidadObligatoria.php

1
<?php
2
3
require_once __DIR__ . "/NOT_FOUND.php";
4
require_once __DIR__ . "/ProblemDetailsException.php";
5
6
function validaEntidadObligatoria(string $nombre,  $entidad)
7
{
8
9
 if ($entidad === false)
10
  throw new ProblemDetailsException([
11
  "status" => NOT_FOUND,
12
  "title" => "Registro de $nombre no encontrado.",
13
  "type" => "/errors/entidadnoencontrada.html",
14
  "detail" => "No se encontró ningún registro de $nombre con el id solicitado.",
15
  ]);
16
17
 return $entidad;
18
}
19

L. Carpeta « js »

Versión para imprimir.

A. Carpeta « js / lib »

1. js / lib / accionElimina.js

1
import { consume } from "./consume.js"
2
import { enviaFormRecibeJson } from "./enviaFormRecibeJson.js"
3
4
/**
5
 * @param {string} url
6
 * @param {HTMLFormElement} formulario
7
 * @param {string} mensaje
8
 * @param {string} nuevaVista
9
 */
10
export async function accionElimina(url, formulario, mensaje, nuevaVista) {
11
 if (confirm(mensaje)) {
12
  await consume(enviaFormRecibeJson(url, formulario))
13
  location.href = nuevaVista
14
 }
15
}

2. js / lib / consume.js

1
import { ProblemDetailsError } from "./ProblemDetailsError.js"
2
3
/**
4
 * Espera a que la promesa de un fetch termine. Si
5
 * hay error, lanza una excepción.
6
 * 
7
 * @param {Promise<Response> } servicio
8
 */
9
export async function consume(servicio) {
10
 const respuesta = await servicio
11
 if (respuesta.ok) {
12
  return respuesta
13
 } else {
14
  const contentType = respuesta.headers.get("Content-Type")
15
  if (
16
   contentType !== null && contentType.startsWith("application/problem+json")
17
  )
18
   throw new ProblemDetailsError(await respuesta.json())
19
  else
20
   throw new Error(respuesta.statusText)
21
 }
22
}

3. js / lib / descargaVista.js

1
import { consume } from "./consume.js"
2
import { muestraObjeto } from "./muestraObjeto.js"
3
import { recibeJson } from "./recibeJson.js"
4
5
/**
6
 * @param {string} url
7
 * @param { "GET" | "POST"| "PUT" | "PATCH" | "DELETE" | "TRACE" | "OPTIONS"
8
 *  | "CONNECT" | "HEAD" } metodoHttp
9
 */
10
export async function descargaVista(url, metodoHttp = "GET") {
11
 const respuesta = await consume(recibeJson(url, metodoHttp))
12
 const json = await respuesta.json()
13
 muestraObjeto(document, json)
14
 return json
15
}

4. js / lib / enviaFormRecibeJson.js

1
/**
2
 * Envía los datos de un formolario a la url usando la codificación
3
 * multipart/form-data.
4
 * @param {string} url
5
 * @param {HTMLFormElement} formulario
6
 * @param { "GET" | "POST"| "PUT" | "PATCH" | "DELETE" | "TRACE" | "OPTIONS"
7
 *  | "CONNECT" | "HEAD" } metodoHttp
8
 */
9
export function enviaFormRecibeJson(url, formulario, metodoHttp = "POST") {
10
 return fetch(
11
  url,
12
  {
13
   method: metodoHttp,
14
   headers: { "Accept": "application/json, application/problem+json" },
15
   body: new FormData(formulario)
16
  }
17
 )
18
}

5. js / lib / manejaErrores.js

1
import { muestraError } from "./muestraError.js"
2
3
/**
4
 * Intercepta Response.prototype.json para capturar errores de parseo
5
 * y asegurar que se reporten correctamente en navegadores Chromium.
6
 */
7
{
8
 const originalJson = Response.prototype.json
9
10
 Response.prototype.json = function () {
11
  // Llamamos al método original usando el contexto (this) de la respuesta
12
  return originalJson.apply(this, arguments)
13
   .catch((/** @type {any} */ error) => {
14
    // Corrige un error de Chrome que evita el manejo correcto de errores.
15
    throw new Error(error)
16
   })
17
 }
18
}
19
20
window.onerror = function (
21
  /** @type {string} */ _message,
22
  /** @type {string} */ _url,
23
  /** @type {number} */ _line,
24
  /** @type {number} */ _column,
25
  /** @type {Error} */ errorObject
26
) {
27
 muestraError(errorObject)
28
 return true
29
}
30
31
window.addEventListener('unhandledrejection', event => {
32
 muestraError(event.reason)
33
 event.preventDefault()
34
})
35

6. js / lib / muestraError.js

1
import { ProblemDetailsError } from "./ProblemDetailsError.js"
2
3
/**
4
 * Muestra los datos de una Error en la consola y en un cuadro de alerta.
5
 * @param { ProblemDetailsError | Error | null } error descripción del error.
6
 */
7
export function muestraError(error) {
8
9
 if (error === null) {
10
11
  console.error("Error")
12
  alert("Error")
13
14
 } else if (error instanceof ProblemDetailsError) {
15
16
  const problemDetails = error.problemDetails
17
18
  let mensaje =
19
   typeof problemDetails["title"] === "string" ? problemDetails["title"] : ""
20
  if (typeof problemDetails["detail"] === "string") {
21
   if (mensaje !== "") {
22
    mensaje += "\n\n"
23
   }
24
   mensaje += problemDetails["detail"]
25
  }
26
  if (mensaje === "") {
27
   mensaje = "Error"
28
  }
29
  console.error(error, problemDetails)
30
  alert(mensaje)
31
32
 } else {
33
34
  console.error(error)
35
  alert(error.message)
36
37
 }
38
39
}

7. js / lib / muestraObjeto.js

1
/**
2
 * @param {Document | HTMLElement | ShadowRoot} raizHtml
3
 * @param { any } objeto
4
 */
5
export function muestraObjeto(raizHtml, objeto) {
6
 for (const [nombre, definiciones] of Object.entries(objeto)) {
7
  if (Array.isArray(definiciones)) {
8
   muestraArray(raizHtml, nombre, definiciones)
9
  } else if (definiciones !== undefined && definiciones !== null) {
10
   muestraElemento(raizHtml, nombre, definiciones)
11
  }
12
 }
13
}
14
15
/**
16
 * @param { string } nombre
17
 */
18
export function selectorDeNombre(nombre) {
19
 return `[id="${nombre}"],[name="${nombre}"],[data-name="${nombre}"]`
20
}
21
22
/**
23
 * @param { Document | HTMLElement | ShadowRoot } raizHtml
24
 * @param { string } propiedad
25
 * @param {any[]} valores
26
 */
27
function muestraArray(raizHtml, propiedad, valores) {
28
 const conjunto = new Set(valores)
29
 const elementos = raizHtml.querySelectorAll(selectorDeNombre(propiedad))
30
 if (elementos.length === 1 && elementos[0] instanceof HTMLSelectElement) {
31
  muestraOptions(elementos[0], conjunto)
32
 } else {
33
  muestraInputs(elementos, conjunto)
34
 }
35
36
}
37
38
/**
39
 * @param {HTMLSelectElement} select
40
 * @param {Set<any>} conjunto
41
 */
42
function muestraOptions(select, conjunto) {
43
 for (let i = 0, options = select.options, len = options.length; i < len; i++) {
44
  const option = options[i]
45
  option.selected = conjunto.has(option.value)
46
 }
47
}
48
49
/**
50
 * @param {NodeListOf<Element>} elementos
51
 * @param {Set<any>} conjunto
52
 */
53
function muestraInputs(elementos, conjunto) {
54
 for (let i = 0, len = elementos.length; i < len; i++) {
55
  const elemento = elementos[i]
56
  if (elemento instanceof HTMLInputElement) {
57
   elemento.checked = conjunto.has(elemento.value)
58
  }
59
 }
60
}
61
62
const data_ = "data-"
63
const data_Length = data_.length
64
65
/**
66
 * @param {Document | HTMLElement | ShadowRoot} raizHtml
67
 * @param {string} nombre
68
 * @param {{ [s: string]: any; } } definiciones
69
 */
70
function muestraElemento(raizHtml, nombre, definiciones) {
71
 const elemento = raizHtml.querySelector(selectorDeNombre(nombre))
72
 if (elemento !== null) {
73
  for (const [propiedad, valor] of Object.entries(definiciones)) {
74
   if (propiedad in elemento) {
75
    elemento[propiedad] = valor
76
   } else if (
77
    propiedad.length > data_Length
78
    && propiedad.startsWith(data_)
79
    && elemento instanceof HTMLElement
80
   ) {
81
    elemento.dataset[propiedad.substring(data_Length)] = valor
82
   }
83
  }
84
 }
85
}

8. js / lib / ProblemDetailsError.js

1
export class ProblemDetailsError extends Error {
2
3
 /**
4
  * Detalle de los errores devueltos por un servicio.
5
  * Crea una instancia de ProblemDetailsError.
6
  * @param {object} problemDetails Objeto con la descripcipon del error.
7
  */
8
 constructor(problemDetails) {
9
10
  super(typeof problemDetails["detail"] === "string"
11
   ? problemDetails["detail"]
12
   : (typeof problemDetails["title"] === "string"
13
    ? problemDetails["title"]
14
    : "Error"))
15
16
  this.problemDetails = problemDetails
17
18
 }
19
20
}

9. js / lib / recibeJson.js

1
2
/**
3
 * @param {string} url
4
 * @param { "GET" | "POST"| "PUT" | "PATCH" | "DELETE" | "TRACE" | "OPTIONS"
5
 *  | "CONNECT" | "HEAD" } metodoHttp
6
 */
7
export async function recibeJson(url, metodoHttp = "GET") {
8
 return fetch(
9
  url,
10
  {
11
   method: metodoHttp,
12
   headers: { "Accept": "application/json, application/problem+json" }
13
  }
14
 )
15
}

10. js / lib / submitAccion.js

1
import { consume } from "./consume.js"
2
import { enviaFormRecibeJson } from "./enviaFormRecibeJson.js"
3
4
/**
5
 * @param {Event} event
6
 * @param {string} url
7
 * @param {HTMLFormElement} formulario
8
 * @param {string} nuevaVista
9
 */
10
export async function submitAccion(event, url, formulario, nuevaVista) {
11
 event.preventDefault()
12
 await consume(enviaFormRecibeJson(url, formulario))
13
 location.href = nuevaVista
14
}

M. Carpeta « errors »

Versión para imprimir.

A. errors / campoenblanco.html

1
<!DOCTYPE html>
2
<html lang="es">
3
4
<head>
5
6
 <meta charset="UTF-8">
7
 <meta name="viewport" content="width=device-width">
8
9
 <title>Campo en blanco</title>
10
11
</head>
12
13
<body>
14
15
 <h1>Campo en blanco</h1>
16
17
 <p>Pon texto en el campo obligatorio que está en blanco.</p>
18
19
</body>
20
21
</html>

B. errors / campoenteroenblanco.html

1
<!DOCTYPE html>
2
<html lang="es">
3
4
<head>
5
6
 <meta charset="UTF-8">
7
 <meta name="viewport" content="width=device-width">
8
9
 <title>Campo entero en blanco</title>
10
11
</head>
12
13
<body>
14
15
 <h1>Campo entero en blanco</h1>
16
17
 <p>
18
  Pon un número entero en el campo que pide un valor entero obligatorio y está
19
  en blanco.
20
 </p>
21
22
</body>
23
24
</html>

C. errors / entidadnoencontrada.html

1
<!DOCTYPE html>
2
<html lang="es">
3
4
<head>
5
6
 <meta charset="UTF-8">
7
 <meta name="viewport" content="width=device-width">
8
9
 <title>Registro no encontrado</title>
10
11
</head>
12
13
<body>
14
15
 <h1>Registro no encontrado</h1>
16
17
 <p>No se encontró ningún registro con el id solicitado.</p>
18
19
</body>
20
21
</html>

D. errors / errorinterno.html

1
<!DOCTYPE html>
2
<html lang="es">
3
4
<head>
5
6
 <meta charset="UTF-8">
7
 <meta name="viewport" content="width=device-width">
8
9
 <title>Error interno del servidor</title>
10
11
</head>
12
13
<body>
14
15
 <h1>Error interno del servidor</h1>
16
17
 <p>Se presentó de forma inesperada un error interno del servidor.</p>
18
19
</body>
20
21
</html>

E. errors / faltavalor.html

1
<!DOCTYPE html>
2
<html lang="es">
3
4
<head>
5
6
 <meta charset="UTF-8">
7
 <meta name="viewport" content="width=device-width">
8
9
 <title>Falta un valor</title>
10
11
</head>
12
13
<body>
14
15
 <h1>Falta un valor</h1>
16
17
 <p>La solicitud no tiene un valor obligatorio.</p>
18
19
</body>
20
21
</html>

F. errors / resultadonojson.html

1
<!DOCTYPE html>
2
<html lang="es">
3
4
<head>
5
6
 <meta charset="UTF-8">
7
 <meta name="viewport" content="width=device-width">
8
9
 <title>El resultado no puede representarse como JSON</title>
10
11
</head>
12
13
<body>
14
15
 <h1>El resultado no puede representarse como JSON</h1>
16
17
 <p>
18
  Debido a un error interno del servidor, el resultado generado, no se puede
19
  recuperar.
20
 </p>
21
22
</body>
23
24
</html>

N. jsconfig.json

1
{
2
 "compilerOptions": {
3
  "checkJs": true,
4
  "strictNullChecks": true,
5
  "target": "ES6",
6
  "module": "Node16",
7
  "moduleResolution": "Node16",
8
  "lib": [
9
   "ES2017",
10
   "WebWorker",
11
   "DOM"
12
  ]
18
}

O. Resumen