1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Thinktomorrow\Chief\Urls; |
4
|
|
|
|
5
|
|
|
use Illuminate\Http\RedirectResponse; |
6
|
|
|
use Illuminate\Http\Response; |
7
|
|
|
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; |
8
|
|
|
use Thinktomorrow\Chief\Concerns\Morphable\Morphables; |
9
|
|
|
use Thinktomorrow\Chief\Concerns\Morphable\NotFoundMorphKey; |
10
|
|
|
use Thinktomorrow\Chief\Concerns\Publishable\PreviewMode; |
11
|
|
|
|
12
|
|
|
class ChiefResponse extends Response |
13
|
|
|
{ |
14
|
10 |
|
public static function fromSlug(string $slug, $locale = null) |
15
|
|
|
{ |
16
|
10 |
|
if (!$locale) { |
17
|
7 |
|
$locale = app()->getLocale(); |
|
|
|
|
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
try { |
21
|
10 |
|
$urlRecord = UrlRecord::findBySlug($slug, $locale); |
22
|
|
|
|
23
|
8 |
|
$model = Morphables::instance($urlRecord->model_type)->find($urlRecord->model_id); |
24
|
|
|
|
25
|
7 |
|
if ($urlRecord->isRedirect()) { |
26
|
|
|
|
27
|
|
|
// If model is not found, it probably means it is archived or removed |
28
|
|
|
// So we detect the model based on the redirect target url. |
29
|
3 |
|
if (!$model) { |
30
|
1 |
|
$targetUrlRecord = $urlRecord->redirectTo(); |
31
|
1 |
|
$targetModel = Morphables::instance($targetUrlRecord->model_type)->find($targetUrlRecord->model_id); |
32
|
|
|
|
33
|
1 |
|
return static::createRedirect($targetModel->url($locale)); |
34
|
|
|
} |
35
|
|
|
|
36
|
2 |
|
return static::createRedirect($model->url($locale)); |
37
|
|
|
} |
38
|
|
|
|
39
|
4 |
|
if (method_exists($model, 'isPublished') && ! $model->isPublished()) { |
40
|
|
|
|
41
|
|
|
/** When admin is logged in and this request is in preview mode, we allow the view */ |
42
|
2 |
|
if (! PreviewMode::fromRequest()->check()) { |
43
|
1 |
|
throw new NotFoundHttpException('Model found for request ['. $slug .'] but it is not published.'); |
44
|
|
|
} |
45
|
|
|
} |
46
|
|
|
|
47
|
3 |
|
return new static($model->renderView(), 200); |
48
|
4 |
|
} catch (UrlRecordNotFound | NotFoundMorphKey $e) { |
49
|
3 |
|
if (config('thinktomorrow.chief.strict')) { |
50
|
|
|
throw $e; |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|
54
|
3 |
|
throw new NotFoundHttpException('No url or model found for request ['. $slug .'] for locale ['.$locale.'].'); |
55
|
|
|
} |
56
|
|
|
|
57
|
3 |
|
private static function createRedirect(string $url) |
58
|
|
|
{ |
59
|
3 |
|
return new RedirectResponse($url, 301, []); |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|