summaryrefslogtreecommitdiff
path: root/app/Rugby/Factory/Service.php
blob: fa8028fcc988b06a43ce375ca4d763ced28adcd5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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']);
    }
}