Passed
Pull Request — master (#53)
by Matthew
02:43
created

DraftRepository::GetAllDraftsByCommish()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 27
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 13
dl 0
loc 27
rs 9.8333
c 0
b 0
f 0
cc 3
nc 3
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 = '') {
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, $password);
35
36
      $drafts[] = $draft;
37
    }
38
39
    return $drafts;
40
  }
41
42
  public function GetPublicDraftsByCommish(Request $request, $commish_id, $password = '') {
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, $password);
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 = '') {
129
    $cachedDraft = $this->GetCachedDraft($id);
130
131
    if ($cachedDraft != null) {
132
      $draft = $cachedDraft;
133
    } else {
134
      $draft = $this->FetchPublicDraftById($id);
135
136
      $this->SetCachedDraft($draft);
137
    }
138
139
    $currentUser = $this->app['phpdraft.LoginUserService']->GetUserFromHeaderToken($request);
140
141
    $draft = $this->NormalizeDraftTimesAndStatuses($draft);
142
    $draft = $this->SetSecurityProperties($currentUser, $draft, $password);
143
144
    if ($getDraftData) {
145
      $draft->sports = $this->app['phpdraft.DraftDataRepository']->GetSports();
146
      $draft->styles = $this->app['phpdraft.DraftDataRepository']->GetStyles();
147
      $draft->statuses = $this->app['phpdraft.DraftDataRepository']->GetStatuses();
148
      $draft->teams = $this->app['phpdraft.DraftDataRepository']->GetTeams($draft->draft_sport);
149
      $draft->historical_teams = $this->app['phpdraft.DraftDataRepository']->GetHistoricalTeams($draft->draft_sport);
150
      $draft->positions = $this->app['phpdraft.DraftDataRepository']->GetPositions($draft->draft_sport);
151
152
      if ($draft->using_depth_charts) {
153
        $draft->depthChartPositions = $this->app['phpdraft.DepthChartPositionRepository']->LoadAll($draft->draft_id);
154
      }
155
    }
156
157
    return $draft;
158
  }
159
160
  /*
161
  * This method is only to be used internally or when the user has been verified as owner of the draft (or is admin)
162
  * (in other words, don't call this then return the result as JSON!)
163
  */
164
  public function Load($id, $bustCache = false) {
165
    $cachedDraft = $this->GetCachedDraft($id);
166
167
    if ($bustCache || $cachedDraft == null) {
168
      $draft = $this->FetchPublicDraftById($id);
169
170
      if ($bustCache) {
171
        $this->UnsetCachedDraft($draft->draft_id);
172
      }
173
174
      $this->SetCachedDraft($draft);
175
    } else {
176
      $draft = $cachedDraft;
177
    }
178
179
    $draft->draft_rounds = (int)$draft->draft_rounds;
180
181
    return $draft;
182
  }
