21. Relaciones a muchos - Usuarios y roles

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://srvamuchos.rf.gd/.

  2. Descarga el archivo /src/srvamuchos.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://srvamuchos.rf.gd/.

  2. Descarga el archivo /src/srvamuchos.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 muchos</title>
10
11
 <script type="module" src="js/lib/manejaErrores.js"></script>
12
 
13
</head>
14
15
<body>
16
17
 <h1>Relaciones a muchos</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/usuario-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
    San *
26
    <input name="san">
27
   </label>
28
  </p>
29
30
  <fieldset id="roles">
31
32
   <legend>Roles</legend>
33
34
   <p>
35
    <progress max="100">Cargando…</progress>
36
   </p>
37
38
  </fieldset>
39
40
  <p>* Obligatorio</p>
41
42
  <p><button type="submit">Agregar</button></p>
43
44
 </form>
45
46
 <script type="module">
47
48
  import { descargaVista } from "./js/lib/descargaVista.js"
49
  import { submitAccion } from "./js/lib/submitAccion.js"
50
51
  descargaDatos()
52
53
  async function descargaDatos() {
54
55
   await descargaVista("php/usuario-vista-agrega.php")
56
57
   formulario.addEventListener(
58
    "submit",
59
    event => submitAccion(
60
     event, "php/usuario-agrega.php", formulario, "index.html"
61
    )
62
   )
63
64
  }
65
66
 </script>
67
68
</body>
69
70
</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
    San *
28
    <input name="san" value="Cargando…">
29
   </label>
30
  </p>
31
32
  <fieldset id="roles">
33
   <legend>Roles</legend>
34
35
   <p>
36
    <progress max="100">Cargando…</progress>
37
   </p>
38
39
  </fieldset>
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/usuario-vista-modifica.php?" + params)
69
70
    formulario.addEventListener(
71
     "submit",
72
     event => submitAccion(
73
      event, "php/usuario-modifica.php", formulario, "index.html"
74
     )
75
    )
76
77
    botonEliminar.addEventListener(
78
     "click",
79
     () => accionElimina(
80
      "php/usuario-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 / Bd.php

1
<?php
2
3
require_once __DIR__ . "/lib/rolBusca.php";
4
require_once __DIR__ . "/lib/rolAgrega.php";
5
6
class Bd
7
{
8
9
 private static ?PDO $pdo = null;
10
11
 static function pdo(): PDO
12
 {
13
  if (self::$pdo === null) {
14
15
   self::$pdo = new PDO(
16
    // cadena de conexión
17
    "sqlite:" . __DIR__ . "/srvamuchos.db",
18
    // usuario
19
    null,
20
    // contraseña
21
    null,
22
    // Opciones: pdos no persistentes y lanza excepciones.
23
    [PDO::ATTR_PERSISTENT => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
24
   );
25
26
   self::$pdo->exec(
27
    'CREATE TABLE IF NOT EXISTS USUARIO (
28
      USU_ID INTEGER,
29
      USU_SAN TEXT NOT NULL,
30
      CONSTRAINT USU_PK
31
       PRIMARY KEY(USU_ID),
32
      CONSTRAINT USU_SAN_UNQ
33
       UNIQUE(USU_SAN),
34
      CONSTRAINT USU_SAN_NV
35
       CHECK(LENGTH(USU_SAN) > 0)
36
     )'
37
   );
38
   self::$pdo->exec(
39
    'CREATE TABLE IF NOT EXISTS ROL (
40
      ROL_ID TEXT NOT NULL,
41
      ROL_DESCRIPCION TEXT NOT NULL,
42
      CONSTRAINT ROL_PK
43
       PRIMARY KEY(ROL_ID),
44
      CONSTRAINT ROL_ID_NV
45
       CHECK(LENGTH(ROL_ID) > 0),
46
      CONSTRAINT ROL_DESCR_UNQ
47
       UNIQUE(ROL_DESCRIPCION),
48
      CONSTRAINT ROL_DESCR_NV
49
       CHECK(LENGTH(ROL_DESCRIPCION) > 0)
50
     )'
51
   );
52
   self::$pdo->exec(
53
    'CREATE TABLE IF NOT EXISTS USU_ROL (
54
      USU_ID INTEGER NOT NULL,
55
      ROL_ID TEXT NOT NULL,
56
      CONSTRAINT USU_ROL_PK
57
       PRIMARY KEY(USU_ID, ROL_ID),
58
      CONSTRAINT USU_ROL_USU_FK
59
       FOREIGN KEY (USU_ID) REFERENCES USUARIO(USU_ID),
60
      CONSTRAINT USU_ROL_ROL_FK
61
       FOREIGN KEY (ROL_ID) REFERENCES ROL(ROL_ID)
62
     )'
63
   );
64
65
   self::$pdo->beginTransaction();
66
67
   if (rolBusca(self::$pdo, "Administrador") === false) {
68
    rolAgrega(
69
     bd: self::$pdo,
70
     id: "Administrador",
71
     descripcion: "Administra el sistema."
72
    );
73
   }
74
75
   if (rolBusca(self::$pdo, "Cliente") === false) {
76
    rolAgrega(
77
     bd: self::$pdo,
78
     id: "Cliente",
79
     descripcion: "Realiza compras."
80
    );
81
   }
82
83
   self::$pdo->commit();
84
  }
85
86
  return self::$pdo;
87
 }
88
}
89

