Blame view

app/Http/ViewComposers/ArticleComposer.php 1.26 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
  <?php
  
  namespace FootyRoom\Http\ViewComposers;
  
  use Illuminate\Contracts\View\View;
  use FootyRoom\Queries\Article\ArticleQuery;
  use Illuminate\Http\Exceptions\HttpResponseException;
  use Illuminate\Http\RedirectResponse;
  use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  
  class ArticleComposer
  {
      /** @var \FootyRoom\Queries\Article\ArticleQuery */
      protected $articleQuery;
  
      public function __construct(ArticleQuery $articleQuery)
      {
          $this->articleQuery = $articleQuery;
      }
  
      public function compose(View $view, string $slug, string $articleId): View
      {
          $this->loadArticle($view, $articleId);
  
          $view->with('canonical', $view->article->getUrl());
  
          if ($slug !== $view->article->getSlug()) {
              throw  new HttpResponseException(new RedirectResponse($view->canonical, 301));
          }
  
          return $view;
      }
  
      /**
       * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
       */
      protected function loadArticle(View $view, $articleId): void
      {
          $article = $this->articleQuery->findOne($articleId);
  
          if (!$article || $article->getStatus() !== 'published') {
              throw new NotFoundHttpException();
          }
  
          $view->with('article', $article);
      }
  }