<commit_before><?php

    require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/ApiException.php';

    class DataFixtures extends AbstractData
    {
        /** 
        * Get tables by competition, optionally filter on season/team.
        * 
        * @param mixed $arrParams
        */
        public function getFixturesByCompetitionAndSeason($strFormat='json')
        {
            $arrRequired = array('competitionId', 'seasonId'); 
            $arrOptional = array();

            if (!self::hasRequiredParameters($arrRequired))
            {
                throw new ApiException("The following parameters are required: ".join(',',$arrRequired), 400);
            }       

            $arrParams = UrlParameters::getFullParamList($arrRequired, $arrOptional);            
            
            $strSql = "SELECT * FROM competition_fixture WHERE fix_competition = ? AND fix_season = ? AND fix_played = 0";
            $arrQueryParams = array($arrParams['competitionId'], $arrParams['seasonId']);

            $objQuery = $this->objDb->prepare($strSql);
            $objQuery->execute($arrQueryParams);
            return self::formatData($objQuery->fetchAll(PDO::FETCH_ASSOC), $strFormat);
        }
        
        /**
        * Generate all fixtures for a competition
        */
        public function createFixturesByCompetition()
        {
            $arrRequired = array('competitionId'); 
            $arrOptional = array();

            if (!self::hasRequiredParameters($arrRequired))
            {
                throw new ApiException("The following parameters are required: ".join(',',$arrRequired), 400);
            }       

            $arrParams = UrlParameters::getFullParamList($arrRequired, $arrOptional);            
            
            // TODO: Find the last season (if exists) and see if its been completed, if so, create a new season ID, if not, fail.
            //throw new ApiException("Season already underway", 400);
            
            // Roll fixture list & Build up a round of matches for each player.
            $arrTeams = DataTeams::getTeamsInCompetition('array');
            $intRoundSize = count($arrTeams) - 1;

            $arrFixtures = array();
            
            foreach($arrTeams as $intRound => $objHomeTeam)
            {
                $arrOpponents = $arrTeams;
                unset($arrOpponents[$intRound]); //don't want to play yourself.
                    
                foreach($arrOpponents as $intOpponentRound => $objAwayTeam) {
                    $intHomeTeamId = $objHomeTeam->teamId;
                    $arrFixtures[] = array('homeTeam'=>$objHomeTeam, 'awayTeam'=>$objAwayTeam);
                }                 
                shuffle($arrFixtures);                            
            }
            
            $arrFixtureRounds = array_fill(1,$intRoundSize,array());
            $arrTeamsInRound = array_fill(1,$intRoundSize,array());
                        
            while (!empty($arrFixtures)) {
                
                $intRound = 1;
                $bolAddedFixture = false;
                $arrFixture = array_shift($arrFixtures);
                
                while (!$bolAddedFixture) 
                {         
                    if (empty($arrTeamsInRound[$intRound]) || (!in_array($arrFixture['homeTeam']->teamId, $arrTeamsInRound[$intRound]) && !in_array($arrFixture['awayTeam']->teamId, $arrTeamsInRound[$intRound])))
                    {                    
                        $arrFixtureRounds[$intRound][] = $arrFixture;                   
                        $arrTeamsInRound[$intRound][] = $arrFixture['homeTeam']->teamId;
                        $arrTeamsInRound[$intRound][] = $arrFixture['awayTeam']->teamId;
                        $bolAddedFixture = true;
                    } else {
                        $intRound ++;
                    }                    
                }                
            }
                                     
            // TODO: Insert each fixture in a single db transaction.
            $this->objDb->beginTransaction();
            foreach ($arrFixtureRounds as $intRound=>$arrRoundFixtures)
            {
                foreach ($arrRoundFixtures as $arrFixture)
                {
                    $strSql = "INSERT INTO competition_fixture (fix_season, fix_competition, fix_round, fix_home_team, fix_away_team) VALUES (?, ?, ?, ?, ?)";    
                    $arrQueryParams = array(1, $arrParams['competitionId'], $intRound, $arrFixture['homeTeam']->teamId, $arrFixture['awayTeam']->teamId);
                    $objQuery = $this->objDb->prepare($strSql);
                    $objQuery->execute($arrQueryParams);
                }
            }
            $this->objDb->commit();
                                    
            // TODO: Return the season ID
            
        }

    }