B. php / rolCheckboxes.php

1
<?php
2
3
require_once __DIR__ . "/Bd.php";
4
5
function rolCheckboxes()
6
{
7
 $bd = Bd::pdo();
8
 $lista =
9
  $bd->query("SELECT * FROM ROL ORDER BY ROL_ID")->fetchAll(PDO::FETCH_ASSOC);
10
11
 $render = "<legend>Roles</legend>";
12
 foreach ($lista as $modelo) {
13
  $id = htmlentities($modelo["ROL_ID"]);
14
  $descripcion = htmlentities($modelo["ROL_DESCRIPCION"]);
15
  $render .=
16
   "<p>
17
    <label style='display: flex'>
18
     <input type='checkbox' name='rolIds[]' value='$id'>
19
     <span>
20
      <strong style='display: block'>$id</strong>
21
      $descripcion
22
     </span>
23
    </label>
24
   </p>";
25
 }
26
27
 return $render;
28
}
29

C. php / usuario-agrega.php

1
<?php
2
3
require_once __DIR__ . "/lib/manejaErrores.php";
4
require_once __DIR__ . "/lib/recibeTextoObligatorio.php";
5
require_once __DIR__ . "/lib/recibeArray.php";
6
require_once __DIR__ . "/lib/usuRolAgrega.php";
7
require_once __DIR__ . "/lib/devuelveCreated.php";
8
require_once __DIR__ . "/Bd.php";
9
require_once __DIR__ . "/rolCheckboxes.php";
10
11
$san = recibeTextoObligatorio("san");
12
$rolIds = recibeArray("rolIds");
13
14
$bd = Bd::pdo();
15
$bd->beginTransaction();
16
17
$stmt = $bd->prepare(
18
 "INSERT INTO USUARIO (
19
    USU_SAN
20
   ) values (
21
    :USU_SAN
22
   )"
23
);
24
$stmt->execute([
25
 ":USU_SAN" => $san
26
]);
27
$usuId = $bd->lastInsertId();
28
29
usuRolAgrega($bd, $usuId, $rolIds);
30
31
$bd->commit();
32
33
$encodeUsuId = urlencode($usuId);
34
devuelveCreated("/php/usuario-vista-modifica.php?id=$encodeUsuId", [
35
 "id" => ["value" => $usuId],
36
 "san" => ["value" => $san],
37
 "roles" => ["innerHTML" =>  rolCheckboxes()],
38
 "rolIds[]" => ["value" => $rolIds],
39
]);
40

