Passed
Push — master ( 415021...b89d31 )
by Thomas
02:10
created

EasyNmtHelper::translate()   B

Complexity

Conditions 9
Paths 25

Size

Total Lines 47
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 29
nc 25
nop 3
dl 0
loc 47
rs 8.0555
c 0
b 0
f 0
1
<?php
2
3
namespace LeKoala\Multilingual;
4
5
/**
6
 * A simple helper to help translating strings
7
 * @link https://github.com/UKPLab/EasyNMT/tree/main/docker
8
 */
9
class EasyNmtHelper
10
{
11
    public static $baseUrl = 'http://localhost:24080/translate';
12
    public static $defaultLanguage = 'en';
13
14
    /**
15
     * Translate from provider
16
     *
17
     * @param string $sourceText
18
     * @param string $targetLang
19
     * @param string $sourceLang
20
     * @return string
21
     */
22
    public static function translate($sourceText, $targetLang = null, $sourceLang = null)
0 ignored issues
show
Unused Code introduced by
The parameter $sourceLang is not used and could be removed. ( Ignorable by Annotation )

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

22
    public static function translate($sourceText, $targetLang = null, /** @scrutinizer ignore-unused */ $sourceLang = null)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
23
    {
24
        $src_lang = self::$defaultLanguage;
25
        if ($targetLang == $src_lang) {
26
            return $sourceText;
27
        }
28
29
        $orgText = $sourceText;
30
        $containsVar = str_contains($sourceText, '{');
31
32
        // use en as intermediate language
33
        if ($targetLang != 'en') {
34
            $params2 = [
35
                'target_lang' => 'en',
36
                'text' => $sourceText
37
            ];
38
            $url = self::$baseUrl . '?' . http_build_query($params2);
39
            $result = @file_get_contents($url);
40
            if ($result) {
41
                $jsonData = json_decode($result, 1);
42
                if ($jsonData) {
43
                    $sourceText = $jsonData['translated'][0] ?? $sourceText;
44
                }
45
            }
46
            $src_lang = 'en';
47
        }
48
49
        $params = [
50
            'target_lang' => $targetLang,
51
            'text' => $sourceText,
52
            'source_lang' => $src_lang,
53
        ];
54
55
        $url = 'http://localhost:24080/translate?' . http_build_query($params);
56
        $result = @file_get_contents($url);
57
        if ($result) {
58
            $jsonData = json_decode($result, 1);
59
            if ($jsonData) {
60
                $sourceText = $jsonData['translated'][0] ?? $sourceText;
61
            }
62
        }
63
64
        if ($containsVar && !str_contains($sourceText, '{')) {
65
            return $orgText;
66
        }
67
68
        return $sourceText;
69
    }
70
}
71