-
-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathUniqueTranslationValidator.php
390 lines (337 loc) · 10.5 KB
/
UniqueTranslationValidator.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
<?php
namespace CodeZero\UniqueTranslation;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Support\Arr;
class UniqueTranslationValidator
{
/**
* Check if the translated value is unique in the database.
*
* @param string $attribute
* @param string $value
* @param array $parameters
* @param \Illuminate\Validation\Validator $validator
*
* @return bool
*/
public function validate($attribute, $value, $parameters, $validator)
{
list ($name, $locale) = $this->isNovaTranslation($attribute)
? $this->getNovaAttributeNameAndLocale($attribute)
: (
$this->isFilamentTranslation($attribute)
? $this->getFilamentAttributeNameAndLocale($attribute, $validator)
: $this->getArrayAttributeNameAndLocale($attribute)
);
if ($this->isUnique($value, $name, $locale, $parameters)) {
return true;
}
$this->setMissingErrorMessages($validator, $name, $locale);
return false;
}
/**
* Set any missing (custom) error messages for our validation rule.
*
* @param \Illuminate\Validation\Validator $validator
* @param string $name
* @param string $locale
*
* @return void
*/
protected function setMissingErrorMessages($validator, $name, $locale)
{
$rule = 'unique_translation';
$keys = [
"{$name}.{$rule}",
"{$name}.*.{$rule}",
"{$name}.{$locale}.{$rule}",
"translations_{$name}_{$locale}.{$rule}",
];
foreach ($keys as $key) {
if ( ! array_key_exists($key, $validator->customMessages)) {
$validator->customMessages[$key] = trans('validation.unique');
}
}
}
/**
* Check if the attribute is a Nova translation field name.
*
* @param string $attribute
*
* @return bool
*/
protected function isNovaTranslation($attribute)
{
return strpos($attribute, '.') === false && strpos($attribute, 'translations_') === 0;
}
/**
* Get the attribute name and locale of a Filament translation field.
*
* @param string $attribute
*
* @return array
*/
protected function getNovaAttributeNameAndLocale($attribute)
{
$attribute = str_replace('translations_', '', $attribute);
return $this->getAttributeNameAndLocale($attribute, '_');
}
/**
* Check if the attribute is a Filament translation field name.
*
* @param string $attribute
*
* @return bool
*/
protected function isFilamentTranslation($attribute)
{
return Str::startsWith($attribute, ['data.', 'mountedTableActionsData.']);
}
/**
* Get the attribute name and locale of a Filament translation field.
*
* @param string $attribute
*
* @return array
*/
protected function getFilamentAttributeNameAndLocale($attribute, $validator)
{
$attribute = preg_replace('~^(?:data|mountedTableActionsData\.\d+)\.~', '', $attribute);
$dataValidator = $validator->getData();
@list($name, $locale) = @explode('.', $attribute);
if ($locale === null && Arr::exists($dataValidator, 'activeLocale')) {
$locale = $dataValidator['activeLocale'];
}
return [$name, $locale];
}
/**
* Get the attribute name and locale of an array field.
*
* @param string $attribute
*
* @return array
*/
protected function getArrayAttributeNameAndLocale($attribute)
{
return $this->getAttributeNameAndLocale($attribute, '.');
}
/**
* Get the attribute name and locale.
*
* @param string $attribute
* @param string $delimiter
*
* @return array
*/
protected function getAttributeNameAndLocale($attribute, $delimiter)
{
$locale = $this->getAttributeLocale($attribute, $delimiter);
$name = $this->getAttributeName($attribute, $locale, $delimiter);
return [$name, $locale ?: App::getLocale()];
}
/**
* Get the locale from the attribute name.
*
* @param string $attribute
* @param string $delimiter
*
* @return string|null
*/
protected function getAttributeLocale($attribute, $delimiter)
{
$pos = strrpos($attribute, $delimiter);
return $pos > 0 ? substr($attribute, $pos + 1) : null;
}
/**
* Get the attribute name without the locale.
*
* @param string $attribute
* @param string|null $locale
* @param string $delimiter
*
* @return string
*/
protected function getAttributeName($attribute, $locale, $delimiter)
{
return $locale ? str_replace("{$delimiter}{$locale}", '', $attribute) : $attribute;
}
/**
* Get the database connection and table name.
*
* @param array $parameters
*
* @return array
*/
protected function getConnectionAndTable($parameters)
{
$parts = explode('.', $this->getParameter($parameters, 0));
$connection = isset($parts[1])
? $parts[0]
: Config::get('database.default');
$table = $parts[1] ?? $parts[0];
return [$connection, $table];
}
/**
* Get the parameter value at the given index.
*
* @param array $parameters
* @param int $index
*
* @return string|null
*/
protected function getParameter($parameters, $index)
{
return $this->convertNullValue($parameters[$index] ?? null);
}
/**
* Convert any 'NULL' string value to null.
*
* @param string $value
*
* @return string|null
*/
protected function convertNullValue($value)
{
return strtoupper($value) === 'NULL' ? null : $value;
}
/**
* Check if a translation is unique.
*
* @param mixed $value
* @param string $name
* @param string $locale
* @param array $parameters
*
* @return bool
*/
protected function isUnique($value, $name, $locale, $parameters)
{
list ($connection, $table) = $this->getConnectionAndTable($parameters);
$column = $this->getParameter($parameters, 1) ?? $name;
$ignoreValue = $this->getParameter($parameters, 2);
$ignoreColumn = $this->getParameter($parameters, 3);
$query = $this->findTranslation($connection, $table, $column, $locale, $value);
$query = $this->ignore($query, $ignoreColumn, $ignoreValue);
$query = $this->addConditions($query, $this->getUniqueExtra($parameters));
$isUnique = $query->count() === 0;
return $isUnique;
}
/**
* Find the given translated value in the database.
*
* @param string $connection
* @param string $table
* @param string $column
* @param string $locale
* @param mixed $value
*
* @return \Illuminate\Database\Query\Builder
*/
protected function findTranslation($connection, $table, $column, $locale, $value)
{
// Properly escape backslashes to work with LIKE queries...
// See: https://stackoverflow.com/questions/14926386/how-to-search-for-slash-in-mysql-and-why-escaping-not-required-for-wher
$escaped = DB::getDriverName() === 'sqlite' ? '\\\\' : '\\\\\\\\';
$value = str_replace('\\', $escaped, $value);
// Support PostgreSQL case insensitive queries with ILIKE
$operator = DB::getDriverName() === 'pgsql' ? 'ILIKE' : 'LIKE';
return DB::connection($connection)->table($table)
->where(function ($query) use ($column, $operator, $locale, $value) {
$query->where($column, $operator, "%\"{$locale}\": \"{$value}\"%")
->orWhere($column, $operator, "%\"{$locale}\":\"{$value}\"%");
});
}
/**
* Ignore the column with the given value.
*
* @param \Illuminate\Database\Query\Builder $query
* @param string|null $column
* @param mixed $value
*
* @return \Illuminate\Database\Query\Builder
*/
protected function ignore($query, $column = null, $value = null)
{
if ($value !== null && $column === null) {
$column = 'id';
}
if ($column !== null) {
$query = $query->where($column, '!=', $value);
}
return $query;
}
/**
* Get the extra conditions for a unique rule.
* Taken From: \Illuminate\Validation\Concerns\ValidatesAttributes
*
* @param array $parameters
*
* @return array
*/
protected function getUniqueExtra($parameters)
{
if (isset($parameters[4])) {
return $this->getExtraConditions(array_slice($parameters, 4));
}
return [];
}
/**
* Get the extra conditions for a unique / exists rule.
* Taken from: \Illuminate\Validation\Concerns\ValidatesAttributes
*
* @param array $segments
*
* @return array
*/
protected function getExtraConditions(array $segments)
{
$extra = [];
$count = count($segments);
for ($i = 0; $i < $count; $i += 2) {
$extra[$segments[$i]] = $segments[$i + 1];
}
return $extra;
}
/**
* Add the given conditions to the query.
* Adapted from: \Illuminate\Validation\DatabasePresenceVerifier
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $conditions
*
* @return \Illuminate\Database\Query\Builder
*/
protected function addConditions($query, $conditions)
{
foreach ($conditions as $key => $value) {
$this->addWhere($query, $key, $value);
}
return $query;
}
/**
* Add a "where" clause to the given query.
* Taken from: \Illuminate\Validation\DatabasePresenceVerifier
*
* @param \Illuminate\Database\Query\Builder $query
* @param string $key
* @param string $extraValue
*
* @return \Illuminate\Database\Query\Builder
*/
protected function addWhere($query, $key, $extraValue)
{
if ($extraValue === 'NULL') {
return $query->whereNull($key);
}
if ($extraValue === 'NOT_NULL') {
return $query->whereNotNull($key);
}
$isNegative = Str::startsWith($extraValue, '!');
$operator = $isNegative ? '!=' : '=';
$value = $isNegative ? mb_substr($extraValue, 1) : $extraValue;
return $query->where($key, $operator, $value);
}
}