D. php / usuario-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
require_once __DIR__ . "/usuRolElimina.php";
8
9
$usuId = recibeEnteroObligatorio("id");
10
11
$bd = Bd::pdo();
12
$bd->beginTransaction();
13
14
usuRolElimina($bd, $usuId);
15
16
$stmt = $bd->prepare("DELETE FROM USUARIO WHERE USU_ID = :USU_ID");
17
$stmt->execute([":USU_ID" => $usuId]);
18
19
$bd->commit();
20
21
devuelveNoContent();
22

E. php / usuario-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/recibeArray.php";
7
require_once __DIR__ . "/lib/usuRolAgrega.php";
8
require_once __DIR__ . "/lib/devuelveJson.php";
9
require_once __DIR__ . "/Bd.php";
10
require_once __DIR__ . "/usuRolElimina.php";
11
require_once __DIR__ . "/rolCheckboxes.php";
12
13
$usuId = recibeEnteroObligatorio("id");
14
$san = recibeTextoObligatorio("san");
15
$rolIds = recibeArray("rolIds");
16
17
$bd = Bd::pdo();
18
$bd->beginTransaction();
19
20
$stmt = $bd->prepare(
21
 "UPDATE USUARIO
22
   SET
23
    USU_SAN = :USU_SAN
24
   WHERE
25
    USU_ID = :USU_ID"
26
);
27
$stmt->execute([
28
 ":USU_SAN" => $san,
29
 ":USU_ID" => $usuId,
30
]);
31
32
usuRolElimina($bd, $usuId);
33
34
usuRolAgrega($bd, $usuId, $rolIds);
35
36
$bd->commit();
37
38
devuelveJson([
39
 "id" => ["value" => $usuId],
40
 "san" => ["value" => $san],
41
 "roles" => ["innerHTML" =>  rolCheckboxes()],
42
 "rolIds" => ["value" => $rolIds],
43
]);
44

F. php / usuario-vista-agrega.php

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

G. php / usuario-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
    U.USU_ID,
11
    U.USU_SAN,
12
    GROUP_CONCAT(UR.ROL_ID, ', ') AS roles
13
   FROM
14
    USUARIO U LEFT JOIN USU_ROL UR
15
     ON U.USU_ID = UR.USU_ID
16
   GROUP BY
17
    U.USU_SAN
18
   ORDER BY
19
    U.USU_SAN"
20
);
21
$lista = $stmt->fetchAll(PDO::FETCH_ASSOC);
22
23
$render = "";
24
foreach ($lista as $modelo) {
25
 $encodeUsuId = urlencode($modelo["USU_ID"]);
26
 $usuId = htmlentities($encodeUsuId);
27
 $usuSan = htmlentities($modelo["USU_SAN"]);
28
 $roles = $modelo["roles"] === null || $modelo["roles"] === ""
29
  ? "<em>-- Sin roles --</em>"
30
  : htmlentities($modelo["roles"]);
31
 $render .=
32
  "<dt><a href='modifica.html?id=$usuId'>$usuSan</a></dt>
33
    <dd><a href='modifica.html?id=$usuId'>$roles</a></dd>";
34
}
35
36
devuelveJson(["lista" => ["innerHTML" => $render]]);
37

H. php / usuario-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__ . "/lib/rolIdsParaUsuId.php";
8
require_once __DIR__ . "/Bd.php";
9
require_once __DIR__ . "/rolCheckboxes.php";
10
11
$usuId = recibeEnteroObligatorio("id");
12
13
$bd = Bd::pdo();
14
15
$stmt = $bd->prepare("SELECT * FROM USUARIO WHERE USU_ID = :USU_ID");
16
$stmt->execute([":USU_ID" => $usuId]);
17
$modelo = $stmt->fetch(PDO::FETCH_ASSOC);
18
19
$modelo = validaEntidadObligatoria("Usuario",  $modelo);
20
21
$rolIds = rolIdsParaUsuId(Bd::pdo(), $usuId);
22
23
devuelveJson([
24
 "id" => ["value" => $usuId],
25
 "san" => ["value" => $modelo["USU_SAN"]],
26
 "roles" => ["innerHTML" =>  rolCheckboxes()],
27
 "rolIds[]" => $rolIds
28
]);
29

