TagController.php 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. <?php
  2. namespace App\Controllers\Api;
  3. use App\Models\TagModel;
  4. use App\Utils\DB;
  5. use PH7\JustHttp\StatusCode;
  6. use Respect\Validation\Exceptions\NestedValidationException;
  7. use Respect\Validation\Validator as v;
  8. class TagController
  9. {
  10. /*
  11. * Obtiene las reglas de validación.
  12. */
  13. private function getValidationRules()
  14. {
  15. return [
  16. 'id' => v::stringType()->NotEmpty()->Uuid(),
  17. 'name' => v::stringType()->NotEmpty()->length(1, 64, true)
  18. ];
  19. }
  20. /*
  21. * Registra el tag de un usuario.
  22. */
  23. public function create($req, $res)
  24. {
  25. $data = [];
  26. $rules = $this->getValidationRules();
  27. // Selecciona solo los campos necesarios.
  28. $fields = array_diff(array_keys($rules), ['id']);
  29. // Obtiene los campos del cuerpo de la petición.
  30. foreach ($fields as $field) {
  31. if (v::key($field, v::notOptional(), true)->validate($req->body)) {
  32. $data[$field] = $req->body[$field];
  33. }
  34. }
  35. // Comprueba los campos del cuerpo de la petición.
  36. try {
  37. v::key('name', $rules['name'], true)->assert($data);
  38. } catch (NestedValidationException $e) {
  39. $res->status(StatusCode::BAD_REQUEST)->json([
  40. 'validations' => $e->getMessages()
  41. ]);
  42. }
  43. // Limpia espacios sobrantes del nombre del nuevo tag.
  44. $data['name'] = trim($data['name']);
  45. $userAuth = $req->app->local('userAuth');
  46. $tagModel = TagModel::factory();
  47. $existsNewTag = $tagModel
  48. ->select('id')
  49. ->where('user_id', $userAuth['id'])
  50. ->where('name', $data['name'])
  51. ->value('id');
  52. // Comprueba que el tag sea único.
  53. if (!empty($existsNewTag)) {
  54. $res->status(StatusCode::CONFLICT)->json([
  55. 'error' => 'A tag already exists with that name'
  56. ]);
  57. }
  58. // Genera el UUID del nuevo tag.
  59. $data['id'] = DB::generateUuid();
  60. // Relaciona la nota al usuario.
  61. $data['user_id'] = $userAuth['id'];
  62. $data['created_at'] = $data['updated_at'] = DB::datetime();
  63. // Registra la información del nuevo tag.
  64. $tagModel->reset()->insert($data);
  65. // Consulta la información del tag registrado.
  66. $newTag = $tagModel
  67. ->reset()
  68. ->select('id, name, user_id, created_at, updated_at')
  69. ->find($data['id']);
  70. $res->status(StatusCode::CREATED)->json([
  71. 'data' => $newTag
  72. ]);
  73. }
  74. /*
  75. * Consulta los tags de un usuario.
  76. */
  77. public function index($req, $res)
  78. {
  79. $userAuth = $req->app->local('userAuth');
  80. $tagModel = tagModel::factory();
  81. // Consulta la información de los tags del usuario.
  82. $tags = $tagModel
  83. ->select('tags.id, tags.name, COUNT(notes_tags.id) AS number_notes, tags.created_at, tags.updated_at')
  84. ->notesTags()
  85. ->where('tags.user_id', $userAuth['id'])
  86. ->groupBy('tags.id')
  87. ->orderBy('tags.updated_at DESC')
  88. ->get();
  89. $res->json([
  90. 'data' => $tags
  91. ]);
  92. }
  93. /*
  94. * Consulta la información del tag de un usuario.
  95. */
  96. public function show($req, $res)
  97. {
  98. $params = $req->params;
  99. $rules = $this->getValidationRules();
  100. // Comprueba los parámetros de la ruta.
  101. try {
  102. v::key('uuid', $rules['id'], true)->assert($params);
  103. } catch (NestedValidationException $e) {
  104. $res->status(StatusCode::BAD_REQUEST)->json([
  105. 'error' => $e->getMessage()
  106. ]);
  107. }
  108. $userAuth = $req->app->local('userAuth');
  109. // Consulta la información del tag.
  110. $tag = TagModel::factory()
  111. ->select('id, user_id, name, created_at, updated_at')
  112. ->where('user_id', $userAuth['id'])
  113. ->find($params['uuid']);
  114. // Comprueba que el tag se encuentra registrado.
  115. if (empty($tag)) {
  116. $res->status(StatusCode::NOT_FOUND)->json([
  117. 'error' => 'Tag cannot be found'
  118. ]);
  119. }
  120. $res->json([
  121. 'data' => $tag
  122. ]);
  123. }
  124. /*
  125. * Modifica o actualiza la información
  126. * del tag de un usuario.
  127. */
  128. public function update($req, $res)
  129. {
  130. $params = $req->params;
  131. $rules = $this->getValidationRules();
  132. // Comprueba los parámetros de la ruta.
  133. try {
  134. v::key('uuid', $rules['id'], true)->assert($params);
  135. } catch (NestedValidationException $e) {
  136. $res->status(StatusCode::BAD_REQUEST)->json([
  137. 'error' => $e->getMessage()
  138. ]);
  139. }
  140. $userAuth = $req->app->local('userAuth');
  141. $tagModel = TagModel::factory();
  142. // Consulta la información del tag que será modificado.
  143. $tag = $tagModel
  144. ->select('id')
  145. ->where('user_id', $userAuth['id'])
  146. ->find($params['uuid']);
  147. // Comprueba que el tag se encuentra registrado.
  148. if (empty($tag)) {
  149. $res->status(StatusCode::NOT_FOUND)->json([
  150. 'error' => 'Tag cannot be found'
  151. ]);
  152. }
  153. $data = [];
  154. // Selecciona solo los campos necesarios.
  155. $fields = array_diff(array_keys($rules), ['id']);
  156. // Obtiene los campos del cuerpo de la petición.
  157. foreach ($fields as $field) {
  158. if (v::key($field, v::notOptional(), true)->validate($req->body)) {
  159. $data[$field] = $req->body[$field];
  160. }
  161. }
  162. // Comprueba los campos del cuerpo de la petición.
  163. try {
  164. v::key('name', $rules['name'], false)->assert($data);
  165. } catch (NestedValidationException $e) {
  166. $res->status(StatusCode::BAD_REQUEST)->json([
  167. 'validations' => $e->getMessages()
  168. ]);
  169. }
  170. /*
  171. * Comprueba que el nombre del tag sea único
  172. * solo si encuentra presente.
  173. */
  174. if (v::key(('name'), v::notOptional(), true)->validate($data)) {
  175. $data['name'] = trim($data['name']);
  176. $existsTag = $tagModel
  177. ->reset()
  178. ->select('id')
  179. ->where('user_id', $userAuth['id'])
  180. ->where('name', $data['name'])
  181. ->where('id', '!=', $tag['id'])
  182. ->value('id');
  183. if (!empty($existsTag)) {
  184. $res->status(StatusCode::CONFLICT)->json([
  185. 'error' => 'A tag already exists with that name'
  186. ]);
  187. }
  188. }
  189. // Modifica total o parcialmente la información del tag del usuario.
  190. if (!empty($data)) {
  191. $data['updated_at'] = DB::datetime();
  192. $tagModel
  193. ->reset()
  194. ->where('id', $tag['id'])
  195. ->update($data);
  196. }
  197. // Consulta la información del tag modificado.
  198. $updatedTag = $tagModel
  199. ->reset()
  200. ->select('tags.id, tags.name, COUNT(notes_tags.id) AS number_notes, tags.created_at, tags.updated_at')
  201. ->notesTags()
  202. ->groupBy('tags.id')
  203. ->find($tag['id']);
  204. $res->json([
  205. 'data' => $updatedTag
  206. ]);
  207. }
  208. /*
  209. * Elimina el tag de un usuario.
  210. */
  211. public function delete($req, $res)
  212. {
  213. $params = $req->params;
  214. $rules = $this->getValidationRules();
  215. // Comprueba los parámetros de la ruta.
  216. try {
  217. v::key('uuid', $rules['id'], true)->assert($params);
  218. } catch (NestedValidationException $e) {
  219. $res->status(StatusCode::BAD_REQUEST)->json([
  220. 'error' => $e->getMessage()
  221. ]);
  222. }
  223. $userAuth = $req->app->local('userAuth');
  224. $tagModel = TagModel::factory();
  225. // Consulta la información del tag que será eliminado.
  226. $deletedTag = $tagModel
  227. ->select('tags.id, tags.name, COUNT(notes_tags.id) AS number_notes, tags.created_at, tags.updated_at')
  228. ->notesTags()
  229. ->where('tags.user_id', $userAuth['id'])
  230. ->groupBy('tags.id')
  231. ->find($params['uuid']);
  232. // Comprueba que el tag se encuentra registrado.
  233. if (empty($deletedTag)) {
  234. $res->status(StatusCode::NOT_FOUND)->json([
  235. 'error' => 'Tag cannot be found'
  236. ]);
  237. }
  238. // Elimina la información del tag.
  239. $tagModel
  240. ->reset()
  241. ->where('id', $deletedTag['id'])
  242. ->delete();
  243. $res->json([
  244. 'data' => $deletedTag
  245. ]);
  246. }
  247. }