slugify()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 25
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 9
nc 2
nop 1
dl 0
loc 25
rs 9.9666
c 1
b 0
f 0
1
<?php
2
3
use Illuminate\Support\Str;
4
use TopviewDigital\TranslationHelper\Model\VocabCite;
5
use TopviewDigital\TranslationHelper\Model\VocabTerm;
6
use TopviewDigital\TranslationHelper\Service\Translation;
7
use TopviewDigital\TranslationHelper\Service\AsyncBroker;
8
use TopviewDigital\TranslationHelper\Service\CiteUpdater;
9
10
if (!function_exists('array_sort_value')) {
11
    function array_sort_value($array, $mode = SORT_LOCALE_STRING)
12
    {
13
        // SORT_REGULAR - compare items normally (don't change types)
14
        // SORT_NUMERIC - compare items numerically
15
        // SORT_STRING - compare items as strings
16
        // SORT_LOCALE_STRING - compare items as strings, based on the current locale.
17
        // It uses the locale, which can be changed using setlocale()
18
        // SORT_NATURAL - compare items as strings using "natural ordering" like natsort()
19
        // SORT_FLAG_CASE
20
21
        if (!is_array($array)) {
22
            $array = method_exists($array, 'toArray') ? $array->toArray() : (array)$array;
23
        }
24
        // \Locale::setDefault(str_replace('-', '_', \App::getLocale()));
25
        $keys = array_keys($array);
26
        $vals = array_values($array);
27
        array_multisort($vals, $mode, $keys);
28
29
        return array_combine($keys, $vals);
30
    }
31
}
32
33
if (!function_exists('is_json')) {
34
    function is_json($string)
35
    {
36
        if (!is_string($string)) {
37
            return false;
38
        }
39
        json_decode($string);
40
41
        return json_last_error() == JSON_ERROR_NONE;
42
    }
43
}
44
45
if (!function_exists('auto_trans_able')) {
46
    function auto_trans_able()
47
    {
48
        return config('trans-helper.translation.mode') == 'auto'
49
            && config('queue.default') != 'sync';
50
    }
51
}
52
53
if (!function_exists('prepare_vocab')) {
54
    function prepare_vocab($term, $tracer)
55
    {
56
        $vocab = [];
57
        $vocab['namespace'] = preg_replace(
58
            '/(^' . addcslashes(base_path(), '\/') . ')|(\.php$)/',
59
            '',
60
            preg_replace('/(\.php)(.+)$/', '${1}', $tracer[0]['file'])
61
        );
62
        $vocab['term'] = $term;
63
        $vocab = VocabTerm::firstOrCreate($vocab);
64
        $vocab->refresh();
65
        $vocab->translation = empty($vocab->translation) ? [] : $vocab->translation;
66
        $vocab->save();
67
        if (auto_trans_able() && !array_key_exists(app()->getLocale(), $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

67
        if (auto_trans_able() && !array_key_exists(app()->/** @scrutinizer ignore-call */ getLocale(), $vocab->translation)) {
Loading history...
68
            AsyncBroker::dispatch(new Translation($vocab))->onQueue('translation');
69
        }
70
        return $vocab;
71
    }
72
}
73
if (!function_exists('localize')) {
74
    function localize($languages, string $failback = '')
75
    {
76
        if (is_array($languages) || is_json($languages)) {
77
            $languages = (!is_array($languages)) ? (array)json_decode($languages) : $languages;
78
            $locales = array_keys($languages);
79
            $system = app()->getLocale();
80
            $default = config('app.locale');
81
82
            $locale = in_array($system, $locales) ? $system : (in_array($default, $locales) ? $default : null);
83
84
            return  $locale ? $languages[$locale] : $failback;
85
        }
86
        if (is_string($languages) && empty($failback)) {
87
            $tracer = (new Exception())->getTrace();
88
            $vocab = prepare_vocab($languages, $tracer);
89
            if (config('trans-helper.cite.enable')) {
90
                $updater = new CiteUpdater($vocab, $tracer);
91
                if (config('trans-helper.cite.async')) {
92
                    AsyncBroker::dispatch($updater)->onqueue('cite');
93
                } else {
94
                    $updater->handle();
95
                }
96
            }
97
98
            return localize($vocab->translation, $vocab->term);
99
        }
100
101
        return $failback;
102
    }
103
}
104
105
if (!function_exists('sweep')) {
106
    function sweep()
107
    {
108
        array_map(
109
            function ($u) {
110
                $u->sweep();
111
            },
112
            array_merge(
113
                VocabCite::get()->all(),
114
                VocabTerm::get()->all()
115
            )
116
        );
117
    }
118
}
119
120
if (!function_exists('translate')) {
121
    function translate($locales = [])
122
    {
123
        dispatch(new Translation(null, $locales));
0 ignored issues
show
Unused Code introduced by
The call to TopviewDigital\Translati...nslation::__construct() has too many arguments starting with $locales. ( Ignorable by Annotation )

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

123
        dispatch(/** @scrutinizer ignore-call */ new Translation(null, $locales));

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
124
    }
125
}
126
if (!function_exists('slugify')) {
127
    function slugify($text)
128
    {
129
        // replace non letter or digits by -
130
        $text = preg_replace('~[^\pL\d]+~u', '-', $text);
131
132
        // transliterate
133
        $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
134
135
        // remove unwanted characters
136
        $text = preg_replace('~[^-\w]+~', '', $text);
137
138
        // trim
139
        $text = trim($text, '-');
140
141
        // remove duplicated - symbols
142
        $text = preg_replace('~-+~', '-', $text);
143
144
        // lowercase
145
        $text = strtolower($text);
146
147
        if (empty($text)) {
148
            return 'n-a';
149
        }
150
151
        return $text;
152
    }
153
}
154
155
if (!function_exists('unique_slugs')) {
156
    function unique_slugs($slugs)
157
    {
158
        $keys = array_keys($slugs);
159
        $slugs = array_values($slugs);
160
        $slugs = array_map(function ($k, $v) use ($slugs) {
161
            if ($k > 0 && in_array($v, array_slice($slugs, 0, $k - 1))) {
162
                $v .= '-' . uniqid();
163
            }
164
165
            return $v;
166
        }, array_keys($slugs), $slugs);
167
168
        return array_combine($keys, $slugs);
169
    }
170
}
171
172
if (!function_exists('lang_file_name')) {
173
    function lang_file_name($path, $locale, $namespace)
174
    {
175
        $lang_file = str_replace('/', '.', strtolower(ltrim(Str::snake($namespace), '/')));
176
        $lang_file = str_replace('//', '/', implode('/', [$path, $locale, $lang_file]));
177
        $lang_file = str_replace('._', '.', $lang_file) . '.php';
178
179
        return $lang_file;
180
    }
181
}
182
183
if (!function_exists('export')) {
184
    function export($path = null)
185
    {
186
        $path = $path ?? config('trans-helper.export.path');
187
        $locales = VocabTerm::locales();
188
        $namespaces = VocabTerm::namespaces();
189
        foreach ($namespaces as $namespace) {
190
            foreach ($locales as $locale) {
191
                $lang_file = lang_file_name($path, $locale, $namespace);
192
                $lang_dir = dirname($lang_file);
193
                if (file_exists($lang_dir) && !is_dir($lang_dir)) {
194
                    unlink($lang_dir);
195
                }
196
                if (!file_exists($lang_dir)) {
197
                    mkdir($lang_dir, 0777, true);
198
                }
199
200
                $slugs = [];
201
                $terms = [];
202
                foreach (VocabTerm::where('namespace', $namespace)->get() as $term) {
203
                    $slugs[] = $term->slug;
204
                    $terms[] = $term->translation[$locale] ?? $term->translation[config('app.locale')];
205
                }
206
                $slugs = unique_slugs($slugs);
207
                $max = intdiv(max(array_map('strlen', $slugs)) + 3, 4) * 4;
0 ignored issues
show
Bug introduced by
It seems like $slugs can also be of type false; however, parameter $arr1 of array_map() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

207
                $max = intdiv(max(array_map('strlen', /** @scrutinizer ignore-type */ $slugs)) + 3, 4) * 4;
Loading history...
208
                $lines = array_map(function ($u, $v) use ($max) {
209
                    $u = "'{$u}'";
210
211
                    return sprintf("    %-{$max}s => '%s',", $u, $v);
212
                }, $slugs, $terms);
213
                $lines[] = "];\n";
214
                array_unshift($lines, "\nreturn [");
215
                array_unshift($lines, '<?php');
216
                file_put_contents($lang_file, implode("\n", $lines));
217
            }
218
        }
219
    }
220
}
221