Passed
Push — master ( ca5e33...a928bb )
by Robin
03:01
created

array_sort_value()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 19
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 6
c 1
b 0
f 0
nc 3
nop 2
dl 0
loc 19
rs 10
1
<?php
2
use Illuminate\Support\Str;
3
use TopviewDigital\TranslationHelper\Model\VocabTerm;
4
use TopviewDigital\TranslationHelper\Model\VocabCite;
5
use TopviewDigital\TranslationHelper\Service\Translation;
6
7
if (! function_exists('array_sort_value')) {
8
    function array_sort_value($array, $mode = SORT_LOCALE_STRING)
9
    {
10
        // SORT_REGULAR - compare items normally (don't change types)
11
        // SORT_NUMERIC - compare items numerically
12
        // SORT_STRING - compare items as strings
13
        // SORT_LOCALE_STRING - compare items as strings, based on the current locale.
14
        // It uses the locale, which can be changed using setlocale()
15
        // SORT_NATURAL - compare items as strings using "natural ordering" like natsort()
16
        // SORT_FLAG_CASE
17
18
        if (! is_array($array)) {
19
            $array = method_exists($array, 'toArray') ? $array->toArray() : (array) $array;
20
        }
21
        // \Locale::setDefault(str_replace('-', '_', \App::getLocale()));
22
        $keys = array_keys($array);
23
        $vals = array_values($array);
24
        array_multisort($vals, $mode, $keys);
25
26
        return array_combine($keys, $vals);
27
    }
28
}
29
30
if (!function_exists('is_json')) {
31
    function is_json($string)
32
    {
33
        if (!is_string($string)) {
34
            return false;
35
        }
36
        json_decode($string);
37
38
        return json_last_error() == JSON_ERROR_NONE;
39
    }
40
}
41
42
if (!function_exists('auto_trans_able')) {
43
    function auto_trans_able()
44
    {
45
        return config('trans-helper.translation.mode') == 'auto'
46
            && config('queue.default') != 'sync';
47
    }
48
}
49
if (!function_exists('localize')) {
50
    function localize($languages, string $failback = '')
51
    {
52
        if (is_array($languages) || is_json($languages)) {
53
            $languages = (!is_array($languages)) ? (array)json_decode($languages) : $languages;
54
            $locales = array_keys($languages);
55
            $system = \App::getLocale();
56
            $default = config('app.locale');
57
58
            $locale = in_array($system, $locales) ? $system : (in_array($default, $locales) ? $default : null);
59
60
            return  $locale ? $languages[$locale] : $failback;
61
        }
62
        if (is_string($languages) && empty($failback)) {
63
            $tracer = (new Exception())->getTrace();
64
            $cite = [];
65
            $cite['file'] = preg_replace('/(\.php)(.+)$/', '${1}', $tracer[0]['file']);
66
            $cite['line'] = $tracer[0]['line'];
67
            array_shift($tracer);
68
            $cite['function'] = $tracer[0]['function'] ?? '';
69
            $cite['class'] = $tracer[0]['class'] ?? '';
70
            $vocab = [];
71
            $vocab['namespace'] = preg_replace(
72
                '/(^' . addcslashes(base_path(), '\/') . ')|(\.php$)/',
73
                '',
74
                $cite['file']
75
            );
76
            $vocab['term'] = $languages;
77
            $vocab = VocabTerm::firstOrCreate($vocab);
78
            if (!$vocab->transaltion) {
79
                $vocab->translation = [config('app.locale') => $vocab['term']];
80
                $vocab->save();
81
                if (auto_trans_able()) {
82
                    dispatch(new Translation($vocab));
83
                }
84
            }
85
            if (auto_trans_able() && !in_array(app()->getLocale(), array_keys($vocab->translation))) {
0 ignored issues
show
introduced by
The method getLocale() does not exist on Illuminate\Container\Container. Are you sure you never get this type here, but always one of the subclasses? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

85
            if (auto_trans_able() && !in_array(app()->/** @scrutinizer ignore-call */ getLocale(), array_keys($vocab->translation))) {
Loading history...
86
                dispatch(new Translation($vocab, [app()->getLocale()]));
87
            }
88
            $cite['file'] = preg_replace(
89
                '/^' . addcslashes(base_path(), '\/') . '/',
90
                '',
91
                $cite['file']
92
            );
93
            $cite = VocabCite::firstOrCreate($cite);
94
            $vocab->cites()->sync([$cite->id], false);
95
            if (!$cite->code) {
96
                $lines = explode("\n", file_get_contents(base_path() . $cite->file));
97
                $cite->code = $lines[$cite->line - 1];
98
                if (substr($cite->file, -10) != '.blade.php') {
99
                    for ($start = $cite->line - 2; $start > -1; $start--) {
100
                        $char = substr(rtrim($lines[$start]), -1);
101
                        if ($char == ';' || $char == '}' || $char == '{') {
102
                            $start++;
103
                            break;
104
                        }
105
                    }
106
                    $count = count($lines);
107
                    for ($end = $cite->line - 1; $end < $count; $end++) {
108
                        $char = substr(rtrim($lines[$end]), -1);
109
                        if ($char == ';') {
110
                            break;
111
                        }
112
                    }
113
                    $code = array_filter(array_slice($lines, $start, $end - $start + 1, true), 'trim');
114
                    $max = strlen($end);
115
                    $cite->code = implode("\n", array_map(function ($u, $v) use ($max) {
116
                        return sprintf("%{$max}d    %s", $u + 1, rtrim($v));
117
                    }, array_keys($code), $code));
118
                    $cite->save();
119
                }
120
            }
121
122
            return localize($vocab->translation, $vocab->term);
123
        }
124
125
        return $failback;
126
    }
127
}
128
129
if (!function_exists('sweep')) {
130
    function sweep()
131
    {
132
        array_map(
133
            function ($u) {
134
                $u->sweep();
135
            },
136
            array_merge(
137
                VocabCite::get()->all(),
138
                VocabTerm::get()->all()
139
            )
140
        );
141
    }
142
}
143
144
if (!function_exists('translate')) {
145
    function translate($locales = [])
146
    {
147
        dispatch(new Translation(null, $locales));
148
    }
149
}
150
if (!function_exists('slugify')) {
151
    function slugify($text)
152
    {
153
        // replace non letter or digits by -
154
        $text = preg_replace('~[^\pL\d]+~u', '-', $text);
155
156
        // transliterate
157
        $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
158
159
        // remove unwanted characters
160
        $text = preg_replace('~[^-\w]+~', '', $text);
161
162
        // trim
163
        $text = trim($text, '-');
164
165
        // remove duplicated - symbols
166
        $text = preg_replace('~-+~', '-', $text);
167
168
        // lowercase
169
        $text = strtolower($text);
170
171
        if (empty($text)) {
172
            return 'n-a';
173
        }
174
175
        return $text;
176
    }
177
}
178
179
if (!function_exists('unique_slugs')) {
180
    function unique_slugs($slugs)
181
    {
182
        $keys = array_keys($slugs);
183
        $slugs = array_values($slugs);
184
        $slugs = array_map(function ($k, $v) use ($slugs) {
185
            if ($k > 0 && in_array($v, array_slice($slugs, 0, $k - 1))) {
186
                $v .= '-' . uniqid();
187
            }
188
            return $v;
189
        }, array_keys($slugs), $slugs);
190
        return array_combine($keys, $slugs);
191
    }
192
}
193
194
if (!function_exists('lang_file_name')) {
195
    function lang_file_name($path, $locale, $namespace)
196
    {
197
        $lang_file = str_replace('/', '.', strtolower(ltrim(Str::snake($namespace), '/')));
198
        $lang_file = str_replace('//', '/', implode('/', [$path, $locale, $lang_file]));
199
        $lang_file = str_replace('._', '.', $lang_file) . '.php';
200
        return $lang_file;
201
    }
202
}
203
204
if (!function_exists('export')) {
205
    function export($path = null)
206
    {
207
        $path = $path ?? config('trans-helper.export.path');
208
        $locales = VocabTerm::locales();
209
        $namespaces = VocabTerm::namespaces();
210
        foreach ($namespaces as $namespace) {
211
            foreach ($locales as $locale) {
212
                $lang_file = lang_file_name($path, $locale, $namespace);
213
                $lang_dir = dirname($lang_file);
214
                if (file_exists($lang_dir) && !is_dir($lang_dir)) {
215
                    unlink($lang_dir);
216
                }
217
                if (!file_exists($lang_dir)) {
218
                    mkdir($lang_dir, 0777, true);
219
                }
220
221
                $slugs = [];
222
                $terms = [];
223
                foreach (VocabTerm::where('namespace', $namespace)->get() as $term) {
224
                    $slugs[] = $term->slug;
225
                    $terms[] = $term->translation[$locale] ?? $term->translation[config('app.locale')];
226
                }
227
                $slugs = unique_slugs($slugs);
228
                $max = intdiv(max(array_map('strlen', $slugs)) + 3, 4) * 4;
229
                $lines = array_map(function ($u, $v) use ($max) {
230
                    $u = "'{$u}'";
231
                    return sprintf("    %-{$max}s => '%s',", $u, $v);
232
                }, $slugs, $terms);
233
                $lines[] = "];\n";
234
                array_unshift($lines, "\nreturn [");
235
                array_unshift($lines, '<?php');
236
                file_put_contents($lang_file, implode("\n", $lines));
237
            }
238
        }
239
    }
240
}
241