-
Notifications
You must be signed in to change notification settings - Fork 554
/
HandleSlugs.php
87 lines (71 loc) · 2.83 KB
/
HandleSlugs.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
<?php
namespace A17\Twill\Repositories\Behaviors;
trait HandleSlugs
{
public function afterSaveHandleSlugs($object, $fields)
{
if (property_exists($this->model, 'slugAttributes')) {
foreach (getLocales() as $locale) {
if (isset($fields['slug']) && isset($fields['slug'][$locale]) && !empty($fields['slug'][$locale])) {
$object->disableLocaleSlugs($locale);
$currentSlug = [];
$currentSlug['slug'] = $fields['slug'][$locale];
$currentSlug['locale'] = $locale;
$currentSlug['active'] = property_exists($this->model, 'translatedAttributes') ? $object->translate($locale)->active : 1;
$currentSlug = $this->getSlugParameters($object, $fields, $currentSlug);
$object->updateOrNewSlug($currentSlug);
}
}
}
}
public function afterDeleteHandleSlugs($object)
{
$object->slugs()->delete();
}
public function afterRestoreHandleSlugs($object)
{
$object->slugs()->restore();
}
public function getFormFieldsHandleSlugs($object, $fields)
{
unset($fields['slugs']);
if ($object->slugs != null) {
foreach ($object->slugs as $slug) {
if ($slug->active || $object->slugs->where('locale', $slug->locale)->where('active', true)->count() === 0) {
$fields['translations']['slug'][$slug->locale] = $slug->slug;
}
}
}
return $fields;
}
public function getSlugParameters($object, $fields, $slug)
{
$slugParams = $object->getSlugParams($slug['locale']);
foreach ($object->slugAttributes as $param) {
if (isset($slugParams[$param]) && isset($fields[$param])) {
$slug[$param] = $fields[$param];
} elseif (isset($slugParams[$param])) {
$slug[$param] = $slugParams[$param];
}
}
return $slug;
}
public function forSlug($slug, $with = [], $withCount = [], $scopes = [])
{
$query = $this->model->where($scopes)->scopes(['published', 'visible']);
foreach (class_uses_recursive(get_called_class()) as $trait) {
if (method_exists(get_called_class(), $method = 'getPublishedScopes')) {
$query->scopes($this->$method());
}
}
$item = (clone $query)->forSlug($slug)->with($with)->withCount($withCount)->first();
if (!$item && $item = (clone $query)->forInactiveSlug($slug)->first()) {
$item->redirect = true;
}
return $item;
}
public function forSlugPreview($slug, $with = [], $withCount = [])
{
return $this->model->forInactiveSlug($slug)->with($with)->withCount($withCount)->first();
}
}