Blame view

app/Http/ViewComposers/CompetitionComposer.php 12.6 KB
e77200db5   nologostudio.ru   Initial commit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
  <?php
  
  namespace FootyRoom\Http\ViewComposers;
  
  use Exception;
  use Illuminate\View\View;
  use FootyRoom\Queries\MatchQuery;
  use FootyRoom\Queries\StageQuery;
  use FootyRoom\Queries\TableQuery;
  use FootyRoom\Core\Match\MatchDays;
  use FootyRoom\Support\Utils\Helpers;
  use FootyRoom\Queries\MatchPostQuery;
  use FootyRoom\Queries\StageGuideQuery;
  use FootyRoom\Queries\StageStatsQuery;
  use Illuminate\Contracts\Cache\Repository;
  
  class CompetitionComposer
  {
      /**
       * @var int
       */
      protected $postPerPage = 24;
  
      /**
       * @var \FootyRoom\Queries\StageGuideQuery
       */
      protected $guideRepo;
  
      /**
       * @var \FootyRoom\Queries\TableQuery
       */
      protected $tableRepo;
  
      /**
       * @var \FootyRoom\Queries\StageQuery
       */
      protected $stageRepo;
  
      /**
       * @var \FootyRoom\Queries\MatchPostQuery
       */
      protected $matchPostQuery;
  
      /**
       * @var \FootyRoom\Queries\StageStatsQuery
       */
      protected $statsRepo;
  
      /**
       * @var \FootyRoom\Queries\MatchQuery
       */
      protected $matchRepo;
  
      /**
       * @var \Illuminate\Contracts\Cache\Repository
       */
      protected $cache;
  
      /**
       * Constructor.
       *
       * @param MatchPostQuery $matchPostQuery
       * @param TableQuery $tableRepo
       * @param StageQuery $stageRepo
       * @param StageStatsQuery $statsRepo
       * @param StageGuideQuery $guideRepo
       * @param MatchQuery $matchRepo
       * @param \Illuminate\Contracts\Cache\Repository $cache
       */
      public function __construct(
          MatchPostQuery $matchPostQuery,
          TableQuery $tableRepo,
          StageQuery $stageRepo,
          StageStatsQuery $statsRepo,
          StageGuideQuery $guideRepo,
          MatchQuery $matchRepo,
          Repository $cache
      ) {
          $this->matchPostQuery = $matchPostQuery;
          $this->tableRepo = $tableRepo;
          $this->stageRepo = $stageRepo;
          $this->guideRepo = $guideRepo;
          $this->statsRepo = $statsRepo;
          $this->matchRepo = $matchRepo;
          $this->cache = $cache;
      }
  
      /**
       * Compose the view.
       *
       * @param \Illuminate\View\View $view
       * @param $competitionSlug
       * @param $competitionId
       * @param int $page
       * @param null $stageId
       *
       * @throws \Exception
       * @return \Illuminate\View\View
       */
      public function compose(View $view, $competitionSlug, $competitionId, $page = 1, $stageId = null)
      {
          $viewData = $this->cache->remember(
              "CompetitionComposer_{$competitionSlug}_{$competitionId}_{$page}_{$stageId}",
              0.3,
              function () use ($view, $competitionSlug, $competitionId, $page, $stageId) {
                  $view->with('competitionId', $competitionId);
                  $view->with('competitionSlug', $competitionSlug);
  
                  // Load competition stages.
                  $this->loadStages($view, $competitionId, $stageId);
  
                  // Load review posts.
                  $this->loadPosts($view, $view->stage->tree, $page);
  
                  // Load standings.
                  $this->loadTables($view, $view->stages);
  
                  // Load fixtures.
                  $this->loadFixtures($view, $view->stage->tree);
  
                  // Load guide.
                  $this->loadGuide($view, $view->season->id);
  
                  // Load stage stats.
                  $this->loadStats($view);
  
                  $this->setupCanonical($view, $competitionId, $competitionSlug, $page);
  
                  $view->with('tabs', $this->getExtraContentTabs($view));
  
                  return $view->getData();
              }
          );
  
          $view->with($viewData);
  
          return $view;
      }
  
      /**
       * Setup next and prev rel link.
       */
      protected function setupRelLinksHtml(View $view, $stageTree, $offset, int $page)
      {
          $hasMorePosts = (bool) $this->matchPostQuery->findByStageTree($stageTree, $offset + $this->postPerPage, 1);
          
          $view->with('relLinksHtml', Helpers::relLinks($hasMorePosts, $view->canonical, $page));
      }
  
      /**
       * Set up page canonical link.
       */
      protected function setupCanonical(View $view, int $competitionId, string $competitionSlug, int $page)
      {
          $routeParam = [
              'id' => $competitionId,
              'slug' => $competitionSlug,
          ];
  
          if ($page !== 1) {
              $routeParam['page'] = $page;
          }
  
          if ($view->season->id !== $view->seasons[0]->id) {
              $routeParam['stageId'] = $view->stage->parent;
          }
  
          $view->with('canonical', route('competition', $routeParam));
      }
  
      /**
       * Loads posts.
       *
       * @param \Illuminate\View\View $view
       * @param string $stageTree
       * @param int $page
       *
       * @throws \Exception
       */
      protected function loadPosts(View $view, $stageTree, $page)
      {
          $offset = $this->postPerPage * ($page - 1);
  
          $view->with('page', $page);
  
          $view->with('posts', $this->matchPostQuery->findByStageTree($stageTree, $offset, $this->postPerPage));
  
          // If we are not on first page and no posts have been found then this is not a valid view.
          if ($page > 1 && !$view->posts) {
              throw new Exception('NoPosts');
          }
  
          $this->setupRelLinksHtml($view, $stageTree, $offset, $page);
      }
  
      /**
       * Loads stages.
       *
       * @param \Illuminate\View\View $view
       * @param int $competitionId
       * @param int $stageId
       *
       * @throws \Exception
       */
      protected function loadStages(View $view, $competitionId, $stageId)
      {
          // Find competition's seasons.
          $seasons = $this->stageRepo->findSeasons($competitionId);
  
          if (!$seasons) {
              throw new Exception('NoSeasons');
          }
  
          // Set current season if stage is known.
          if ($stageId) {
              $season = $this->stageRepo->findSeasonOf($stageId);
          }
  
          // If season is not yet set then check if competition has a "default
          // season" property configured and use that to calculate season to show.
          // Currently we only support 'year' option which will choose default
          // season to correspond with current year.
          if (!isset($season)) {
              $competition = $this->stageRepo->findById($competitionId);
  
              if (isset($competition->meta->defaultSeason) && $competition->meta->defaultSeason === 'year') {
                  $currentYear = date('Y');
  
                  foreach ($seasons as $s) {
                      if ($s->meta->year == $currentYear) {
                          $season = $s;
                          break;
                      }
                  }
              }
          }
  
          // If season is not yet set then choose the latest one from the
          // competition's seasons.
          if (!isset($season)) {
              $season = $seasons[0];
          }
  
          // Get all of the current season's stages.
          $stages = $this->stageRepo->findStagesByTree($season->tree);
  
          if (!$stages) {
              throw new Exception('NoStages');
          }
  
          if (count($stages) === 1) {
              // If there is only one stage in this season then set it to be the
              // current stage.
              $stage = $stages[0];
          } elseif ($stageId) {
              $stage = $this->searchStagesById($stageId, $stages);
          }
  
          // If stage is not yet set, then set it to current season by default.
          if (!isset($stage)) {
              $stage = $season;
          }
  
          $view->with('seasons', $seasons);
          $view->with('stages', $stages);
          $view->with('season', $season);
          $view->with('stage', $stage);
      }
  
      /**
       * Loads tables.
       *
       * @param \Illuminate\View\View $view
       * @param array $stages
       */
      protected function loadTables(View $view, array $stages)
      {
          $enetStageIds = [];
  
          if (count($stages) > 0) {
              foreach ($stages as $stage) {
                  /**
                   * TODO: This implementation for looking up tables depends on
                   * enetStageId. We should instead look up by our own stage id.
                   */
                  if (isset($stage->meta->enetStageId)) {
                      $enetStageIds[] = (int) $stage->meta->enetStageId;
                  }
              }
          }
  
          $cursor = $this->tableRepo->findByEnetStageIds($enetStageIds);
  
          $tables = [];
  
          // There may be more than one table returned (such as group tables).
          foreach ($cursor as $table) {
              $tables[] = $table;
          }
  
          $view->with('tables', $tables);
      }
  
      /**
       * Loads fixtures.
       *
       * @param \Illuminate\View\View $view
       * @param string $stageTree
       */
      protected function loadFixtures(View $view, $stageTree)
      {
          $matchDays = MatchDays::getDays(
              $this->matchRepo->distinctTimesByStageTree($stageTree)
          );
  
          // Figure out the date of Monday of the week in which current match day falls.
          if (date('w', strtotime($matchDays['currentDay'])) === '1') {
              $minDate = strtotime('this Monday', strtotime($matchDays['currentDay']));
          } else {
              $minDate = strtotime('last Monday', strtotime($matchDays['currentDay']));
          }
  
          $view->with('matches', $this->matchRepo->find([
              'stageTree' => $stageTree,
              'minDate' => $minDate,
              'maxDate' => strtotime('next Monday', strtotime($matchDays['currentDay'])) - 1,
          ]));
  
          $view->with('matchDays', $matchDays);
      }
  
      /**
       * Loads stage guide.
       *
       * @param \Illuminate\View\View $view
       * @param int $stageId
       */
      protected function loadGuide(View $view, $stageId)
      {
          $view->with('guide', $this->guideRepo->findOneByStageId($stageId));
      }
  
      /**
       * Searches given stages by id and returns the first found one.
       *
       * @param int $stageId
       * @param array $stages
       *
       * @return array|null
       */
      protected function searchStagesById($stageId, $stages)
      {
          foreach ($stages as $stage) {
              if ($stage->id === $stageId) {
                  return $stage;
              }
          }
  
          return null;
      }
  
      /**
       * Decides which extra content tab should be active.
       *
       * @param \Illuminate\View\View $view
       *
       * @return array[string]
       */
      protected function getExtraContentTabs(View $view): array
      {
          $tabs = [];
  
          if ($view->guide) {
              $tabs[] = 'guide';
          }
  
          if (count($view->matches) > 0) {
              $tabs[] = 'fixtures';
          }
          
          if ($view->tables) {
              $tabs[] = 'tables';
          }
  
          if ($view->stats) {
              $tabs[] = 'stats';
          }
          
          return $tabs;
      }
  
      /**
       * Load stats into view.
       *
       * @param \Illuminate\View\View $view
       */
      protected function loadStats(View $view): void
      {
          $currentStageTree = explode(',', $view->stage->tree);
          
          if (count($currentStageTree) > 2 && $this->isProperOrQualifiers((int) $currentStageTree[2], $view->stages)) {
              $stats = $this->statsRepo->findByStageId((int) $currentStageTree[2]);
          } else if (count($currentStageTree) === 2) {
              [$qualifiers, $proper] = $this->getQualifiersAndProper($view);
  
              if ($proper) {
                  $stats = $this->statsRepo->findByStageId($proper->id);
              }
  
              if ($qualifiers && !isset($stats)) {
                  $stats = $this->statsRepo->findByStageId($qualifiers->id);
              }
          }
  
          if (!isset($stats)) {
              $stats = $this->statsRepo->findByStageId($view->season->id);
          }
          
          $view->with('stats', $stats);
      }
  
      protected function getQualifiersAndProper($view)
      {
          $qualifiers = null;
          $proper = null;
          
          foreach ($view->stages as $stage) {
              if (!$proper && $stage->name === 'Tournament Proper') {
                  $proper = $stage;
              }
  
              if (!$qualifiers && preg_match('/^qualif/i', $stage->name)) {
                  $qualifiers = $stage;
              }
  
              if ($proper && $qualifiers) {
                  break;
              }
          }
  
          return [$qualifiers, $proper];
      }
  
      /**
       * Given a third level stage id that is within current season, will let you know if this
       * stage is tournament proper or a qualifiers stage.
       *
       * @param int $stageId
       *
       * @return bool
       */
      protected function isProperOrQualifiers(int $stageId, $stages): bool
      {
          $stage = $this->searchStagesById($stageId, $stages);
  
          if ($stage->name === 'Tournament Proper' || preg_match('/^qualif/i', $stage->name)) {
              return true;
          }
  
          return false;
      }
  }