Completed
Pull Request — master (#139)
by De Cramer
02:36
created

RecordHandler::loadForMap()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 9.4285
c 0
b 0
f 0
ccs 12
cts 12
cp 1
cc 2
eloc 11
nc 2
nop 2
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 15
     * @param int $nbRecords
77
     * @param string $ordering
78
     */
79 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 15
        $nbRecords,
83 15
        $ordering = self::ORDER_ASC
84 15
    ) {
85 15
        $this->recordQueryBuilder = $recordQueryBuilder;
86 15
        $this->nbRecords = $nbRecords;
87
        $this->ordering = $ordering;
88
        $this->playerDb = $playerDb;
89
    }
90
91 7
    /**
92
     * @return Record[]
93 7
     */
94
    public function getRecords()
95
    {
96
        return $this->records;
97
    }
98
99
    /**
100
     * Get the position of a player
101
     *
102
     * @param string $login
103 5
     *
104
     * @return integer|null
105 5
     */
106
    public function getPlayerPosition($login)
107
    {
108
        return isset($this->positionPerPlayer[$login]) ? $this->positionPerPlayer[$login] : null;
109
    }
110
111
    /**
112
     * Get a players record information.
113
     *
114
     * @param $login
115 2
     *
116
     * @return Record|null
117 2
     */
118
    public function getPlayerRecord($login)
119
    {
120
        return isset($this->recordsPerPlayer[$login]) ? $this->recordsPerPlayer[$login] : null;
121
    }
122
123
    /**
124
     * Load records for a certain map.
125
     *
126 12
     * @param $mapUid
127
     * @param integer $nbLaps
128 12
     */
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 12
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
            ->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
            $records = $this->recordQueryBuilder->getPlayerMapRecords($mapUid, $nbLaps, $logins);
161 1
162 1
            foreach ($records as $record) {
163 1
                $this->recordsPerPlayer[$record->getPlayer()->getLogin()] = $record;
164 1
            }
165
        }
166
    }
167 1
168 1
    /**
169
     * Save all new records.
170
     */
171 1
    public function save()
172
    {
173
        $con = Propel::getWriteConnection(RecordTableMap::DATABASE_NAME);
174
        $con->beginTransaction();
175
176 1
        foreach ($this->recordsPerPlayer as $record) {
177
            $record->save();
178 1
        }
179 1
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 12
     * @return array|null Data for the new records.
191 12
     */
192 12
    public function addRecord($login, $score, $checkpoints) {
193 12
        $oldPosition = isset($this->positionPerPlayer[$login]) ? $this->positionPerPlayer[$login] : count($this->records) + 1;
194
        $record = isset($this->recordsPerPlayer[$login]) ? $this->recordsPerPlayer[$login] : $this->getNewRecord($login);
195 12
        $this->recordsPerPlayer[$login] = $record;
196 12
197
        $oldRecord = clone $record;
198 12
        $this->updateRecordStats($record, $score);
199 2
200 2
        if (empty($this->records)) {
201 2
            $record->setScore($score);
202
            $record->setCreatedAt(new \DateTime());
203 2
            $record->setCheckpoints($checkpoints);
204 2
205 2
            $this->records[0] = $record;
206
            $this->positionPerPlayer[$record->getPlayer()->getLogin()] = 1;
207
            $this->recordsPerPlayer[$record->getPlayer()->getLogin()] = $record;
208 2
209 2
            return [
210 2
                self::COL_EVENT => self::EVENT_TYPE_FIRST_TIME,
211 2
                self::COL_RECORD => $record,
212
                self::COL_RECORDS => $this->records,
213
                self::COL_POS => 1,
214
            ];
215
        }
216 12
217
        // Check if first time of this player.
218 12
        $firstTime = is_null($record->getScore());
219
220 1
        if ($score == $record->getScore()) {
221 1
            return [
222 1
                self::COL_EVENT => self::EVENT_TYPE_SAME_SCORE,
223 1
                self::COL_RECORD => $record,
224
                self::COL_OLD_RECORD => $oldRecord,
225
                self::COL_RECORDS => $this->records
226
            ];
227 11
        }
228 9
229 9
        if ($firstTime || $this->compareNewScore($record, $score)) {
230
            $recordIndex = $oldPosition - 1;
231 9
            $newPosition = $oldPosition;
232 9
233
            $this->records[$recordIndex] = $record;
234 9
            $this->positionPerPlayer[$record->getPlayer()->getLogin()] = $oldPosition;
235 5
236
            while ($recordIndex > 0 && $this->compareNewScore($this->records[$recordIndex - 1], $score)) {
237 5
                $previousRecord = $this->records[$recordIndex - 1];
238 5
239
                $this->records[$recordIndex - 1] = $record;
240 5
                $this->records[$recordIndex] = $previousRecord;
241 5
242 5
                $newPosition = $recordIndex;
243
                $this->positionPerPlayer[$record->getPlayer()->getLogin()] = $recordIndex;
244 5
                $this->positionPerPlayer[$previousRecord->getPlayer()->getLogin()] = $recordIndex + 1;
245
246
                $recordIndex--;
247 9
            }
248 9
249 9
            $record->setScore($score);
250
            $record->setUpdatedAt(new \DateTime());
251
            $record->setCheckpoints($checkpoints);
252 9
253
            // Remove entries whose position is superior to the limit.
254 9
            $this->records = array_slice($this->records, 0, $this->nbRecords);
255 8
256
            if ($newPosition <= $this->nbRecords) {
257 6
                if ($newPosition != $oldPosition || $firstTime) {
258 6
                    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
                        self::COL_POS => $newPosition,
264
                        self::COL_OLD_POS => $firstTime ? null : $oldPosition,
265
                    ];
266
                }
267 2
268 2
                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
                    self::COL_RECORDS => $this->records,
273
                    self::COL_POS => $newPosition,
274
                ];
275
            }
276 5
        }
277
278
        return null;
279
    }
280
281
    /**
282
     * Get a new record instance.
283
     *
284
     * @param string $login
285
     *
286 6
     * @return Record
287
     */
288 6
    protected function getNewRecord($login)
289 6
    {
290 6
        $record = new Record();
291 6
        $record->setPlayer($this->playerDb->get($login));
292 6
        $record->setNbLaps($this->currentNbLaps);
293
        $record->setNbFinish(0);
294 6
        $record->setMapUid($this->currentMapUid);
295
296
        return $record;
297
    }
298
299
    /**
300
     * Update Records statistics.
301
     *
302
     * @param Record $record
303 12
     * @param        integer $score
304
     */
305 12
    protected function updateRecordStats(Record $record, $score)
306 12
    {
307
        $record->setAvgScore(
308 12
            (($record->getAvgScore() * $record->getNbFinish()) + $score) / ($record->getNbFinish() + 1)
309 12
        );
310
        $record->setNbFinish($record->getNbFinish() + 1);
311
    }
312
313
314
    /**
315
     * Get ordering use for sorting.
316
     *
317 13
     * @return string
318
     */
319 13
    protected function getScoreOrdering()
320
    {
321
        return $this->ordering;
322
    }
323
324
    /**
325
     * @param int $newScore
326
     * @param Record $record
327
     *
328 11
     * @return bool
329
     */
330 11
    protected function compareNewScore($record, $newScore)
331 10
    {
332
        if ($this->getScoreOrdering() == self::ORDER_ASC) {
333 1
            return $newScore <= $record->getScore();
334
        } else {
335
            return $newScore >= $record->getScore();
336
        }
337
    }
338
}
339