tippspiel/pfosten/app/leagues/League.php
2017-10-25 10:42:05 +02:00

414 lines
15 KiB
PHP

<?php
namespace App\Leagues;
use Illuminate\Database\Eloquent\Model;
use App\Season;
use App\Round;
use App\User;
use DB;
use Log;
class League extends Model
{
const RANK_LEAGUE1 = 1;
const RANK_LEAGUE2 = 2;
const RANK_LEAGUE3 = 3;
const RANK_QUALIFICATION = 4;
protected $table ='leagues';
protected $fillable = [
'id','season_id','is_qualification','rank','subrank','start_round_id','round_count','name'
];
//
public static function neededLeagues($member_count, $round_count) {
$max_members_per_league=22;
if ( $round_count < $max_members_per_league-1 ) { $max_members_per_league = $round_count+1; }
if ($member_count <= $max_members_per_league) return $member_count;
$neededLeagues = intdiv($member_count, $max_members_per_league);
if ( $member_count - $max_members_per_league * $neededLeagues ) {
$neededLeagues+=1;
}
return $neededLeagues;
}
public static function getMemberCount($league_id) {
$members = DB::table('leagues_members')->where('league_id','=',$league_id)->get();
return sizeof($members);
}
public static function getNames() {
$season = Season::getCurrent();
$leagues = League::where('season_id','=',$season->id)->orderBy('rank')->orderBy('name')->get();
$leagueNames = array();
foreach($leagues as $league) {
$leagueNames[$league->id] = $league->name;
}
return $leagueNames;
}
public static function getStartRoundId($leagueId)
{
$league = League::where('id','=',$leagueId)->first();
return $league->start_round_id;
}
public static function cmpScore($score1, $score2) {
// [0] = user-id
$_score1 = $score1[1];
$goals1 = $score1[2];
$cGoals1 = $score1[3];
$_score2 = $score2[1];
$goals2 = $score2[2];
$cGoals2 = $score2[3];
$diff1 = $goals1-$cGoals1;
$diff2 = $goals2-$cGoals2;
if ($_score1 == $_score2) {
if ($diff1==$diff2) {
if ($goals1 == $goals2) {
return $cGoals1 > $cGoals2;
}
return ( $goals1 < $goals2 );
}
return ($diff1<$diff2);
}
return ($_score1 < $_score2);
}
public static function getRanking($rank, $seasonId=-1) {
$season = Season::getCurrent();
if ($seasonId > -1) { $season=Season::where('id','=',$seasonId)->first(); };
$leagues = League::where('rank','=',$rank)->where('season_id','=', $season->id)->orderBy('id')->get();
error_log("LeagueCount:".sizeof($leagues));
$leagueScores=array();
foreach($leagues as $league) {
$memberIds = LeagueMember::getMembers($league->id);
$memberScores =array();
foreach($memberIds as $memberId) {
$tpl=array();
$tpl[0]=$memberId;
$tpl[1]=0; // league_score
$tpl[2]=0; // goals
$tpl[3]=0; // countergoals
$memberScores[$memberId] = $tpl;
}
$matches=Match::getMatchResults($league->id,-1);
foreach ($matches as $match) {
if (Round::isCompleted($match->round_id)) {
$memberScores[$match->user1_id][1] += $match->user1_league_score;
$memberScores[$match->user1_id][2] += $match->user1_rankscore; // goals
$memberScores[$match->user1_id][3] += $match->user2_rankscore; // countergoals
$memberScores[$match->user2_id][1] += $match->user2_league_score;
$memberScores[$match->user2_id][2] += $match->user2_rankscore; // goals
$memberScores[$match->user2_id][3] += $match->user1_rankscore; // countergoals
}
}
usort($memberScores, array('App\Leagues\League','cmpScore'));
$leagueScores[$league->id]=$memberScores;
}
return $leagueScores;
}
// Für Auf/Abstiegsberechnung - wird auf previous Season angewendet.
public static function getUnifiedRanking($rank, $seasonId=-1) {
$leagueScores = League::getRanking($rank, $seasonId);
$unifiedScores = array();
foreach($leagueScores as $leagueId => $singleLeagueScores) {
foreach ($singleLeagueScores as $placeNr => $singleLeagueScore) {
$userId=$singleLeagueScores[$placeNr][0];
$unifiedScores[$userId]=$singleLeagueScores[$placeNr];
}
}
usort($unifiedScores,array('App\Leagues\League','cmpScore'));
return $unifiedScores;
}
// ausfaktoriert aus LeaguesController::createLeagues()
// TODO: $round_count ist nur im Quali-Modus relevant und steuert, wieviele Quali-Gruppen benötigt werden.
// TODO: Sobald es Liga1 und Liga2 gibt, wird der round_count immer 21 sein, da Liga1 und Liga2 auf
// TODO: 22 Mitspieler festgelegt sind.
public static function createLeagues($start_round_id, $round_count) {
$currentSeason=Season::getCurrent();
// Eventuell vorhandene Ligen loeschen
$leagues=League::where('season_id','=',$currentSeason->id)->get();
if ($leagues) {
foreach ($leagues as $league) {
DB::table('leagues_matches')->where('league_id', '=', $league->id)->delete();
DB::table('leagues_members')->where('league_id', '=', $league->id)->delete();
DB::table('leagues')->where('id', '=', $league->id)->delete();
}
}
$active_member_count=sizeof(User::getActives());
Log::info("Aktive Spieler: ".$active_member_count);
$neededLeagues = League::neededLeagues($active_member_count, $round_count);
Log::info("Benötigte Quali-Gruppen: ".$neededLeagues);
$league_ids=array();
//TODO: Den Leaguemode kann die Methode selbst rausfinden.
//TODO: Wenn es keine Vorsaison gibt -> Qualifikation
//TODO: Ansonsten: Ligen erzeugen.
$league_mode="Qualifikation";
if ($league_mode=="Qualifikation") {
for ($league_nr=1; $league_nr<=$neededLeagues; $league_nr+=1) {
$league = League::create([
'is_qualification' => true,
'name' => 'Qualifikationsgruppe '.$league_nr,
'rank' => '4',
'subrank' => $league_nr,
'round_count' => $round_count,
'season_id' => $currentSeason->id,
'start_round_id' => $start_round_id
]);
$league->save();
$league_ids[$league_nr-1] = $league->id;
}
// Distribute members
$users = User::getActives();
shuffle($users);
$league_index=0;
Log::info("Distributing Members between groups");
while(sizeof($users)>0) {
$user = array_pop($users);
$leagueMember = LeagueMember::create([
'user_id' => $user->id,
'league_id' => $league_ids[$league_index]
]);
$leagueMember->save();
$league_index+=1;
if (sizeof($league_ids)==$league_index) { $league_index=0; }
}
} else {
// ToDo: Branch Qualifikation/Liga entfällt in Zukunft, da Quali der Fallback für den Fall ist, dass keine vorherige Saison existiert.
// Pokal und Play-Off findet hier nicht statt, da diese Wettbewerbe die Matches abgängig von existierenden Vorrunden-Ergebnissen erzeugen,
// und daher zwangsläufig inkrementell sein müssen.
$league_size1= min(22,$active_member_count);
$league1 = League::create([
'is_qualification' => false,
'name' => 'Spielerliga 1',
'rank' => '1',
'subrank' => '1',
'round_count' => $round_count,
'season_id' => $currentSeason->id,
'start_round_id' => $start_round_id
]);
$league_size2=min(22,$active_member_count - $league_size1);
if ($league_size2>0) {
$league2 = League::create([
'is_qualification' => false,
'name' => 'Spielerliga 2',
'rank' => '2',
'subrank' => '1',
'round_count' => $round_count,
'season_id' => $currentSeason->id,
'start_round_id' => $start_round_id
]);
$league_size3 = $active_member_count - $league_size1 - $league_size2;
if ($league_size3>0) {
$neededLeagues = League::neededLeagues($league_size3, $round_count);
for ($league_nr=1; $league_nr<=$neededLeagues; $league_nr+=1) {
$league = League::create([
'is_qualification' => false,
'name' => 'Spielerliga 3, Gruppe '.$league_nr,
'rank' => '3',
'subrank' => $league_nr,
'round_count' => $round_count,
'season_id' => $currentSeason->id,
'start_round_id' => $start_round_id
]);
$league->save();
}
}
// TODO: LeagueMembers zu den Leagues hinzufügen, abhängig vom zuzuordnenden Platz
}
}
}
// Aktuelle Liga-Zuordnung auf Basis des Rangs in der letzten Liga
// Oder des Rangs in der Qualifikation
// oder erstellung des Quali Rangs wenn es keine previous Season gibt.
// Liga-Zugehörigkeit festlegen. Setzt voraus, dass die Ligen bereits erzeugt wurden.
public static function setLeagueForPlayers()
/*
* setLeagueForPlayers__NEW_QUALIFICATION case1
* setLeagueForPlayers__FROM_QUALIFICATION case2
* setLeagueForPlayers__FROM_LEAGUES case3
*/
{
$previousSeason = Season::getPrevious();
$currentSeason = Season::getCurrent();
$users = User::getActives();
if (!$previousSeason) {
// case 1: first season ever, no previous season exists, qualification (league-rank=4)
} elseif (Season::hasQualification($previousSeason->id)){
// case 2: previous season was qualification season (rank 4)
} else { /*case 3 - default: determine league-ranks 1,2,3 from previous Season rank verwenden*/
}
// 2 Möglichkeiten:
// 1.) previousSeason hat rank=4 => Qualification Round
// 2.) sonst aus .
$usersLastSeason = User::getActives($previousSeason->id);
$league1 = League::getUnifiedRanking(1, $previousSeason->id);
$league2 = League::getUnifiedRanking( 2, $previousSeason->id);
$league3 = League::getUnifiedRanking( 3, $previousSeason->id);
//$lastLeagues = League::where('season_id','=',$previousSeason->id)->get();
/*
foreach ($users as $index => $user) {
$found = false;
foreach ($usersLastSeason as $userLastSeason) {
if ($userLastSeason->id == $user->id) $found = true;
}
if (!$found) {
$users[$index]['rank']=League::RANK_LEAGUE3; // In der letzten Season unter den Actives nicht gefunden
$leagueMember = LeagueMember::create([
'user_id' => $user->id,
'league_id' => $league3->id
]);
$leagueMember->save();
} else {
// League1, 1-16: RANK_LEAGUE1
// League1, 17-22: RANK_LEAGUE2
// League2, 1-6: RANK_LEAGUE1
// League2, 7-16: RANK_LEAGUE2
// League2, 17-22: RANK_LEAGUE3
// League3, best6: RANK_LEAGUE2
// League3, 7-end: RANK_LEAGUE3
//
//alte Ligen durchsuchen und entsprechend einordnen
foreach($league1 as $index => $entry) {
$userId = $entry[0];
$score = $entry[1];
$goals = $entry[2];
$cGoals = $entry[3];
$leagueId = -1;
if ($user->id == $userId) {
$rank=-1;
if ($index<16) {
$rank=1;
$leagueId=$league1->id;
} else {
$rank=2;
$leagueId=$league2->id;
}
$leagueMember = LeagueMember::create([
'user_id' => $userId,
'league_id' => $leagueId
]);
$leagueMember->save();
}
}
foreach($league2 as $index => $entry) {
$userId = $entry[0];
$score = $entry[1];
$goals = $entry[2];
$cGoals = $entry[3];
$leagueId = -1;
if ($user->id == $userId) {
$rank=-1;
$leagueId=$league1->id;
if ($index<6) {
$rank=1;
} elseif ($index<16) {
$rank=2;
$leagueId=$league2->id;
} else {
$rank=3;
$leagueId=$league3->id;
}
$leagueMember = LeagueMember::create([
'user_id' => $userId,
'league_id' => $leagueId
]);
$leagueMember->save();
}
}
foreach($league3 as $index => $entry) {
$userId = $entry[0];
$score = $entry[1];
$goals = $entry[2];
$cGoals = $entry[3];
if ($user->id == $userId) {
$rank=-1;
if ($index<6) {
$rank=2;
$leagueId=$league2->id;
} else {
$rank=3;
$leagueId=$league3->id;
}
$leagueMember = LeagueMember::create([
'user_id' => $userId,
'league_id' => $leagueId
]);
$leagueMember->save();
}
}
}
}
*/
}
}