Completed
Push — feature/team-activity ( 2f8466 )
by Vladimir
02:53
created

TeamController::createAction()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
use BZIon\Event as Event;
4
use BZIon\Event\Events;
5
use Symfony\Component\Form\FormError;
6
use Symfony\Component\HttpFoundation\RedirectResponse;
7
use Symfony\Component\HttpFoundation\Request;
8
9
class TeamController extends CRUDController
10
{
11
    /**
12
     * The new leader if we're changing them
13
     * @var null|Player
14
     */
15
    private $newLeader = null;
16
17
    public function showAction(Team $team)
18
    {
19
        $creationDate = $team->getCreationDate()->setTimezone('UTC')->startOfMonth();
20
21
        $matches = Match::getQueryBuilder()
22
            ->with($team)
23
            ->getSummary($creationDate);
24
25
        $wins = Match::getQueryBuilder()
26
            ->with($team, "win")
27
            ->getSummary($creationDate);
28
29
        return [
30
            'matches' => $matches,
31
            'wins'    => $wins,
32
            'team'    => $team
33
        ];
34
    }
35
36
    public function listAction(Request $request)
37
    {
38
        $teamQB = Team::getQueryBuilder()
39
            ->active()
40
            ->sortBy('elo')->reverse()
41
        ;
42
43
        // Cache team captains so we don't fetch each manually
44
        $captains = $teamQB->getArray('leader');
45
        $captIDs = array_column($captains, 'leader');
46
        Player::getQueryBuilder()
47
            ->where('id')->isOneOf($captIDs)
48
            ->addToCache()
49
        ;
50
51
        return [
52
            'teams'   => $teamQB->withMatchActivity()->getModels($fast = true),
53
            'showAll' => (bool)$request->get('showAll', false),
54
        ];
55
    }
56
57
    public function createAction(Player $me)
58
    {
59
        return $this->create($me);
60
    }
61
62 View Code Duplication
    public function editAction(Player $me, Team $team)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
63
    {
64
        // TODO: Generating this response is unnecessary
65
        $response = $this->edit($team, $me, "team");
66
67
        if ($this->newLeader) {
68
            // Redirect to a confirmation form if we are assigning a new leader
69
            $url = Service::getGenerator()->generate('team_assign_leader', array(
70
                'team'   => $team->getAlias(),
71
                'player' => $this->newLeader->getAlias()
72
            ));
73
74
            return new RedirectResponse($url);
75
        }
76
77
        return $response;
78
    }
79
80
    public function deleteAction(Player $me, Team $team)
81
    {
82
        $members = $team->getMembers();
83
84
        return $this->delete($team, $me, function () use ($team, $me, $members) {
85
            $event = new Event\TeamDeleteEvent($team, $me, $members);
86
            Service::getDispatcher()->dispatch(Events::TEAM_DELETE, $event);
87
        });
88
    }
89
90 View Code Duplication
    public function joinAction(Team $team, Player $me)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
91
    {
92
        $this->requireLogin();
93
        if (!$me->isTeamless()) {
94
            throw new ForbiddenException("You are already a member of a team");
95
        } elseif ($team->getStatus() != 'open') {
96
            throw new ForbiddenException("This team is not accepting new members without an invitation");
97
        }
98
99
        return $this->showConfirmationForm(function () use ($team, $me) {
100
            $team->addMember($me->getId());
101
            Service::getDispatcher()->dispatch(Events::TEAM_JOIN,  new Event\TeamJoinEvent($team, $me));
102
103
            return new RedirectResponse($team->getUrl());
104
        },  "Are you sure you want to join {$team->getEscapedName()}?",
105
            "You are now a member of {$team->getName()}");
106
    }
107
108
    public function kickAction(Team $team, Player $player, Player $me)
109
    {
110
        $this->assertCanEdit($me, $team, "You are not allowed to kick a player off that team!");
111
112
        if ($team->getLeader()->isSameAs($player)) {
113
            throw new ForbiddenException("You can't kick the leader off their team.");
114
        }
115
116
        if (!$team->isMember($player->getId())) {
117
            throw new ForbiddenException("The specified player is not a member of that team.");
118
        }
119
120
        return $this->showConfirmationForm(function () use ($me, $team, $player) {
121
            $team->removeMember($player->getId());
122
            $event = new Event\TeamKickEvent($team, $player, $me);
123
            Service::getDispatcher()->dispatch(Events::TEAM_KICK, $event);
124
125
            return new RedirectResponse($team->getUrl());
126
        },  "Are you sure you want to kick {$player->getEscapedUsername()} from {$team->getEscapedName()}?",
127
            "Player {$player->getUsername()} has been kicked from {$team->getName()}", "Kick");
128
    }
129
130 View Code Duplication
    public function abandonAction(Team $team, Player $me)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
131
    {
132
        if (!$team->isMember($me->getId())) {
133
            throw new ForbiddenException("You are not a member of that team!");
134
        }
135
136
        if ($team->getLeader()->isSameAs($me)) {
137
            throw new ForbiddenException("You can't abandon the team you are leading.");
138
        }
139
140
        return $this->showConfirmationForm(function () use ($team, $me) {
141
            $team->removeMember($me->getId());
142
            Service::getDispatcher()->dispatch(Events::TEAM_ABANDON, new Event\TeamAbandonEvent($team, $me));
143
144
            return new RedirectResponse($team->getUrl());
145
        },  "Are you sure you want to abandon {$team->getEscapedName()}?",
146
            "You have left {$team->getName()}", "Abandon");
147
    }
148
149
    public function assignLeaderAction(Team $team, Player $me, Player $player)
150
    {
151
        $this->assertCanEdit($me, $team, "You are not allowed to change the leader of this team.");
152
153
        if (!$team->isMember($player->getId())) {
154
            throw new ForbiddenException("The specified player is not a member of {$team->getName()}");
155
        } elseif ($team->getLeader()->isSameAs($player)) {
156
            throw new ForbiddenException("{$player->getUsername()} is already the leader of {$team->getName()}");
157
        }
158
159
        return $this->showConfirmationForm(function () use ($player, $team) {
160
            $event = new Event\TeamLeaderChangeEvent($team, $player, $team->getLeader());
161
            $team->setLeader($player->getId());
162
            Service::getDispatcher()->dispatch(Events::TEAM_LEADER_CHANGE, $event);
163
164
            return new RedirectResponse($team->getUrl());
165
        }, "Are you sure you want to transfer the leadership of the team to <strong>{$player->getEscapedUsername()}</strong>?",
166
        "{$player->getUsername()} is now leading {$team->getName()}",
167
        "Appoint leadership");
168
    }
169
170
    /**
171
     * Show a confirmation form to confirm that the user wants to assign a new
172
     * leader to a team
173
     *
174
     * @param Player $leader The new leader
175
     */
176
    public function newLeader($leader)
177
    {
178
        $this->newLeader = $leader;
179
    }
180
181
    protected function validateNew($form)
182
    {
183
        $name = $form->get('name');
184
        $team = Team::getFromName($name->getData());
185
186
        // The name for the team that the user gave us already exists
187
        // TODO: This takes deleted teams into account, do we want that?
188
        if ($team->isValid()) {
189
            $name->addError(new FormError("A team called {$team->getName()} already exists"));
190
        }
191
    }
192
193
    protected function canCreate($player)
194
    {
195
        if ($player->getTeam()->isValid()) {
196
            throw new ForbiddenException("You need to abandon your current team before you can create a new one");
197
        }
198
199
        return parent::canCreate($player);
200
    }
201
202
    /**
203
     * Make sure that a player can edit a team
204
     *
205
     * Throws an exception if a player is not an admin or the leader of a team
206
     * @param  Player        $player  The player to test
207
     * @param  Team          $team    The team
208
     * @param  string        $message The error message to show
209
     * @throws HTTPException
210
     * @return void
211
     */
212
    private function assertCanEdit(Player $player, Team $team, $message = "You are not allowed to edit that team")
213
    {
214
        if (!$player->canEdit($team)) {
215
            throw new ForbiddenException($message);
216
        }
217
    }
218
}
219