Completed
Push — fm-support ( 67f3c2...5f26cf )
by Vladimir
04:53
created

MatchFormCreator::build()   B

Complexity

Conditions 3
Paths 2

Size

Total Lines 41
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 3.0005

Importance

Changes 2
Bugs 0 Features 2
Metric Value
dl 0
loc 41
ccs 24
cts 25
cp 0.96
rs 8.8571
c 2
b 0
f 2
cc 3
eloc 29
nc 2
nop 1
crap 3.0005
1
<?php
2
/**
3
 * This file contains a form creator for Matches
4
 *
5
 * @license    https://github.com/allejo/bzion/blob/master/LICENSE.md GNU General Public License Version 3
6
 */
7
8
namespace BZIon\Form\Creator;
9
10
use BZIon\Form\Type\DatetimeWithTimezoneType;
11
use BZIon\Form\Type\MatchTeamType;
12
use BZIon\Form\Type\ModelType;
13
use Symfony\Component\Form\FormInterface;
14
use Symfony\Component\Validator\Constraints\LessThan;
15
use Symfony\Component\Validator\Constraints\NotBlank;
16
17
/**
18
 * Form creator for matches
19
 */
20
class MatchFormCreator extends ModelFormCreator
21
{
22
    /**
23
     * {@inheritdoc}
24
     */
25 1
    protected function build($builder)
26
    {
27 1
        $durations = \Service::getParameter('bzion.league.duration');
28 1
        foreach ($durations as $duration => &$value) {
0 ignored issues
show
Bug introduced by
The expression $durations of type string is not traversable.
Loading history...
29 1
            $durations[$duration] = $duration;
30
        }
31
32
        return $builder
33 1
            ->add('first_team', new MatchTeamType(), array(
34 1
                'disableTeam' => $this->isEdit()
35
            ))
36 1
            ->add('second_team', new MatchTeamType(), array(
37 1
                'disableTeam' => $this->isEdit()
38
            ))
39 1
            ->add('duration', 'choice', array(
40 1
                'choices'     => $durations,
41 1
                'constraints' => new NotBlank(),
42
                'expanded'    => true
43
            ))
44 1
            ->add('server_address', 'text', array(
45 1
                'required' => false,
46
                'attr'     => array('placeholder' => 'brad.guleague.org:5100'),
47
            ))
48 1
            ->add('time', new DatetimeWithTimezoneType(), array(
49
                'constraints' => array(
50 1
                    new NotBlank(),
51 1
                    new LessThan(array(
52 1
                        'value'   => \TimeDate::now()->addMinutes(10),
53 1
                        'message' => 'The timestamp of the match must not be in the future'
54
                    ))
55
                ),
56 1
                'data' => ($this->isEdit())
57
                    ? $this->editing->getTimestamp()->setTimezone(\Controller::getMe()->getTimezone())
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Model as the method getTimestamp() does only exist in the following sub-classes of Model: AbstractMessage, ConversationEvent, Match, Message, Notification, Visit. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
58 1
                    : \TimeDate::now(\Controller::getMe()->getTimezone()),
59 1
                'with_seconds' => $this->isEdit()
60
            ))
61 1
            ->add('map', new ModelType('Map'), array(
62
                'required' => false
63 1
            ))
64 1
            ->add('enter', 'submit');
65
    }
66
67
    /**
68
     * {@inheritdoc}
69
     *
70
     * @param \Match $match
71
     */
72
    public function fill($form, $match)
73
    {
74
        $form->get('first_team')->setData(array(
75
            'team'         => $match->getTeamA(),
76
            'participants' => $match->getTeamAPlayers(),
77
            'score'        => $match->getTeamAPoints()
78
        ));
79
        $form->get('second_team')->setData(array(
80
            'team'         => $match->getTeamB(),
81
            'participants' => $match->getTeamBPlayers(),
82
            'score'        => $match->getTeamBPoints()
83
        ));
84
85
        $form->get('duration')->setData($match->getDuration());
86
        $form->get('server_address')->setData($match->getServerAddress());
87
        $form->get('time')->setData($match->getTimestamp());
88
        $form->get('map')->setData($match->getMap());
89
    }
90
91
    /**
92
     * {@inheritdoc}
93
     *
94
     * @param \Match $match
95
     */
96
    public function update($form, $match)
97
    {
98
        if (($match->getDuration() != $form->get('duration')->getData())
99
            || $match->getTimestamp()->ne($form->get('time')->getData())) {
100
            // The timestamp of the match was changed, we might need to
101
            // recalculate its ELO
102
            $this->controller->recalculateNeeded = true;
0 ignored issues
show
Bug introduced by
The property recalculateNeeded does not seem to exist in Controller.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
103
        }
104
105
        $firstTeam  = $form->get('first_team');
106
        $secondTeam = $form->get('second_team');
107
108
        $serverInfo = $this->getServerInfo($form->get('server_address'));
109
110
        $match->setTeamPlayers(
111
            $this->getPlayerList($firstTeam),
112
            $this->getPlayerList($secondTeam)
113
        );
114
115
        $match->setTeamPoints(
116
            $firstTeam->get('score')->getData(),
117
            $secondTeam->get('score')->getData()
118
        );
119
120
        $match->setDuration($form->get('duration')->getData())
121
            ->setServerAddress($serverInfo[0], $serverInfo[1])
122
            ->setTimestamp($form->get('time')->getData())
123
            ->setMap($form->get('map')->getData()->getId());
124
125
        if (!$match->isEloCorrect()) {
126
            $this->controller->recalculateNeeded = true;
127
        }
128
    }
129
130
    /**
131
     * {@inheritdoc}
132
     */
133 1
    public function enter($form)
134
    {
135 1
        $firstTeam  = $form->get('first_team');
136 1
        $secondTeam = $form->get('second_team');
137
138 1
        $serverInfo = $this->getServerInfo($form->get('server_address'));
139
140 1
        $match = \Match::enterMatch(
141 1
            $firstTeam->get('team')->getData()->getId(),
142 1
            $secondTeam->get('team')->getData()->getId(),
143 1
            $firstTeam->get('score')->getData(),
144 1
            $secondTeam->get('score')->getData(),
145 1
            $form->get('duration')->getData(),
146 1
            $this->me->getId(),
147 1
            $form->get('time')->getData(),
148 1
            $this->getPlayerList($firstTeam),
149 1
            $this->getPlayerList($secondTeam),
150 1
            $serverInfo[0],
151 1
            $serverInfo[1],
152 1
            null,
153 1
            $form->get('map')->getData()->getId()
154
        );
155
156
        return $match;
157
    }
158
159
    /**
160
     * Get the player list of a team
161
     *
162
     * @param FormInterface $team A MatchTeamType form
163
     * @return array
164
     */
165 1
    private function getPlayerList(FormInterface $team)
166
    {
167 1
        return array_map($this->getModelToID(),  $team->get('participants')->getData());
168
    }
169
170
    /**
171
     * Get the server address and port of a match
172
     *
173
     * @param FormInterface $server A text form representing the server
174
     * @return array
175
     */
176 1
    private function getServerInfo(FormInterface $server)
177
    {
178 1
        $serverInfo = explode(':', $server->getData());
179 1
        if (!isset($serverInfo[1])) {
180 1
            $serverInfo[1] = 5154;
181
        }
182
183 1
        return $serverInfo;
184
    }
185
186
    /**
187
     * Get a function which converts models to their IDs
188
     *
189
     * Useful to store the match players into the database
190
     */
191
    private static function getModelToID()
192
    {
193 1
        return function ($model) {
194
            return $model->getId();
195 1
        };
196
    }
197
}
198