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