Completed
Push — feature/sass-standard ( a5bd48...aade0e )
by Vladimir
14:40 queued 11:12
created

MatchFormCreator::build()   B

Complexity

Conditions 6
Paths 2

Size

Total Lines 50
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 30
CRAP Score 6.0012

Importance

Changes 0
Metric Value
dl 0
loc 50
ccs 30
cts 31
cp 0.9677
rs 8.6315
c 0
b 0
f 0
cc 6
eloc 36
nc 2
nop 1
crap 6.0012
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) {
29 1
            $durations[$duration] = $duration;
30
        }
31
32
        return $builder
33 1
            ->add('first_team', new MatchTeamType(), array(
34 1
                'disableTeam' => $this->isEdit() && $this->editing->isOfficial()
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 isOfficial() does only exist in the following sub-classes of Model: Match. 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...
35
            ))
36 1
            ->add('second_team', new MatchTeamType(), array(
37 1
                'disableTeam' => $this->isEdit() && $this->editing->isOfficial()
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 isOfficial() does only exist in the following sub-classes of Model: Match. 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...
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 1
                'required' => false
63
            ))
64 1
            ->add('type', 'choice', array(
65
                'choices'  => array(
66 1
                    \Match::OFFICIAL => 'Official',
67 1
                    \Match::FUN => 'Fun match',
68 1
                    \Match::SPECIAL => 'Special event match',
69
                ),
70 1
                'disabled' => $this->editing && $this->editing->isOfficial(),
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 isOfficial() does only exist in the following sub-classes of Model: Match. 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...
71 1
                'label' => 'Match Type'
72
            ))
73 1
            ->add('enter', 'submit');
74
    }
75
76
    /**
77
     * {@inheritdoc}
78
     *
79
     * @param \Match $match
80
     */
81
    public function fill($form, $match)
82
    {
83
        $form->get('first_team')->setData(array(
84
            'team'         => $match->getTeamA(),
85
            'participants' => $match->getTeamAPlayers(),
86
            'score'        => $match->getTeamAPoints()
87
        ));
88
        $form->get('second_team')->setData(array(
89
            'team'         => $match->getTeamB(),
90
            'participants' => $match->getTeamBPlayers(),
91
            'score'        => $match->getTeamBPoints()
92
        ));
93
94
        $form->get('duration')->setData($match->getDuration());
95
        $form->get('server_address')->setData($match->getServerAddress());
96
        $form->get('time')->setData($match->getTimestamp());
97
        $form->get('map')->setData($match->getMap());
98
        $form->get('type')->setData($match->getMatchType());
99
    }
100
101
    /**
102
     * {@inheritdoc}
103
     *
104
     * @param \Match $match
105
     */
106
    public function update($form, $match)
107
    {
108
        if (($match->getDuration() != $form->get('duration')->getData())
109
            || $match->getTimestamp()->ne($form->get('time')->getData())) {
110
            // The timestamp of the match was changed, we might need to
111
            // recalculate its ELO
112
            $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...
113
        }
114
115
        $firstTeam  = $form->get('first_team');
116
        $secondTeam = $form->get('second_team');
117
118
        if (!$match->isOfficial()) {
119
            $match->setTeamColors(
120
                $firstTeam->get('team')->getData(),
121
                $secondTeam->get('team')->getData()
122
            );
123
        }
124
125
        $match->setTeamPlayers(
126
            $this->getPlayerList($firstTeam),
127
            $this->getPlayerList($secondTeam)
128
        );
129
130
        $match->setTeamPoints(
131
            $firstTeam->get('score')->getData(),
132
            $secondTeam->get('score')->getData()
133
        );
134
135
        $match->setDuration($form->get('duration')->getData())
136
            ->setServerAddress($form->get('server_address')->getData())
137
            ->setTimestamp($form->get('time')->getData())
138
            ->setMap($form->get('map')->getData()->getId());
139
140
        if (!$match->isEloCorrect()) {
141
            $this->controller->recalculateNeeded = true;
142
        }
143
    }
144
145
    /**
146
     * {@inheritdoc}
147
     */
148 1
    public function enter($form)
149
    {
150 1
        $firstTeam  = $form->get('first_team');
151 1
        $secondTeam = $form->get('second_team');
152
153 1
        $firstId = $firstTeam->get('team')->getData()->getId();
154 1
        $secondId = $secondTeam->get('team')->getData()->getId();
155
156 1
        $official = ($form->get('type')->getData() === \Match::OFFICIAL);
157
158 1
        $match = \Match::enterMatch(
159 1
            $official ? $firstId : null,
160 1
            $official ? $secondId : null,
161 1
            $firstTeam->get('score')->getData(),
162 1
            $secondTeam->get('score')->getData(),
163 1
            $form->get('duration')->getData(),
164 1
            $this->me->getId(),
165 1
            $form->get('time')->getData(),
166 1
            $this->getPlayerList($firstTeam),
167 1
            $this->getPlayerList($secondTeam),
168 1
            $form->get('server_address')->getData(),
169 1
            null,
170 1
            $form->get('map')->getData()->getId(),
171 1
            $form->get('type')->getData(),
172 1
            $official ? null : $firstId,
173 1
            $official ? null : $secondId
174
        );
175
176 1
        return $match;
177
    }
178
179
    /**
180
     * Get the player list of a team
181
     *
182
     * @param FormInterface $team A MatchTeamType form
183
     * @return array
184
     */
185 1
    private function getPlayerList(FormInterface $team)
186
    {
187 1
        return array_map($this->getModelToID(),  $team->get('participants')->getData());
188
    }
189
190
    /**
191
     * Get a function which converts models to their IDs
192
     *
193
     * Useful to store the match players into the database
194
     */
195
    private static function getModelToID()
196
    {
197 1
        return function ($model) {
198 1
            return $model->getId();
199 1
        };
200
    }
201
}
202