<?php namespace App\Models; use \App\Entity\Group; class Groups { public function total_group_by_user(int $user_id) :int { $tablename = Group::get_tablename(); $sql = "SELECT COUNT(*) FROM `{$tablename}` WHERE `user_id`='{$user_id}'"; $result = app() -> db() -> query($sql); if(!$result) { return throw new \Exception("Error of db query"); } $d = $result -> fetch_assoc(); return $d["COUNT(*)"]; } public function create_group(int $user_id, String $title, String $type) :Group { $group = new Group(); $group -> user_id = $user_id; $group -> title = $title; $group -> type = $type; $group -> position = $this -> total_group_by_user($user_id) + 1; $group -> update_at = get_formatted_timestamp(); $group -> create_at = get_formatted_timestamp(); $group -> create_new(); return $group; } public function get_groups_by_user_id(int $user_id) :Array { $tablename = Group::get_tablename(); $sql = "SELECT * FROM `{$tablename}` WHERE `user_id`='{$user_id}' ORDER BY `position` ASC"; $results = app() -> db() -> query($sql); if(!$results) { return throw new \Exception("Error of query to database"); } $groups = []; while($row = $results -> fetch_assoc()) { $groups[] = Group::instance_from_data($row); } return $groups; } public function change_group_position(int $group_id, int $new_position) :bool { $tablename = Group::get_tablename(); $session = get_current_session(); $groups = $session -> user() -> get_groups(); list($selected_group) = array_values(array_filter($groups, function($group) use($group_id) { return $group -> get_id() == $group_id; })); $pos_min = min($selected_group -> position, $new_position); $pos_max = max($selected_group -> position, $new_position); $current_position = $selected_group->position; foreach($groups as $i => $group) { if($group -> position < $pos_min or $group -> position > $pos_max) { continue; } if($group -> get_id() == $group_id) { $group -> position = $new_position; continue; } if ($new_position > $current_position) { if ($group->position > $current_position && $group->position <= $new_position) { $group->position--; } } else { if ($group->position < $current_position && $group->position >= $new_position) { $group->position++; } } } array_map(function($group){ $group -> update(); }, $groups); return true; } }