Passed
Branch 2.3.0 (f3b97b)
by Matthew
06:16
created

DraftRepository::UpdateStatus()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 7
dl 0
loc 14
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
namespace PhpDraft\Domain\Repositories;
3
4
use Silex\Application;
5
use Symfony\Component\HttpFoundation\Request;
6
use PhpDraft\Domain\Entities\Draft;
7
use PhpDraft\Domain\Entities\Pick;
8
9
class DraftRepository {
10
  private $app;
11
12
  public function __construct(Application $app) {
13
    $this->app = $app;
14
  }
15
16
  public function GetPublicDrafts(Request $request, $password = '') {
0 ignored issues
show
Unused Code introduced by
The parameter $password is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

16
  public function GetPublicDrafts(Request $request, /** @scrutinizer ignore-unused */ $password = '') {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
17
    $draft_stmt = $this->app['db']->prepare("SELECT d.*, u.Name AS commish_name FROM draft d
18
      LEFT OUTER JOIN users u
19
      ON d.commish_id = u.id
20
      ORDER BY draft_create_time DESC");
21
22
    $draft_stmt->setFetchMode(\PDO::FETCH_CLASS, '\PhpDraft\Domain\Entities\Draft');
23
24
    $currentUser = $this->app['phpdraft.LoginUserService']->GetUserFromHeaderToken($request);
25
26
    if (!$draft_stmt->execute()) {
27
      throw new \Exception("Unable to load drafts.");
28
    }
29
30
    $drafts = array();
31
32
    while ($draft = $draft_stmt->fetch()) {
33
      $draft = $this->NormalizeDraftTimesAndStatuses($draft);
34
      $draft = $this->SetSecurityProperties($currentUser, $draft);
35
36
      $drafts[] = $draft;
37
    }
38
39
    return $drafts;
40
  }
41
42
  public function GetPublicDraftsByCommish(Request $request, $commish_id, $password = '') {
0 ignored issues
show
Unused Code introduced by
The parameter $password is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

42
  public function GetPublicDraftsByCommish(Request $request, $commish_id, /** @scrutinizer ignore-unused */ $password = '') {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
43
    $commish_id = (int)$commish_id;
44
45
    $draftStatement = $this->app['db']->prepare("SELECT d.*, u.Name AS commish_name FROM draft d
46
    LEFT OUTER JOIN users u
47
    ON d.commish_id = u.id
48
    WHERE commish_id = ?
49
    ORDER BY draft_create_time DESC");
50
51
    $draftStatement->setFetchMode(\PDO::FETCH_CLASS, '\PhpDraft\Domain\Entities\Draft');
52
    $draftStatement->bindParam(1, $commish_id);
53
54
    if (!$draftStatement->execute()) {
55
      throw new \Exception("Unable to load drafts.");
56
    }
57
58
    $currentUser = $this->app['phpdraft.LoginUserService']->GetUserFromHeaderToken($request);
59
60
    $drafts = array();
61
62
    while ($draft = $draftStatement->fetch()) {
63
      $draft = $this->NormalizeDraftTimesAndStatuses($draft);
64
      $draft = $this->SetSecurityProperties($currentUser, $draft);
65
66
      $drafts[] = $draft;
67
    }
68
69
    return $drafts;
70
  }
71
72
  //Note: this method is to be used by admin section only
73
  public function GetAllDraftsByCommish($commish_id) {
74
    $commish_id = (int)$commish_id;
75
76
    $draftStatement = $this->app['db']->prepare("SELECT d.*, u.Name AS commish_name FROM draft d
77
    LEFT OUTER JOIN users u
78
    ON d.commish_id = u.id
79
    WHERE commish_id = ?
80
    ORDER BY draft_create_time DESC");
81
82
    $draftStatement->setFetchMode(\PDO::FETCH_CLASS, '\PhpDraft\Domain\Entities\Draft');
83
    $draftStatement->bindParam(1, $commish_id);
84
85
    if (!$draftStatement->execute()) {
86
      throw new \Exception("Unable to load drafts.");
87
    }
88
89
    $drafts = array();
90
91
    while ($draft = $draftStatement->fetch()) {
92
      $draft->draft_create_time = $this->app['phpdraft.UtilityService']->ConvertTimeForClientDisplay($draft->draft_create_time);
93
      $draft->draft_start_time = $this->app['phpdraft.UtilityService']->ConvertTimeForClientDisplay($draft->draft_start_time);
94
      $draft->draft_end_time = $this->app['phpdraft.UtilityService']->ConvertTimeForClientDisplay($draft->draft_end_time);
95
96
      $drafts[] = $draft;
97
    }
98
99
    return $drafts;
100
  }
101
102
  //Note: this method is to be used by admin section only
103
  public function GetAllCompletedDrafts() {
104
    $draftStatement = $this->app['db']->prepare("SELECT d.*, u.Name AS commish_name FROM draft d
105
      LEFT OUTER JOIN users u
106
      ON d.commish_id = u.id
107
      WHERE d.draft_status = 'complete'
108
      ORDER BY draft_create_time DESC");
109
110
    $draftStatement->setFetchMode(\PDO::FETCH_CLASS, '\PhpDraft\Domain\Entities\Draft');
111
112
    if (!$draftStatement->execute()) {
113
      throw new \Exception("Unable to load drafts.");
114
    }
115
116
    $drafts = array();
117
118
    while ($draft = $draftStatement->fetch()) {
119
      $draft = $this->NormalizeDraftTimesAndStatuses($draft);
120
      //Skipping security call here as we have not passed a request in (thus no currentUser) and this is only called by admin
121
122
      $drafts[] = $draft;
123
    }
124
125
    return $drafts;
126
  }
127
128
  public function GetPublicDraft(Request $request, $id, $getDraftData = false, $password = '') {
0 ignored issues
show
Unused Code introduced by
The parameter $password is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

128
  public function GetPublicDraft(Request $request, $id, $getDraftData = false, /** @scrutinizer ignore-unused */ $password = '') {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
129
    $draft = new Draft();
0 ignored issues
show
Unused Code introduced by
The assignment to $draft is dead and can be removed.
Loading history...
130
131
    $cachedDraft = $this->GetCachedDraft($id);
132
133
    if ($cachedDraft != null) {
134
      $draft = $cachedDraft;
135
    } else {
136
      $draft = $this->FetchPublicDraftById($id);
137
138
      $this->SetCachedDraft($draft);
139
    }
140
141
    $currentUser = $this->app['phpdraft.LoginUserService']->GetUserFromHeaderToken($request);
142
143
    $draft = $this->NormalizeDraftTimesAndStatuses($draft);
144
    $draft = $this->SetSecurityProperties($currentUser, $draft);
145
146
    if ($getDraftData) {
147
      $draft->sports = $this->app['phpdraft.DraftDataRepository']->GetSports();
148
      $draft->styles = $this->app['phpdraft.DraftDataRepository']->GetStyles();
149
      $draft->statuses = $this->app['phpdraft.DraftDataRepository']->GetStatuses();
150
      $draft->teams = $this->app['phpdraft.DraftDataRepository']->GetTeams($draft->draft_sport);
151
      $draft->historical_teams = $this->app['phpdraft.DraftDataRepository']->GetHistoricalTeams($draft->draft_sport);
152
      $draft->positions = $this->app['phpdraft.DraftDataRepository']->GetPositions($draft->draft_sport);
153
154
      if ($draft->using_depth_charts) {
155
        $draft->depthChartPositions = $this->app['phpdraft.DepthChartPositionRepository']->LoadAll($draft->draft_id);
156
      }
157
    }
158
159
    return $draft;
160
  }
161
162
  /*
163
  * This method is only to be used internally or when the user has been verified as owner of the draft (or is admin)
164
  * (in other words, don't call this then return the result as JSON!)
165
  */
166
  public function Load($id, $bustCache = false) {
167
    $draft = new Draft();
0 ignored issues
show
Unused Code introduced by
The assignment to $draft is dead and can be removed.
Loading history...
168
169
    $cachedDraft = $this->GetCachedDraft($id);
170
171
    if ($bustCache || $cachedDraft == null) {
172
      $draft = $this->FetchPublicDraftById($id);
173
174
      if ($bustCache) {
175
        $this->UnsetCachedDraft($draft->draft_id);
176
      }
177
178
      $this->SetCachedDraft($draft);
179
    } else {
180
      $draft = $cachedDraft;
181
    }
182
183
    $draft->draft_rounds = (int)$draft->draft_rounds;
184
185
    return $draft;
186
  }
187
188
  public function Create(Draft $draft) {
189
    $insert_stmt = $this->app['db']->prepare("INSERT INTO draft
190
      (draft_id, commish_id, draft_create_time, draft_name, draft_sport, draft_status, draft_style, draft_rounds, draft_password, using_depth_charts)
191
      VALUES
192
      (NULL, ?, UTC_TIMESTAMP(), ?, ?, ?, ?, ?, ?, ?)");
193
194
    $insert_stmt->bindParam(1, $draft->commish_id);
195
    $insert_stmt->bindParam(2, $draft->draft_name);
196
    $insert_stmt->bindParam(3, $draft->draft_sport);
197
    $insert_stmt->bindParam(4, $draft->draft_status);
198
    $insert_stmt->bindParam(5, $draft->draft_style);
199
    $insert_stmt->bindParam(6, $draft->draft_rounds);
200
    $insert_stmt->bindParam(7, $draft->draft_password);
201
    $insert_stmt->bindParam(8, $draft->using_depth_charts);
202
203
    if (!$insert_stmt->execute()) {
204
      throw new \Exception("Unable to create draft.");
205
    }
206
207
    $draft = $this->Load((int)$this->app['db']->lastInsertId(), true);
208
209
    return $draft;
210
  }
211
212
  //Excluded properties in update:
213
  //draft_start_time/draft_end_time - updated in separate operations at start/end of draft
214
  //draft_current_round/draft_current_pick - updated when new picks are made
215
  //draft_counter - call IncrementDraftCounter instead - this call's made a lot independently of other properties.
216
  //draft_status - separate API call to update the draft status
217
  public function Update(Draft $draft) {
218
    $update_stmt = $this->app['db']->prepare("UPDATE draft
219
      SET commish_id = ?, draft_name = ?, draft_sport = ?,
220
      draft_style = ?, draft_password = ?, draft_rounds = ?,
221
      using_depth_charts = ?
222
      WHERE draft_id = ?");
223
224
    $draft->using_depth_charts = $draft->using_depth_charts;
225
226
    $update_stmt->bindParam(1, $draft->commish_id);
227
    $update_stmt->bindParam(2, $draft->draft_name);
228
    $update_stmt->bindParam(3, $draft->draft_sport);
229
    $update_stmt->bindParam(4, $draft->draft_style);
230
    $update_stmt->bindParam(5, $draft->draft_password);
231
    $update_stmt->bindParam(6, $draft->draft_rounds);
232
    $update_stmt->bindParam(7, $draft->using_depth_charts);
233
    $update_stmt->bindParam(8, $draft->draft_id);
234
235
    if (!$update_stmt->execute()) {
236
      throw new \Exception("Unable to update draft.");
237
    }
238
239
    $this->ResetDraftCache($draft->draft_id);
240
241
    return $draft;
242
  }
243
244
  public function UpdateStatus(Draft $draft) {
245
    $status_stmt = $this->app['db']->prepare("UPDATE draft
246
      SET draft_status = ? WHERE draft_id = ?");
247
248
    $status_stmt->bindParam(1, $draft->draft_status);
249
    $status_stmt->bindParam(2, $draft->draft_id);
250
251
    if (!$status_stmt->execute()) {
252
      throw new \Exception("Unable to update draft status.");
253
    }
254
255
    $this->ResetDraftCache($draft->draft_id);
256
257
    return $draft;
258
  }
259
260
  public function UpdateStatsTimestamp(Draft $draft) {
261
    $status_stmt = $this->app['db']->prepare("UPDATE draft
262
      SET draft_stats_generated = UTC_TIMESTAMP() WHERE draft_id = ?");
263
264
    $status_stmt->bindParam(1, $draft->draft_id);
265
266
    if (!$status_stmt->execute()) {
267
      throw new \Exception("Unable to update draft's stats timestamp.");
268
    }
269
270
    $this->ResetDraftCache($draft->draft_id);
271
272
    return $draft;
273
  }
274
275
  public function IncrementDraftCounter(Draft $draft) {
276
    $incrementedCounter = (int)$draft->draft_counter + 1;
277
278
    $increment_stmt = $this->app['db']->prepare("UPDATE draft
279
      SET draft_counter = ? WHERE draft_id = ?");
280
281
    $increment_stmt->bindParam(1, $incrementedCounter);
282
    $increment_stmt->bindParam(2, $draft->draft_id);
283
284
    if (!$increment_stmt->execute()) {
285
      throw new \Exception("Unable to increment draft counter.");
286
    }
287
288
    $this->ResetDraftCache($draft->draft_id);
289
290
    return $incrementedCounter;
291
  }
292
293
  //$next_pick can't be type-hinted - can be null
294
  public function MoveDraftForward(Draft $draft, $next_pick) {
295
    if ($next_pick !== null) {
296
      $draft->draft_current_pick = (int)$next_pick->player_pick;
297
      $draft->draft_current_round = (int)$next_pick->player_round;
298
299
      $stmt = $this->app['db']->prepare("UPDATE draft SET draft_current_pick = ?, draft_current_round = ? WHERE draft_id = ?");
300
      $stmt->bindParam(1, $draft->draft_current_pick);
301
      $stmt->bindParam(2, $draft->draft_current_round);
302
      $stmt->bindParam(3, $draft->draft_id);
303
304
      if (!$stmt->execute()) {
305
        throw new \Exception("Unable to move draft forward.");
306
      }
307
    } else {
308
      $draft->draft_status = 'complete';
309
      $stmt = $this->app['db']->prepare("UPDATE draft SET draft_status = ?, draft_end_time = UTC_TIMESTAMP() WHERE draft_id = ?");
310
      $stmt->bindParam(1, $draft->draft_status);
311
      $stmt->bindParam(2, $draft->draft_id);
312
313
      if (!$stmt->execute()) {
314
        throw new \Exception("Unable to move draft forward.");
315
      }
316
    }
317
318
    $this->ResetDraftCache($draft->draft_id);
319
320
    return $draft;
321
  }
322
323
  //Used when we move a draft from "undrafted" to "in_progress":
324
  //Resets the draft counter
325
  //Sets the current pick and round to 1
326
  //Sets the draft start time to UTC now, nulls out end time
327
  public function SetDraftInProgress(Draft $draft) {
328
    $reset_stmt = $this->app['db']->prepare("UPDATE draft
329
      SET draft_counter = 0, draft_current_pick = 1, draft_current_round = 1,
330
      draft_start_time = UTC_TIMESTAMP(), draft_end_time = NULL
331
      WHERE draft_id = ?");
332
333
    $reset_stmt->bindParam(1, $draft->draft_id);
334
335
    if (!$reset_stmt->execute()) {
336
      throw new \Exception("Unable to set draft to in progress.");
337
    }
338
339
    $this->ResetDraftCache($draft->draft_id);
340
341
    return 0;
342
  }
343
344
  public function NameIsUnique($name, $id = null) {
345
    if (!empty($id)) {
346
      $name_stmt = $this->app['db']->prepare("SELECT draft_name FROM draft WHERE draft_name LIKE ? AND draft_id <> ?");
347
      $name_stmt->bindParam(1, $name);
348
      $name_stmt->bindParam(2, $id);
349
    } else {
350
      $name_stmt = $this->app['db']->prepare("SELECT draft_name FROM draft WHERE draft_name LIKE ?");
351
      $name_stmt->bindParam(1, $name);
352
    }
353
354
    if (!$name_stmt->execute()) {
355
      throw new \Exception("Draft name '%s' is invalid", $name);
356
    }
357
358
    return $name_stmt->rowCount() == 0;
359
  }
360
361
  public function DeleteDraft($draft_id) {
362
    $delete_stmt = $this->app['db']->prepare("DELETE FROM draft WHERE draft_id = ?");
363
    $delete_stmt->bindParam(1, $draft_id);
364
365
    if (!$delete_stmt->execute()) {
366
      throw new \Exception("Unable to delete draft $draft_id.");
367
    }
368
369
    $this->UnsetCachedDraft($draft_id);
370
371
    return;
372
  }
373
374
  private function ResetDraftCache($draft_id) {
375
    $draft = $this->Load($draft_id, true);
0 ignored issues
show
Unused Code introduced by
The assignment to $draft is dead and can be removed.
Loading history...
376
  }
377
378
  private function SetCachedDraft(Draft $draft) {
379
    $this->app['phpdraft.DatabaseCacheService']->SetCachedItem("draft$draft->draft_id", $draft);
380
  }
381
382
  private function GetCachedDraft($draft_id) {
383
    return $this->app['phpdraft.DatabaseCacheService']->GetCachedItem("draft$draft_id");
384
  }
385
386
  private function UnsetCachedDraft($draft_id) {
387
    $this->app['phpdraft.DatabaseCacheService']->DeleteCachedItem("draft$draft_id");
388
  }
389
390
  private function ProtectPrivateDraft(Draft $draft) {
391
    $draft->draft_sport = '';
392
    $draft->draft_status = '';
393
    $draft->setting_up = '';
0 ignored issues
show
Bug introduced by
The property setting_up does not seem to exist on PhpDraft\Domain\Entities\Draft.
Loading history...
394
    $draft->in_progress = '';
0 ignored issues
show
Bug introduced by
The property in_progress does not seem to exist on PhpDraft\Domain\Entities\Draft.
Loading history...
395
    $draft->complete = '';
0 ignored issues
show
Bug introduced by
The property complete does not seem to exist on PhpDraft\Domain\Entities\Draft.
Loading history...
396
    $draft->draft_style = '';
397
    $draft->draft_rounds = '';
0 ignored issues
show
Documentation Bug introduced by
The property $draft_rounds was declared of type integer, but '' is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
398
    $draft->draft_counter = '';
0 ignored issues
show
Documentation Bug introduced by
The property $draft_counter was declared of type integer, but '' is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
399
    $draft->draft_start_time = null;
400
    $draft->draft_end_time = null;
401
    $draft->draft_current_pick = '';
0 ignored issues
show
Documentation Bug introduced by
The property $draft_current_pick was declared of type integer, but '' is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
402
    $draft->draft_current_round = '';
0 ignored issues
show
Documentation Bug introduced by
The property $draft_current_round was declared of type integer, but '' is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
403
    $draft->draft_create_time = '';
0 ignored issues
show
Bug introduced by
The property draft_create_time does not seem to exist on PhpDraft\Domain\Entities\Draft.
Loading history...
404
    $draft->draft_stats_generated = '';
405
    $draft->nfl_extended = null;
406
    $draft->sports = null;
407
    $draft->styles = null;
408
    $draft->statuses = null;
409
    $draft->teams = null;
0 ignored issues
show
Bug introduced by
The property teams does not seem to exist on PhpDraft\Domain\Entities\Draft.
Loading history...
410
    $draft->positions = null;
0 ignored issues
show
Bug introduced by
The property positions does not exist on PhpDraft\Domain\Entities\Draft. Did you mean sports_positions?
Loading history...
411
    $draft->using_depth_charts = null;
412
    $draft->depthChartPositions = null;
0 ignored issues
show
Bug introduced by
The property depthChartPositions does not seem to exist on PhpDraft\Domain\Entities\Draft.
Loading history...
413
414
    return $draft;
415
  }
416
417
  private function FetchPublicDraftById($id) {
418
    $draft = new Draft();
419
420
    $draft_stmt = $this->app['db']->prepare("SELECT d.*, u.Name AS commish_name FROM draft d
421
      LEFT OUTER JOIN users u
422
      ON d.commish_id = u.id
423
      WHERE d.draft_id = ? LIMIT 1");
424
425
    $draft_stmt->setFetchMode(\PDO::FETCH_INTO, $draft);
426
427
    $draft_stmt->bindParam(1, $id, \PDO::PARAM_INT);
428
429
    if (!$draft_stmt->execute() || !$draft_stmt->fetch()) {
430
      throw new \Exception("Unable to load draft");
431
    }
432
433
    $draft->using_depth_charts = $draft->using_depth_charts == 1;
434
435
    return $draft;
436
  }
437
438
  private function NormalizeDraftTimesAndStatuses($draft) {
439
    $draft->setting_up = $this->app['phpdraft.DraftService']->DraftSettingUp($draft);
440
    $draft->in_progress = $this->app['phpdraft.DraftService']->DraftInProgress($draft);
441
    $draft->complete = $this->app['phpdraft.DraftService']->DraftComplete($draft);
442
443
    $draft->draft_create_time = $this->app['phpdraft.UtilityService']->ConvertTimeForClientDisplay($draft->draft_create_time);
444
    $draft->draft_start_time = $this->app['phpdraft.UtilityService']->ConvertTimeForClientDisplay($draft->draft_start_time);
445
    $draft->draft_end_time = $this->app['phpdraft.UtilityService']->ConvertTimeForClientDisplay($draft->draft_end_time);
446
447
    return $draft;
448
  }
449
450
  private function SetSecurityProperties($currentUser, $draft) {
0 ignored issues
show
Unused Code introduced by
The parameter $currentUser is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

450
  private function SetSecurityProperties(/** @scrutinizer ignore-unused */ $currentUser, $draft) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
451
    $currentUserOwnsIt = !empty($current_user) && $draft->commish_id == $current_user->id;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $current_user does not exist. Did you maybe mean $currentUser?
Loading history...
452
    $currentUserIsAdmin = !empty($current_user) && $this->app['phpdraft.LoginUserService']->CurrentUserIsAdmin($current_user);
453
454
    $draft->draft_visible = empty($draft->draft_password);
455
    $draft->commish_editable = $currentUserOwnsIt || $currentUserIsAdmin;
456
    $draft->is_locked = false;
457
458
459
    if (!$currentUserOwnsIt && !$currentUserIsAdmin && !$draft->draft_visible && $password != $draft->draft_password) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $password seems to be never defined.
Loading history...
460
      $draft->is_locked = true;
461
      $draft = $this->ProtectPrivateDraft($draft);
462
    }
463
464
    unset($draft->draft_password);
465
466
    return $draft;
467
  }
468
}
469