1 | <?php |
||
2 | |||
3 | namespace TopviewDigital\UniqueJsonRule; |
||
4 | |||
5 | use DB; |
||
6 | |||
7 | class UniqueJsonValidator |
||
8 | { |
||
9 | /** |
||
10 | * Check if the translated value is unique in the database. |
||
11 | * |
||
12 | * @param string $attribute |
||
13 | * @param string $value |
||
14 | * @param array $parameters |
||
15 | * @param \Illuminate\Validation\Validator $validator |
||
16 | * |
||
17 | * @return bool |
||
18 | */ |
||
19 | public function validate($attribute, $value, array $parameters, $validator) |
||
0 ignored issues
–
show
|
|||
20 | { |
||
21 | list($name, $json_field) = array_map('trim', explode('.', $attribute)); |
||
22 | $parameters = array_map('trim', $parameters); |
||
23 | $parameters = array_map(function ($u) { |
||
24 | return strtolower($u) == 'null' || empty($u) ? null : $u; |
||
25 | }, $parameters); |
||
26 | list($table, $combined_fields, $except_value, $id_field) = array_pad($parameters, 4, null); |
||
27 | list($field, $json) = array_pad( |
||
28 | array_filter(explode('->', $combined_fields), 'strlen'), |
||
29 | 2, |
||
30 | null |
||
31 | ); |
||
32 | $field = $field ?: $name; |
||
33 | $json = $json ?? $json_field; |
||
34 | |||
35 | return $this->findJsonValue( |
||
36 | $value, |
||
37 | $json, |
||
38 | $table, |
||
39 | $field, |
||
40 | $except_value, |
||
41 | $id_field |
||
42 | ); |
||
43 | } |
||
44 | |||
45 | /** |
||
46 | * Check if a translation is unique. |
||
47 | * |
||
48 | * @param mixed $value |
||
49 | * @param string $locale |
||
50 | * @param string $table |
||
51 | * @param string $column |
||
52 | * @param mixed $ignoreValue |
||
53 | * @param string|null $ignoreColumn |
||
54 | * |
||
55 | * @return bool |
||
56 | */ |
||
57 | protected function findJsonValue( |
||
58 | $value, |
||
59 | $json, |
||
60 | $table, |
||
61 | $field, |
||
62 | $except_value, |
||
63 | $id_field |
||
64 | ) { |
||
65 | $except_value = $except_value ?? null; |
||
66 | $id_field = $id_field ?? 'id'; |
||
67 | $query = DB::table($table)->where("{$field}->{$json}", $value); |
||
68 | if ($except_value) { |
||
69 | $query = $query->where($id_field, '!=', $except_value); |
||
70 | } |
||
71 | |||
72 | return $query->count() === 0; |
||
73 | } |
||
74 | } |
||
75 |
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.