?><commit_msg>Fixture Drawing<commit_after><?php

    require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/ApiException.php';

    class DataFixtures extends AbstractData
    {
        /** 
        * Get tables by competition, optionally filter on season/team.
        * 
        * @param mixed $arrParams
        */
        public function getFixturesByCompetitionAndSeason($strFormat='json')
        {
            $arrRequired = array('competitionId', 'seasonId'); 
            $arrOptional = array();

            if (!self::hasRequiredParameters($arrRequired))
            {
                throw new ApiException("The following parameters are required: ".join(',',$arrRequired), 400);
            }       

            $arrParams = UrlParameters::getFullParamList($arrRequired, $arrOptional);            
            
            $strSql = "SELECT * FROM competition_fixture WHERE fix_competition = ? AND fix_season = ? AND fix_played = 0";
            $arrQueryParams = array($arrParams['competitionId'], $arrParams['seasonId']);

            $objQuery = $this->objDb->prepare($strSql);
            $objQuery->execute($arrQueryParams);
            return self::formatData($objQuery->fetchAll(PDO::FETCH_ASSOC), $strFormat);
        }
        
        /**
        * Generate all fixtures for a competition
        */
        public function createFixturesByCompetition($strFormat='json')
        {
            $arrRequired = array('competitionId'); 
            $arrOptional = array();

            if (!self::hasRequiredParameters($arrRequired))
            {
                throw new ApiException("The following parameters are required: ".join(',',$arrRequired), 400);
            }       

            $arrParams = UrlParameters::getFullParamList($arrRequired, $arrOptional);            
                        
            // Roll fixture list & Build up a round of matches for each player.
            $arrTeams = DataTeams::getTeamsInCompetition('array');
            shuffle($arrTeams); //Randomly ordering the teams prevents fixtures always being in the same order.
            
            $intNumTeams = count($arrTeams);
            
            //Even up the teams so that fixtures can always be plotted, in unevenly number leagues, each team will have a round where they don't play.
            if ($intNumTeams % 2 == 1) {
                $intNumTeams++;
            }
            
            $intTotalRounds = $intNumTeams - 1;
            $intMatchesPerRound = $intNumTeams / 2;
            
            //Some of this logic borrowed from http://bluebones.net/2005/05/generating-fixture-lists/
            for ($intRound = 0; $intRound < $intTotalRounds; $intRound++)
            {
                for ($intMatch = 0; $intMatch < $intMatchesPerRound; $intMatch++)
                {
                    $intHome = ($intRound + $intMatch) % ($intNumTeams - 1);
                    $intAway = ($intNumTeams - 1 - $intMatch + $intRound) % ($intNumTeams - 1);
                    
                    if ($intMatch == 0)
                    {
                        $intAway = $intNumTeams - 1;
                    }
                                        
                    if (!empty($arrTeams[$intHome]) && !empty($arrTeams[$intAway]))
                    {
                        $arrFixtureRounds[$intRound][$intMatch] = array($arrTeams[$intHome], $arrTeams[$intAway]);    
                    }                                                        
                }
            }            
                                                            
            return self::formatData($arrFixtureRounds, $strFormat);            
        }

    }
?>
{'fraction_non_alphanumeric': 0.11114994757077945, 'fraction_numerical': 0.004543865781195386, 'mean_word_length': 1.5143526654950206, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 32, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3815607', 'n_tokens_mistral': 2235, 'n_tokens_neox': 2082, 'n_words': 431}