I. php / usuRolElimina.php

1
<?php
2
3
function usuRolElimina(\PDO $bd, string $usuId)
4
{
5
 $usuRolElimina = $bd->prepare("DELETE FROM USU_ROL WHERE USU_ID = :USU_ID");
6
 $usuRolElimina->execute([":USU_ID" => $usuId]);
7
}
8

J. 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 / recibeArray.php

1
<?php
2
3
/**
4
 * Devuelve los valores asociados a un
5
 * parámetro multivaluado; por ejemplo, un
6
 * grupo de checkbox, recibido en el servidor
7
 * por medio de GET, POST o cookie.
8
 * 
9
 * Si no se recibe el parámetro, devuelve [].
10
 * 
11
 * Si el valor recibido no es un arreglo, lo
12
 * coloca dentro de uno.
13
 */
14
function recibeArray(string $parametro)
15
{
16
 if (isset($_REQUEST[$parametro])) {
17
  $valor = $_REQUEST[$parametro];
18
  return is_array($valor)
19
   ? $valor
20
   : [$valor];
21
 } else {
22
  return [];
23
 }
24
}
25

11. 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

12. 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

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 / rolAgrega.php

1
<?php
2
3
function rolAgrega(\PDO $bd, string $id, string $descripcion)
4
{
5
 $rolAgrega = $bd->prepare(
6
  "INSERT INTO ROL (
7
     ROL_ID, ROL_DESCRIPCION
8
    ) VALUES (
9
     :ROL_ID, :ROL_DESCRIPCION
10
    )"
11
 );
12
 $rolAgrega->execute([
13
  ":ROL_ID" => $id,
14
  ":ROL_DESCRIPCION" => $descripcion,
15
 ]);
16
}
17

16. php / lib / rolBusca.php

1
<?php
2
3
function rolBusca(\PDO $bd, string $id)
4
{
5
 $rolBusca =  $bd->prepare("SELECT * FROM ROL WHERE ROL_ID = :ROL_ID");
6
 $rolBusca->execute([":ROL_ID" => $id]);
7
 $rol = $rolBusca->fetch(PDO::FETCH_ASSOC);
8
 return $rol;
9
}
10

17. php / lib / rolIdsParaUsuId.php

1
<?php
2
3
function rolIdsParaUsuId(\PDO $bd, int $usuId)
4
{
5
 $stmt = $bd->prepare(
6
  "SELECT ROL_ID
7
   FROM USU_ROL
8
   WHERE USU_ID = :USU_ID
9
   ORDER BY USU_ID"
10
 );
11
 $stmt->execute([":USU_ID" => $usuId]);
12
 $rolIds = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
13
 return $rolIds;
14
}
15

18. php / lib / usuRolAgrega.php

1
<?php
2
3
function usuRolAgrega(\PDO $bd, string $usuId, array $rolIds)
4
{
5
 $usuRolAgrega = $bd->prepare(
6
  "INSERT INTO USU_ROL (USU_ID, ROL_ID) values (:USU_ID, :ROL_ID)"
7
 );
8
 foreach ($rolIds as $rolId) {
9
  $usuRolAgrega->execute([
10
   ":USU_ID" => $usuId,
11
   ":ROL_ID" => $rolId,
12
  ]);
13
 }
14
}
15

19. 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 dataLength = 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 > dataLength
78
    && propiedad.startsWith(data_)
79
    && elemento instanceof HTMLElement
80
   ) {
81
    elemento.dataset[propiedad.substring(dataLength)] = 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