1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace App\Foundation\Models\Updaters; |
4
|
|
|
|
5
|
|
|
use Illuminate\Support\Collection; |
6
|
|
|
use Spatie\Regex\MatchResult; |
7
|
|
|
use Spatie\Regex\Regex; |
8
|
|
|
|
9
|
|
|
trait UpdatesSeoValues |
10
|
|
|
{ |
11
|
|
|
protected function updateSeoValues() |
12
|
|
|
{ |
13
|
|
|
collect($this->request->all()) |
|
|
|
|
14
|
|
|
->filter(function ($value, $fieldName) { |
15
|
|
|
// Filter out everything that starts with 'translated_<locale>_seo_' |
16
|
|
|
return Regex::match('/^translated_([a-z][a-z])_seo_/', $fieldName)->hasMatch(); |
17
|
|
|
}) |
18
|
|
|
->map(function ($value, $fieldName) { |
19
|
|
|
|
20
|
|
|
// Replace 'translated_<locale>_seo_<attribute>' with '<locale>_<attribute>' |
21
|
|
|
$localeAndAttribute = Regex::replace('/translated_([a-z][a-z])_seo_/', function (MatchResult $matchResult) { |
22
|
|
|
return $matchResult->group(1) . '_'; |
23
|
|
|
}, $fieldName)->result(); |
24
|
|
|
|
25
|
|
|
$localeAndAttribute = explode('_', $localeAndAttribute, 2); |
26
|
|
|
|
27
|
|
|
return [ |
28
|
|
|
'locale' => $localeAndAttribute[0], |
29
|
|
|
'attribute' => $localeAndAttribute[1], |
30
|
|
|
'value' => $value, |
31
|
|
|
]; |
32
|
|
|
}) |
33
|
|
|
->groupBy('locale') |
34
|
|
|
->map(function (Collection $valuesInLocale) { |
35
|
|
|
return $valuesInLocale->mapToAssoc(function ($values) { |
36
|
|
|
return [$values['attribute'], $values['value']]; |
37
|
|
|
}); |
38
|
|
|
}) |
39
|
|
|
->each(function ($values, $locale) { |
40
|
|
|
$this->model->setTranslation('seo_values', $locale, $values); |
|
|
|
|
41
|
|
|
}); |
42
|
|
|
} |
43
|
|
|
} |
44
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: