/
ShowWithPreview.php
97 lines (84 loc) · 2.56 KB
/
ShowWithPreview.php
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
<?php
namespace A17\Twill\Http\Controllers\Front;
use Illuminate\Config\Repository as Config;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Str;
use Illuminate\View\Factory as ViewFactory;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
trait ShowWithPreview
{
/**
* @param string $slug
* @param Request $request
* @param Redirector $redirector
* @param ViewFactory $viewFactory
* @param Config $config
* @return \Illuminate\Contracts\View\View|\Illuminate\Http\RedirectResponse
* @throws \Exception
*/
public function show(
string $slug,
Request $request,
Redirector $redirector,
ViewFactory $viewFactory,
Config $config
) {
if (!isset($this->moduleName) || !isset($this->repository)) {
throw new \Exception("You should at least provide a module name and inject a repository.");
}
if (!isset($this->routeName)) {
$this->routeName = $this->moduleName;
}
if (!isset($this->showViewName)) {
$this->showViewName = $config->get('twill.frontend.views_path', 'site') . '.' . Str::singular($this->moduleName);
}
if (Str::endsWith($request->route()->getName(), $this->routeName . '.preview')) {
$item = $this->getItemPreview($slug);
}
$item = ($item ?? $this->getItem($slug));
if (!$item) {
throw new NotFoundHttpException(ucfirst($this->moduleName) . ' not found');
}
if ($item->redirect) {
return $redirector->to(route($this->routeName . '.show', $item->getSlug()));
}
return $viewFactory->make($this->showViewName, [
'item' => $item,
] + $this->showData($slug, $item));
}
/**
* @param string $slug
* @return \A17\Twill\Models\Model|null
*/
protected function getItem($slug)
{
return $this->repository->forSlug(
$slug,
$this->showWith ?? [],
$this->showWithCount ?? [],
$this->showScopes ?? []
);
}
/**
* @param $slug
* @return \A17\Twill\Models\Model|null
*/
protected function getItemPreview($slug)
{
return $this->repository->forSlugPreview(
$slug,
$this->showWith ?? [],
$this->showWithCount ?? []
);
}
/**
* @param string $slug
* @param mixed $item
* @return array
*/
protected function showData($slug, $item)
{
return [];
}
}