diff options
Diffstat (limited to 'app/Rugby/Factory/Service.php')
| -rw-r--r-- | app/Rugby/Factory/Service.php | 71 | 
1 files changed, 71 insertions, 0 deletions
| diff --git a/app/Rugby/Factory/Service.php b/app/Rugby/Factory/Service.php new file mode 100644 index 0000000..fa8028f --- /dev/null +++ b/app/Rugby/Factory/Service.php @@ -0,0 +1,71 @@ +<?php + +namespace App\Rugby\Factory; + +use App\Rugby\Model; +use App\Rugby\Factory\DataAdapter; + +class Service +{ +    protected $data_adapter; + +    public function __construct(DataAdapter $data_adapter) +    { +        $this->data_adapter = $data_adapter; +    } + +    public function save() +    { +        $tournament = Model\Tournament::where(['name' => $this->data_adapter->getTournamentName()])->first(); + +        if (!$tournament) { +            $tournament = Model\Tournament::create(['name' => $this->data_adapter->getTournamentName()]); +        } + +        foreach ($this->data_adapter->getData() as $match_data) { +            $this->processMatch($match_data, $tournament); +        } +    } + +    protected function processMatch(array $data, Model\Tournament $tournament) +    { +        $venue = Model\Venue::where('name', '=', $data['venue_name'])->first(); + +        if (!$venue) { +            $venue = Model\Venue::create( +                [ +                    'city' => $data['venue_city'], +                    'name' => $data['venue_name'] +                ] +            ); +        } + +        $home_team = Model\Team::where('name', '=', $data['team_home'])->first(); + +        if (!$home_team) { +            $home_team = Model\Team::Create(['name' => $data['team_home']]); +        } + +        $away_team = Model\Team::where('name', '=', $data['team_away'])->first(); + +        if (!$away_team) { +            $away_team = Model\Team::Create(['name' => $data['team_away']]); +        } + +        $match = Model\Match::create( +            [ +                'date' => (new \Carbon\Carbon($data['match_date']))->format('Y-m-d H:i:s'), +                'score' => $data['match_score'], +                'half_score' => $data['match_half_score'], +                'referee' => $data['match_referee'] ?? null, +            ] +        ); + +        $match->venue_id = $venue->id; +        $match->save(); + +        $match->tournaments()->save($tournament); +        $match->teams()->attach($home_team, ['is_home' => '1']); +        $match->teams()->attach($away_team, ['is_home' => '0']); +    } +} | 
