Completed
Pull Request — master (#131)
by De Cramer
05:13 queued 02:26
created

RecordHandler::getPlayerPosition()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 2
eloc 2
nc 2
nop 1
crap 2
1
<?php
2
3
namespace eXpansion\Bundle\LocalRecords\Services;
4
5
use eXpansion\Bundle\LocalRecords\Model\Map\RecordTableMap;
6
use eXpansion\Bundle\LocalRecords\Model\Record;
7
use eXpansion\Bundle\LocalRecords\Model\RecordQuery;
8
use eXpansion\Bundle\LocalRecords\Model\RecordQueryBuilder;
9
use eXpansion\Framework\PlayersBundle\Storage\PlayerDb;
10
use Propel\Runtime\Propel;
11
12
/**
13
 * Class RecordHandler
14
 *
15
 * @package eXpansion\Bundle\LocalRecords\Model;
16
 * @author  oliver de Cramer <[email protected]>
17
 */
18
class RecordHandler
19
{
20
    /**
21
     * Available order logic for score.
22
     */
23
    const ORDER_ASC = "ASC";
24
    const ORDER_DESC = "DESC";
25
26
    /**
27
     * List of event types
28
     */
29
    const EVENT_TYPE_FIRST_TIME = 'first_time';
30
    const EVENT_TYPE_SAME_SCORE = 'same_score';
31
    const EVENT_TYPE_SAME_POS = 'same_position';
32
    const EVENT_TYPE_BETTER_POS = 'better_position';
33
34
    /**
35
     * List of data in the associative array returned.
36
     */
37
    const COL_EVENT = 'event';
38
    const COL_RECORD = 'record';
39
    const COL_OLD_RECORD = 'old_record';
40
    const COL_POS = 'position';
41
    const COL_OLD_POS = 'old_position';
42
    const COL_RECORDS = 'records';
43
44
    /** @var int */
45
    protected $nbRecords;
46
47
    /** @var string */
48
    protected $ordering;
49
50
    /** @var RecordQueryBuilder */
51
    protected $recordQueryBuilder;
52
53
    /** @var PlayerDb */
54
    protected $playerDb;
55
56
    /** @var Record[] */
57
    protected $records;
58
59
    /** @var Record[] */
60
    protected $recordsPerPlayer;
61
62
    /** @var int[] */
63
    protected $positionPerPlayer;
64
65
    /** @var int */
66
    protected $currentNbLaps;
67
68
    /** @var string */
69
    protected $currentMapUid;
70
71
    /**
72
     * RecordHandler constructor.
73
     *
74
     * @param RecordQueryBuilder $recordQueryBuilder
75
     * @param PlayerDb $playerDb
76
     * @param int $nbRecords
77
     * @param string $ordering
78
     */
79 14 View Code Duplication
    public function __construct(
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...
80
        RecordQueryBuilder $recordQueryBuilder,
81
        PlayerDb $playerDb,
82
        $nbRecords,
83
        $ordering = self::ORDER_ASC
84
    ) {
85 14
        $this->recordQueryBuilder = $recordQueryBuilder;
86 14
        $this->nbRecords = $nbRecords;
87 14
        $this->ordering = $ordering;
88 14
        $this->playerDb = $playerDb;
89 14
    }
90
91
    /**
92
     * @return Record[]
93
     */
94 7
    public function getRecords()
95
    {
96 7
        return $this->records;
97
    }
98
99
    /**
100
     * Get the position of a player
101
     *
102
     * @param string $login
103
     *
104
     * @return integer|null
105
     */
106 5
    public function getPlayerPosition($login)
107
    {
108 5
        return isset($this->positionPerPlayer[$login]) ? $this->positionPerPlayer[$login] : null;
109
    }
110
111
    /**
112
     * Get a players record information.
113
     *
114
     * @param $login
115
     *
116
     * @return Record|null
117
     */
118 2
    public function getPlayerRecord($login)
119
    {
120 2
        return isset($this->recordsPerPlayer[$login]) ? $this->recordsPerPlayer[$login] : null;
121
    }
122
123
    /**
124
     * Load records for a certain map.
125
     *
126
     * @param $mapUid
127
     * @param integer $nbLaps
128
     */
129 12
    public function loadForMap($mapUid, $nbLaps)
130
    {
131 12
        $this->recordsPerPlayer = [];
132 12
        $this->positionPerPlayer = [];
133
134 12
        $this->currentMapUid = $mapUid;
135 12
        $this->currentNbLaps = $nbLaps;
136
137 12
        $this->records = $this->recordQueryBuilder
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->recordQueryBuilde...ng(), $this->nbRecords) can also be of type object<Propel\Runtime\Co...ction\ObjectCollection>. However, the property $records is declared as type array<integer,object<eXp...lRecords\Model\Record>>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
138 12
            ->getMapRecords($mapUid, $nbLaps, $this->getScoreOrdering(), $this->nbRecords);
139
140 12
        $position = 1;
141 12
        foreach ($this->records as $record)
142
        {
143 11
            $this->recordsPerPlayer[$record->getPlayer()->getLogin()] = $record;
144 11
            $this->positionPerPlayer[$record->getPlayer()->getLogin()] = $position++;
145
        }
146 12
    }
147
148
    /**
149
     * Load records for certain players only.
150
     *
151
     * @param $mapUid
152
     * @param $nbLaps
153
     * @param $logins
154
     */
155 1
    public function loadForPlayers($mapUid, $nbLaps, $logins)
156
    {
157 1
        $logins = array_diff(array_keys($this->recordsPerPlayer), $logins);
158
159 1
        if (!empty($logins)) {
160 1
            $records = $this->recordQueryBuilder->getPlayerMapRecords($mapUid, $nbLaps, $logins);
161
162 1
            foreach ($records as $record) {
163 1
                $this->recordsPerPlayer[$record->getPlayer()->getLogin()] = $record;
164
            }
165
        }
166 1
    }
167
168
    /**
169
     * Save all new records.
170
     */
171
    public function save()
172
    {
173
        $con = Propel::getWriteConnection(RecordTableMap::DATABASE_NAME);
174
        $con->beginTransaction();
175
176
        foreach ($this->recordsPerPlayer as $record) {
177
            $record->save();
178
        }
179
180
        $con->commit();
181
    }
182
183
    /**
184
     * Add a new record
185
     *
186
     * @param string $login
187
     * @param int $score
188
     * @param int[] $checkpoints
189
     *
190
     * @return array|null Data for the new records.
191
     */
192 12
    public function addRecord($login, $score, $checkpoints) {
193 12
        $oldPosition = isset($this->positionPerPlayer[$login]) ? $this->positionPerPlayer[$login] : count($this->records) + 1;
194 12
        $record = isset($this->recordsPerPlayer[$login]) ? $this->recordsPerPlayer[$login] : $this->getNewRecord($login);
195 12
        $this->recordsPerPlayer[$login] = $record;
196
197 12
        $oldRecord = clone $record;
198 12
        $this->updateRecordStats($record, $score);
199
200 12
        if (empty($this->records)) {
201 2
            $record->setScore($score);
202 2
            $record->setCreatedAt(new \DateTime());
203 2
            $record->setCheckpoints($checkpoints);
204
205 2
            $this->records[0] = $record;
206 2
            $this->positionPerPlayer[$record->getPlayer()->getLogin()] = 1;
207 2
            $this->recordsPerPlayer[$record->getPlayer()->getLogin()] = $record;
208
209
            return [
210 2
                self::COL_EVENT => self::EVENT_TYPE_FIRST_TIME,
211 2
                self::COL_RECORD => $record,
212 2
                self::COL_RECORDS => $this->records,
213 2
                self::COL_POS => 1,
214
            ];
215
        }
216
217
        // Check if first time of this player.
218 12
        $firstTime = is_null($record->getScore());
219
220 12
        if ($score == $record->getScore()) {
221
            return [
222 1
                self::COL_EVENT => self::EVENT_TYPE_SAME_SCORE,
223 1
                self::COL_RECORD => $record,
224 1
                self::COL_OLD_RECORD => $oldRecord,
225 1
                self::COL_RECORDS => $this->records
226
            ];
227
        }
228
229 11
        if ($firstTime || $this->compareNewScore($record, $score)) {
230 9
            $recordIndex = $oldPosition - 1;
231 9
            $newPosition = $oldPosition;
232
233 9
            $this->records[$recordIndex] = $record;
234 9
            $this->positionPerPlayer[$record->getPlayer()->getLogin()] = $oldPosition;
235
236 9
            while ($recordIndex > 0 && $this->compareNewScore($this->records[$recordIndex - 1], $score)) {
237 5
                $previousRecord = $this->records[$recordIndex - 1];
238
239 5
                $this->records[$recordIndex - 1] = $record;
240 5
                $this->records[$recordIndex] = $previousRecord;
241
242 5
                $newPosition = $recordIndex;
243 5
                $this->positionPerPlayer[$record->getPlayer()->getLogin()] = $recordIndex;
244 5
                $this->positionPerPlayer[$previousRecord->getPlayer()->getLogin()] = $recordIndex + 1;
245
246 5
                $recordIndex--;
247
            }
248
249 9
            $record->setScore($score);
250 9
            $record->setUpdatedAt(new \DateTime());
251 9
            $record->setCheckpoints($checkpoints);
252
253
            // Remove entries whose position is superior to the limit.
254 9
            $this->records = array_slice($this->records, 0, $this->nbRecords);
255
256 9
            if ($newPosition <= $this->nbRecords) {
257 8
                if ($newPosition != $oldPosition || $firstTime) {
258
                    return [
259 6
                        self::COL_EVENT => self::EVENT_TYPE_BETTER_POS,
260 6
                        self::COL_RECORD => $record,
261 6
                        self::COL_OLD_RECORD => $oldRecord,
262 6
                        self::COL_RECORDS => $this->records,
263 6
                        self::COL_POS => $newPosition,
264 6
                        self::COL_OLD_POS => $firstTime ? null : $oldPosition,
265
                    ];
266
                }
267
268
                return [
269 2
                    self::COL_EVENT => self::EVENT_TYPE_SAME_POS,
270 2
                    self::COL_RECORD => $record,
271 2
                    self::COL_OLD_RECORD => $oldRecord,
272 2
                    self::COL_RECORDS => $this->records,
273 2
                    self::COL_POS => $newPosition,
274
                ];
275
            }
276
        }
277
278 5
        return null;
279
    }
280
281
    /**
282
     * Get a new record instance.
283
     *
284
     * @param string $login
285
     *
286
     * @return Record
287
     */
288 6
    protected function getNewRecord($login)
289
    {
290 6
        $record = new Record();
291 6
        $record->setPlayer($this->playerDb->get($login));
292 6
        $record->setNbLaps($this->currentNbLaps);
293 6
        $record->setNbFinish(0);
294 6
        $record->setMapUid($this->currentMapUid);
295
296 6
        return $record;
297
    }
298
299
    /**
300
     * Update Records statistics.
301
     *
302
     * @param Record $record
303
     * @param        integer $score
304
     */
305 12
    protected function updateRecordStats(Record $record, $score)
306
    {
307 12
        $record->setAvgScore(
308 12
            (($record->getAvgScore() * $record->getNbFinish()) + $score) / ($record->getNbFinish() + 1)
309
        );
310 12
        $record->setNbFinish($record->getNbFinish() + 1);
311 12
    }
312
313
314
    /**
315
     * Get ordering use for sorting.
316
     *
317
     * @return string
318
     */
319 13
    protected function getScoreOrdering()
320
    {
321 13
        return $this->ordering;
322
    }
323
324
    /**
325
     * @param int $newScore
326
     * @param Record $record
327
     *
328
     * @return bool
329
     */
330 11
    protected function compareNewScore($record, $newScore)
331
    {
332 11
        if ($this->getScoreOrdering() == self::ORDER_ASC) {
333 10
            return $newScore <= $record->getScore();
334
        } else {
335 1
            return $newScore >= $record->getScore();
336
        }
337
    }
338
}
339