Newer
Older
flow-task / server / App / Models / Groups.php
  1. <?php
  2.  
  3. namespace App\Models;
  4.  
  5. use \App\Entity\Group;
  6.  
  7. class Groups {
  8. public function total_group_by_user(int $user_id) :int {
  9. $tablename = Group::get_tablename();
  10. $sql = "SELECT COUNT(*) FROM `{$tablename}` WHERE `user_id`='{$user_id}'";
  11.  
  12. $result = app() -> db() -> query($sql);
  13. if(!$result) {
  14. return throw new \Exception("Error of db query");
  15. }
  16.  
  17. $d = $result -> fetch_assoc();
  18. return $d["COUNT(*)"];
  19. }
  20.  
  21. public function create_group(int $user_id, String $title, String $type) :Group {
  22. $group = new Group();
  23. $group -> user_id = $user_id;
  24. $group -> title = $title;
  25. $group -> type = $type;
  26. $group -> position = $this -> total_group_by_user($user_id) + 1;
  27. $group -> update_at = get_formatted_timestamp();
  28. $group -> create_at = get_formatted_timestamp();
  29.  
  30. $group -> create_new();
  31.  
  32. return $group;
  33. }
  34.  
  35. public function get_groups_by_user_id(int $user_id) :Array {
  36. $tablename = Group::get_tablename();
  37. $sql = "SELECT * FROM `{$tablename}` WHERE `user_id`='{$user_id}' ORDER BY `position` ASC";
  38. $results = app() -> db() -> query($sql);
  39.  
  40. if(!$results) {
  41. return throw new \Exception("Error of query to database");
  42. }
  43.  
  44. $groups = [];
  45.  
  46. while($row = $results -> fetch_assoc()) {
  47. $groups[] = Group::instance_from_data($row);
  48. }
  49.  
  50. return $groups;
  51. }
  52.  
  53. public function change_group_position(int $group_id, int $new_position) :bool {
  54. $tablename = Group::get_tablename();
  55. $session = get_current_session();
  56. $groups = $session -> user() -> get_groups();
  57.  
  58. list($selected_group) = array_values(array_filter($groups, function($group) use($group_id) {
  59. return $group -> get_id() == $group_id;
  60. }));
  61.  
  62. $pos_min = min($selected_group -> position, $new_position);
  63. $pos_max = max($selected_group -> position, $new_position);
  64. $current_position = $selected_group->position;
  65.  
  66. foreach($groups as $i => $group) {
  67. if($group -> position < $pos_min or $group -> position > $pos_max) {
  68. continue;
  69. }
  70.  
  71. if($group -> get_id() == $group_id) {
  72. $group -> position = $new_position;
  73. continue;
  74. }
  75.  
  76. if ($new_position > $current_position) {
  77. if ($group->position > $current_position && $group->position <= $new_position) {
  78. $group->position--;
  79. }
  80. } else {
  81. if ($group->position < $current_position && $group->position >= $new_position) {
  82. $group->position++;
  83. }
  84. }
  85. }
  86.  
  87. array_map(function($group){
  88. $group -> update();
  89. }, $groups);
  90.  
  91. return true;
  92. }
  93. }