Completed
Push — master ( 466821...a1a5c2 )
by Konstantinos
04:15
created

TeamController   B

Complexity

Total Complexity 25

Size/Duplication

Total Lines 191
Duplicated Lines 27.23 %

Coupling/Cohesion

Components 2
Dependencies 16

Test Coverage

Coverage 89.47%
Metric Value
wmc 25
lcom 2
cbo 16
dl 52
loc 191
ccs 34
cts 38
cp 0.8947
rs 8.4614

13 Methods

Rating   Name   Duplication   Size   Complexity  
A showAction() 0 4 1
A listAction() 0 15 1
A createAction() 0 4 1
A editAction() 17 17 2
A deleteAction() 0 9 1
A joinAction() 17 17 3
A kickAction() 0 21 3
A abandonAction() 18 18 3
A assignLeaderAction() 0 20 3
A newLeader() 0 4 1
A validateNew() 0 11 2
A canCreate() 0 8 2
A assertCanEdit() 0 6 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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
8
class TeamController extends CRUDController
9
{
10
    /**
11
     * The new leader if we're changing them
12
     * @var null|Player
13
     */
14
    private $newLeader = null;
15
16 1
    public function showAction(Team $team)
17
    {
18 1
        return array("team" => $team);
19
    }
20
21 1
    public function listAction()
22
    {
23 1
        Team::$cachedMatches = $this->getQueryBuilder('Match')
24 1
            ->where('time')->isAfter(TimeDate::from('45 days ago'))
25 1
            ->active()
26
            ->getModels($fast = true);
27
28 1
        $teams = $this->getQueryBuilder()
29
            ->sortBy('elo')->reverse()
30
            ->getModels($fast = true);
31
32
        return array(
33
            "teams" => $teams
34
        );
35
    }
36
37
    public function createAction(Player $me)
38
    {
39
        return $this->create($me);
40
    }
41
42 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...
43
    {
44
        // TODO: Generating this response is unnecessary
45
        $response = $this->edit($team, $me, "team");
46
47
        if ($this->newLeader) {
48
            // Redirect to a confirmation form if we are assigning a new leader
49
            $url = Service::getGenerator()->generate('team_assign_leader', array(
50
                'team'   => $team->getAlias(),
51
                'player' => $this->newLeader->getAlias()
52
            ));
53
54
            return new RedirectResponse($url);
55 1
        }
56
57 1
        return $response;
58
    }
59
60 1
    public function deleteAction(Player $me, Team $team)
61 1
    {
62 1
        $members = $team->getMembers();
63
64
        return $this->delete($team, $me, function () use ($team, $me, $members) {
65
            $event = new Event\TeamDeleteEvent($team, $me, $members);
66
            Service::getDispatcher()->dispatch(Events::TEAM_DELETE, $event);
67
        });
68
    }
69
70 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...
71
    {
72
        $this->requireLogin();
73
        if (!$me->isTeamless()) {
74
            throw new ForbiddenException("You are already a member of a team");
75
        } elseif ($team->getStatus() != 'open') {
76
            throw new ForbiddenException("This team is not accepting new members without an invitation");
77
        }
78
79
        return $this->showConfirmationForm(function () use ($team, $me) {
80
            $team->addMember($me->getId());
81
            Service::getDispatcher()->dispatch(Events::TEAM_JOIN,  new Event\TeamJoinEvent($team, $me));
82
83 1
            return new RedirectResponse($team->getUrl());
84
        },  "Are you sure you want to join {$team->getEscapedName()}?",
85 1
            "You are now a member of {$team->getName()}");
86
    }
87 1
88
    public function kickAction(Team $team, Player $player, Player $me)
89
    {
90
        $this->assertCanEdit($me, $team, "You are not allowed to kick a player off that team!");
91 1
92
        if ($team->getLeader()->isSameAs($player)) {
93
            throw new ForbiddenException("You can't kick the leader off their team.");
94
        }
95
96 1
        if (!$team->isMember($player->getId())) {
97 1
            throw new ForbiddenException("The specified player is not a member of that team.");
98 1
        }
99
100 1
        return $this->showConfirmationForm(function () use ($me, $team, $player) {
101 1
            $team->removeMember($player->getId());
102 1
            $event = new Event\TeamKickEvent($team, $player, $me);
103
            Service::getDispatcher()->dispatch(Events::TEAM_KICK, $event);
104
105 1
            return new RedirectResponse($team->getUrl());
106
        },  "Are you sure you want to kick {$player->getEscapedUsername()} from {$team->getEscapedName()}?",
107 1
            "Player {$player->getUsername()} has been kicked from {$team->getName()}", "Kick");
108
    }
109
110 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...
111 1
    {
112 1
        if (!$team->isMember($me->getId())) {
113
            throw new ForbiddenException("You are not a member of that team!");
114
        }
115
116 1
        if ($team->getLeader()->isSameAs($me)) {
117 1
            throw new ForbiddenException("You can't abandon the team you are leading.");
118
        }
119 1
120 1
        return $this->showConfirmationForm(function () use ($team, $me) {
121 1
            $team->removeMember($me->getId());
122
            Service::getDispatcher()->dispatch(Events::TEAM_ABANDON, new Event\TeamAbandonEvent($team, $me));
123
124
            return new RedirectResponse($team->getUrl());
125
        },  "Are you sure you want to abandon {$team->getEscapedName()}?",
126
            "You have left {$team->getName()}", "Abandon");
127
    }
128
129
    public function assignLeaderAction(Team $team, Player $me, Player $player)
130
    {
131
        $this->assertCanEdit($me, $team, "You are not allowed to change the leader of this team.");
132
133
        if (!$team->isMember($player->getId())) {
134
            throw new ForbiddenException("The specified player is not a member of {$team->getName()}");
135
        } elseif ($team->getLeader()->isSameAs($player)) {
136
            throw new ForbiddenException("{$player->getUsername()} is already the leader of {$team->getName()}");
137
        }
138
139
        return $this->showConfirmationForm(function () use ($player, $team) {
140
            $event = new Event\TeamLeaderChangeEvent($team, $player, $team->getLeader());
0 ignored issues
show
Bug introduced by
It seems like $team->getLeader() can be null; however, __construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
141
            $team->setLeader($player->getId());
142
            Service::getDispatcher()->dispatch(Events::TEAM_LEADER_CHANGE, $event);
143
144
            return new RedirectResponse($team->getUrl());
145
        }, "Are you sure you want to transfer the leadership of the team to <strong>{$player->getEscapedUsername()}</strong>?",
146
        "{$player->getUsername()} is now leading {$team->getName()}",
147
        "Appoint leadership");
148
    }
149
150
    /**
151
     * Show a confirmation form to confirm that the user wants to assign a new
152
     * leader to a team
153
     *
154
     * @param Player $leader The new leader
155
     */
156
    public function newLeader($leader)
157
    {
158
        $this->newLeader = $leader;
159
    }
160
161
    protected function validateNew($form)
162
    {
163
        $name = $form->get('name');
164
        $team = Team::getFromName($name->getData());
165
166
        // The name for the team that the user gave us already exists
167
        // TODO: This takes deleted teams into account, do we want that?
168
        if ($team->isValid()) {
169
            $name->addError(new FormError("A team called {$team->getName()} already exists"));
170
        }
171
    }
172
173
    protected function canCreate($player)
174
    {
175
        if ($player->getTeam()->isValid()) {
176
            throw new ForbiddenException("You need to abandon your current team before you can create a new one");
177
        }
178
179
        return parent::canCreate($player);
180
    }
181
182
    /**
183
     * Make sure that a player can edit a team
184
     *
185
     * Throws an exception if a player is not an admin or the leader of a team
186
     * @param  Player        $player  The player to test
187 1
     * @param  Team          $team    The team
188
     * @param  string        $message The error message to show
189 1
     * @throws HTTPException
190
     * @return void
191
     */
192 1
    private function assertCanEdit(Player $player, Team $team, $message = "You are not allowed to edit that team")
193
    {
194
        if (!$player->canEdit($team)) {
195
            throw new ForbiddenException($message);
196
        }
197
    }
198
}
199