ArticleComposer.php 1.26 KB
<?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);
    }
}