1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace Thinktomorrow\Chief\Settings\Application; |
5
|
|
|
|
6
|
|
|
use Thinktomorrow\Chief\Concerns\Morphable\Morphables; |
7
|
|
|
use Thinktomorrow\Chief\FlatReferences\FlatReferenceFactory; |
8
|
|
|
use Thinktomorrow\Chief\Settings\Setting; |
9
|
|
|
use Thinktomorrow\Chief\Urls\Application\RevertUrlSlug; |
10
|
|
|
use Thinktomorrow\Chief\Urls\Application\SaveUrlSlugs; |
11
|
|
|
use Thinktomorrow\Chief\Urls\UrlRecord; |
12
|
|
|
|
13
|
|
|
class ChangeHomepage |
14
|
|
|
{ |
15
|
5 |
|
public function onSettingChanged(array $existingValues) |
16
|
|
|
{ |
17
|
5 |
|
$setting = Setting::findByKey(Setting::HOMEPAGE); |
18
|
|
|
|
19
|
5 |
|
$flatReferences = is_array($setting->value) |
|
|
|
|
20
|
5 |
|
? $setting->value |
21
|
5 |
|
: array_fill_keys(config('translatable.locales'), $setting->value); |
22
|
|
|
|
23
|
5 |
|
$this->assertNoEmptyValues($flatReferences); |
24
|
|
|
|
25
|
5 |
|
foreach ($flatReferences as $locale => $flatReferenceString) { |
26
|
|
|
|
27
|
|
|
// If existing value has changed, we'll need to revert this previous value |
28
|
5 |
|
if (isset($existingValues[$locale])) { |
29
|
1 |
|
if ($flatReferenceString != $existingValues[$locale]) { |
30
|
1 |
|
$flatReferenceInstance = FlatReferenceFactory::fromString(($existingValues[$locale])); |
31
|
1 |
|
(new RevertUrlSlug($flatReferenceInstance->instance()))->handle($locale); |
|
|
|
|
32
|
|
|
} |
33
|
|
|
} |
34
|
|
|
|
35
|
5 |
|
$flatReferenceInstance = FlatReferenceFactory::fromString($flatReferenceString); |
36
|
5 |
|
(new SaveUrlSlugs($flatReferenceInstance->instance()))->strict(false)->handle([$locale => '/']); |
|
|
|
|
37
|
|
|
} |
38
|
5 |
|
} |
39
|
|
|
|
40
|
2 |
|
public function onUrlChanged(UrlRecord $urlRecord) |
41
|
|
|
{ |
42
|
2 |
|
$model = Morphables::instance($urlRecord->model_type)->find($urlRecord->model_id); |
43
|
|
|
|
44
|
2 |
|
if (!$homepage = Setting::findByKey(Setting::HOMEPAGE)) { |
45
|
2 |
|
$homepage = Setting::create(['key' => Setting::HOMEPAGE, 'value' => []]); |
46
|
|
|
} |
47
|
|
|
|
48
|
2 |
|
$homepage->value = array_merge($homepage->value, [$urlRecord->locale => $model->flatReference()->get()]); |
|
|
|
|
49
|
2 |
|
$homepage->save(); |
50
|
2 |
|
} |
51
|
|
|
|
52
|
5 |
|
private function assertNoEmptyValues(array $flatReferences) |
53
|
|
|
{ |
54
|
5 |
|
foreach ($flatReferences as $locale => $flatReferenceString) { |
55
|
5 |
|
if (!$flatReferenceString) { |
56
|
5 |
|
throw new \InvalidArgumentException('Homepage setting value cannot be empty. Value for locale ' . $locale . ' is missing.'); |
57
|
|
|
} |
58
|
|
|
} |
59
|
5 |
|
} |
60
|
|
|
} |
61
|
|
|
|