183
184
  public function Create(Draft $draft) {
185
    $insert_stmt = $this->app['db']->prepare("INSERT INTO draft
186
      (draft_id, commish_id, draft_create_time, draft_name, draft_sport, draft_status, draft_style, draft_rounds, draft_password, using_depth_charts)
187
      VALUES
188
      (NULL, ?, UTC_TIMESTAMP(), ?, ?, ?, ?, ?, ?, ?)");
189
190
    $insert_stmt->bindParam(1, $draft->commish_id);
191
    $insert_stmt->bindParam(2, $draft->draft_name);
192
    $insert_stmt->bindParam(3, $draft->draft_sport);
193
    $insert_stmt->bindParam(4, $draft->draft_status);
194
    $insert_stmt->bindParam(5, $draft->draft_style);
195
    $insert_stmt->bindParam(6, $draft->draft_rounds);
196
    $insert_stmt->bindParam(7, $draft->draft_password);
197
    $insert_stmt->bindParam(8, $draft->using_depth_charts);
198
199
    if (!$insert_stmt->execute()) {
200
      throw new \Exception("Unable to create draft.");
201
    }
202
203
    $draft = $this->Load((int)$this->app['db']->lastInsertId(), true);
204
205
    return $draft;
206
  }
207
208
  //Excluded properties in update:
209
  //draft_start_time/draft_end_time - updated in separate operations at start/end of draft
210
  //draft_current_round/draft_current_pick - updated when new picks are made
211
  //draft_counter - call IncrementDraftCounter instead - this call's made a lot independently of other properties.
212
  //draft_status - separate API call to update the draft status
213
  public function Update(Draft $draft) {
214
    $update_stmt = $this->app['db']->prepare("UPDATE draft
215
      SET commish_id = ?, draft_name = ?, draft_sport = ?,
216
      draft_style = ?, draft_password = ?, draft_rounds = ?,
217
      using_depth_charts = ?
218
      WHERE draft_id = ?");
219
220
    $draft->using_depth_charts = $draft->using_depth_charts;
221
222
    $update_stmt->bindParam(1, $draft->commish_id);
223
    $update_stmt->bindParam(2, $draft->draft_name);
224
    $update_stmt->bindParam(3, $draft->draft_sport);
225
    $update_stmt->bindParam(4, $draft->draft_style);
226
    $update_stmt->bindParam(5, $draft->draft_password);
227
    $update_stmt->bindParam(6, $draft->draft_rounds);
228
    $update_stmt->bindParam(7, $draft->using_depth_charts);
229
    $update_stmt->bindParam(8, $draft->draft_id);
230
231
    if (!$update_stmt->execute()) {
232
      throw new \Exception("Unable to update draft.");
233
    }
234
235
    $this->ResetDraftCache($draft->draft_id);
236
237
    return $draft;
238
  }
239
240
  public function UpdateStatus(Draft $draft) {
241
    $status_stmt = $this->app['db']->prepare("UPDATE draft
242
      SET draft_status = ? WHERE draft_id = ?");
243
244
    $status_stmt->bindParam(1, $draft->draft_status);
245
    $status_stmt->bindParam(2, $draft->draft_id);
246
247
    if (!$status_stmt->execute()) {
248
      throw new \Exception("Unable to update draft status.");
249
    }
250
251
    $this->ResetDraftCache($draft->draft_id);
252
253
    return $draft;
254
  }
255
256
  public function UpdateStatsTimestamp(Draft $draft) {
257
    $status_stmt = $this->app['db']->prepare("UPDATE draft
258
      SET draft_stats_generated = UTC_TIMESTAMP() WHERE draft_id = ?");
259
260
    $status_stmt->bindParam(1, $draft->draft_id);
261
262
    if (!$status_stmt->execute()) {
263
      throw new \Exception("Unable to update draft's stats timestamp.");
264
    }
265
266
    $this->ResetDraftCache($draft->draft_id);
267
268
    return $draft;
269
  }
270
271
  public function IncrementDraftCounter(Draft $draft) {
272
    $incrementedCounter = (int)$draft->draft_counter + 1;
273
274
    $increment_stmt = $this->app['db']->prepare("UPDATE draft
275
      SET draft_counter = ? WHERE draft_id = ?");
276
277
    $increment_stmt->bindParam(1, $incrementedCounter);
278
    $increment_stmt->bindParam(2, $draft->draft_id);
279
280
    if (!$increment_stmt->execute()) {
281
      throw new \Exception("Unable to increment draft counter.");
282
    }
283
284
    $this->ResetDraftCache($draft->draft_id);
285
286
    return $incrementedCounter;
287
  }
288
289
  //$next_pick can't be type-hinted - can be null
290
  public function MoveDraftForward(Draft $draft, $next_pick) {
291
    if ($next_pick !== null) {
292
      $draft->draft_current_pick = (int)$next_pick->player_pick;
293
      $draft->draft_current_round = (int)$next_pick->player_round;
294
295
      $stmt = $this->app['db']->prepare("UPDATE draft SET draft_current_pick = ?, draft_current_round = ? WHERE draft_id = ?");
296
      $stmt->bindParam(1, $draft->draft_current_pick);
297
      $stmt->bindParam(2, $draft->draft_current_round);
298
      $stmt->bindParam(3, $draft->draft_id);
299
300
      if (!$stmt->execute()) {
301
        throw new \Exception("Unable to move draft forward.");
302
      }
303
    } else {
304
      $draft->draft_status = 'complete';
305
      $stmt = $this->app['db']->prepare("UPDATE draft SET draft_status = ?, draft_end_time = UTC_TIMESTAMP() WHERE draft_id = ?");
306
      $stmt->bindParam(1, $draft->draft_status);
307
      $stmt->bindParam(2, $draft->draft_id);
308
309
      if (!$stmt->execute()) {
310
        throw new \Exception("Unable to move draft forward.");
311
      }
312
    }
313
314
    $this->ResetDraftCache($draft->draft_id);
315
316
    return $draft;
317
  }
318
319
  //Used when we move a draft from "undrafted" to "in_progress":
320
  //Resets the draft counter
321
  //Sets the current pick and round to 1
322
  //Sets the draft start time to UTC now, nulls out end time
323
  public function SetDraftInProgress(Draft $draft) {
324
    $reset_stmt = $this->app['db']->prepare("UPDATE draft
325
      SET draft_counter = 0, draft_current_pick = 1, draft_current_round = 1,
326
      draft_start_time = UTC_TIMESTAMP(), draft_end_time = NULL
327
      WHERE draft_id = ?");
328
329
    $reset_stmt->bindParam(1, $draft->draft_id);
330
331
    if (!$reset_stmt->execute()) {
332
      throw new \Exception("Unable to set draft to in progress.");
333
    }
334
335
    $this->ResetDraftCache($draft->draft_id);
336
337
    return 0;
338
  }
339
340
  public function NameIsUnique($name, $id = null) {
341
    if (!empty($id)) {
342
      $name_stmt = $this->app['db']->prepare("SELECT draft_name FROM draft WHERE draft_name LIKE ? AND draft_id <> ?");
343
      $name_stmt->bindParam(1, $name);
344
      $name_stmt->bindParam(2, $id);
345
    } else {
346
      $name_stmt = $this->app['db']->prepare("SELECT draft_name FROM draft WHERE draft_name LIKE ?");
347
      $name_stmt->bindParam(1, $name);
348
    }
349
350
    if (!$name_stmt->execute()) {
351
      throw new \Exception("Draft name '%s' is invalid", $name);
352
    }
353
354
    return $name_stmt->rowCount() == 0;
355
  }
356
357
  public function DeleteDraft($draft_id) {
358
    $delete_stmt = $this->app['db']->prepare("DELETE FROM draft WHERE draft_id = ?");
359
    $delete_stmt->bindParam(1, $draft_id);
360
361
    if (!$delete_stmt->execute()) {
362
      throw new \Exception("Unable to delete draft $draft_id.");
363
    }
364
365
    $this->UnsetCachedDraft($draft_id);
366
367
    return;
368
  }
369
370
  private function ResetDraftCache($draft_id) {
371
    $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...
372
  }
373
374
  private function SetCachedDraft(Draft $draft) {
375
    $this->app['phpdraft.DatabaseCacheService']->SetCachedItem("draft$draft->draft_id", $draft);
376
  }
377
378
  private function GetCachedDraft($draft_id) {
379
    return $this->app['phpdraft.DatabaseCacheService']->GetCachedItem("draft$draft_id");
380
  }
381
382
  private function UnsetCachedDraft($draft_id) {
383
    $this->app['phpdraft.DatabaseCacheService']->DeleteCachedItem("draft$draft_id");
384
  }
385
386
  private function ProtectPrivateDraft(Draft $draft) {
387
    $draft->draft_sport = '';
388
    $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...
389
    $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...
390
    $draft->complete = '';
0 ignored issues
show
Bug introduced by
The property complete does not seem to exist on PhpDraft\Domain\Entities\Draft.
Loading history...
391
    $draft->draft_style = '';
392
    $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...
393
    $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...
394
    $draft->draft_start_time = null;
395
    $draft->draft_end_time = null;
396
    $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...
397
    $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...
398
    $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...
399
    $draft->draft_stats_generated = '';
400
    $draft->nfl_extended = null;
401
    $draft->sports = null;
402
    $draft->styles = null;
403
    $draft->statuses = null;
404
    $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...
405
    $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...
406
    $draft->using_depth_charts = null;
407
    $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...
408
409
    return $draft;
410
  }
411
412
  private function FetchPublicDraftById($id) {
413
    $draft = new Draft();
414
415
    $draft_stmt = $this->app['db']->prepare("SELECT d.*, u.Name AS commish_name FROM draft d
416
      LEFT OUTER JOIN users u
417
      ON d.commish_id = u.id
418
      WHERE d.draft_id = ? LIMIT 1");
419
420
    $draft_stmt->setFetchMode(\PDO::FETCH_INTO, $draft);
421
422
    $draft_stmt->bindParam(1, $id, \PDO::PARAM_INT);
423
424
    if (!$draft_stmt->execute() || !$draft_stmt->fetch()) {
425
      throw new \Exception("Unable to load draft");
426
    }
427
428
    $draft->using_depth_charts = $draft->using_depth_charts == 1;
429
430
    return $draft;
431
  }
432
433
  private function NormalizeDraftTimesAndStatuses($draft) {
434
    $draft->setting_up = $this->app['phpdraft.DraftService']->DraftSettingUp($draft);
435
    $draft->in_progress = $this->app['phpdraft.DraftService']->DraftInProgress($draft);
436
    $draft->complete = $this->app['phpdraft.DraftService']->DraftComplete($draft);
437
438
    $draft->display_status = $this->app['phpdraft.DraftService']->GetDraftStatusDisplay($draft);
439
440
    $draft->draft_create_time = $this->app['phpdraft.UtilityService']->ConvertTimeForClientDisplay($draft->draft_create_time);
441
    $draft->draft_start_time = $this->app['phpdraft.UtilityService']->ConvertTimeForClientDisplay($draft->draft_start_time);
442
    $draft->draft_end_time = $this->app['phpdraft.UtilityService']->ConvertTimeForClientDisplay($draft->draft_end_time);
443
444
    return $draft;
445
  }
446
447
  private function SetSecurityProperties($currentUser, $draft, $password) {
448
    $currentUserOwnsIt = !empty($currentUser) && $draft->commish_id == $currentUser->id;
449
    $currentUserIsAdmin = !empty($currentUser) && $this->app['phpdraft.LoginUserService']->CurrentUserIsAdmin($currentUser);
450
451
    $draft->draft_visible = empty($draft->draft_password);
452
    $draft->commish_editable = $currentUserOwnsIt || $currentUserIsAdmin;
453
    $draft->is_locked = false;
454
455
    if (!$draft->commish_editable && !$draft->draft_visible && $password != $draft->draft_password) {
456
      $draft->is_locked = true;
457
      $draft->draft_status = 'locked';
458
      $draft->display_status = 'Locked';
459
      $draft = $this->ProtectPrivateDraft($draft);
460
    }
461
462
    unset($draft->draft_password);
463
464
    return $draft;
465
  }
466
}
467