MirzaClient   A
last analyzed

Complexity

Total Complexity 15

Size/Duplication

Total Lines 153
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 15
eloc 73
dl 0
loc 153
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A getLanguages() 0 15 3
B isValidKey() 0 35 6
A __construct() 0 5 1
A detectLanguage() 0 16 3
A translate() 0 15 2
1
<?php
2
/**
3
 * Mirza Yandex Translator For Laravel
4
 * Mirza makes it easy to translate and manipulate text using the Yandex.Translate API.
5
 *
6
 * @version 1.0.0
7
 *
8
 * @author yak0d3 <[email protected]>
9
 * @license MIT
10
 *
11
 * @link https://github.com/yak0d3/Mirza_Yandex_Translator
12
 *
13
 * @copyright 2018 Yak0d3
14
 */
15
16
namespace yak0d3\mirza_yandex_translator;
17
18
use Exception;
19
20
class MirzaClient
21
{
22
    /**
23
     * Yandex Translation API Key Variable
24
     * Publish the configuration using `php artisan vendor:publish`,
25
     * then set the YANDEX_KEY environment variable (inside of the .env file) to your own Yandex.Translate API Key.
26
     *
27
     * @var string
28
     */
29
    private $key;
30
    /**
31
     * The list of supported languages variable.
32
     *
33
     * @var string
34
     */
35
    public $supportedLanguages;
36
37
    public function __construct($key)
38
    {
39
        $this->isValidKey($key);
40
        $this->key = $key;
41
        $this->supportedLanguages = $this->getLanguages(true);
42
    }
43
44
    /**
45
     * Validates if the API Key.
46
     *
47
     * @param string $key
48
     *
49
     * @throws Exception if the key is invalid
50
     *
51
     * @return boolean
52
     */
53
    private function isValidKey($key)
54
    {
55
        $ch = curl_init();
56
        curl_setopt($ch, CURLOPT_URL, 'https://translate.yandex.net/api/v1.5/tr.json/detect');
57
        curl_setopt($ch, CURLOPT_POST, true);
58
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
59
        curl_setopt($ch, CURLOPT_HEADER, true);
60
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
61
        curl_setopt($ch, CURLOPT_POSTFIELDS, 'text=YTranslator&key='.$key);
62
        $response = curl_exec($ch);
0 ignored issues
show
Unused Code introduced by
The assignment to $response is dead and can be removed.
Loading history...
63
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
64
        curl_close($ch);
65
        $goodKey = false;
66
        $errorMsg = false;
67
        switch ($httpcode) {
68
            case 200:
69
                $goodKey = true;
70
                $errorMsg = false;
71
                break;
72
            case 401:
73
                $errorMsg = 'Invalid API key.';
74
                break;
75
            case 402:
76
                $errorMsg = 'Blocked API key.';
77
                break;
78
            case 403:
79
                $errorMsg = 'Exceeded the daily limit on the amount of translated text.';
80
                break;
81
82
            default:
83
                $errorMsg = 'An unexpected error has occured while trying to verify the API Key.';
84
                break;
85
        }
86
        if (!$goodKey) {
87
            throw new \Exception($errorMsg);
0 ignored issues
show
Bug introduced by
It seems like $errorMsg can also be of type false; however, parameter $message of Exception::__construct() does only seem to accept string, 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

87
            throw new \Exception(/** @scrutinizer ignore-type */ $errorMsg);
Loading history...
88
        }
89
    }
90
91
    /**
92
     * Translates a given text to a given language.
93
     *
94
     * @param string $text
95
     * @param string $lang
96
     * @param string $format [plain|html]
97
     *
98
     * @throws Exception if the string could not be translated
99
     *
100
     * @return string
101
     */
102
    public function translate($text, $lang, $format = 'plain')
103
    {
104
        $ch = curl_init();
105
        curl_setopt($ch, CURLOPT_URL, 'https://translate.yandex.net/api/v1.5/tr.json/translate');
106
        curl_setopt($ch, CURLOPT_POST, true);
107
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
108
        curl_setopt($ch, CURLOPT_POSTFIELDS, 'text='.urlencode($text).'&lang='.$lang.'&format='.$format.'&key='.$this->key);
109
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
110
111
        $response = json_decode(curl_exec($ch));
112
        curl_close($ch);
113
        if (array_key_exists('text', $response)) {
114
            return $response->text[0];
115
        } else {
116
            throw new Exception('This text could not be translated: the string you entered or the language code are maybe invalid. Run getSupportedLanguages() to get the list of supported languages.');
117
        }
118
    }
119
120
    /**
121
     * Detects the language of a given text and returns the language code.
122
     *
123
     * @param string $text
124
     *
125
     * @throws Exception if it couldn't detect the language
126
     *
127
     * @return string
128
     */
129
    public function detectLanguage($text)
130
    {
131
        $ch = curl_init();
132
        curl_setopt($ch, CURLOPT_URL, 'https://translate.yandex.net/api/v1.5/tr.json/detect');
133
        curl_setopt($ch, CURLOPT_POST, true);
134
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
135
        curl_setopt($ch, CURLOPT_POSTFIELDS, 'text='.urlencode($text).'&key='.$this->key);
136
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
137
138
        $response = json_decode(curl_exec($ch));
139
        curl_close($ch);
140
141
        if (array_key_exists('lang', $response) && $response->lang != null) {
142
            return $response->lang;
143
        } else {
144
            throw new Exception('Could not get the language code: the entered string may not be valid.');
145
        }
146
    }
147
148
    /**
149
     * Returns the list of supported languages
150
     * If `$codes` is set to true, only language code will be returned.
151
     *
152
     * @param bool $codes
153
     *
154
     * @throws Exception if an unknown error occures while trying to fetch the list of supported languages
155
     *
156
     * @return string
157
     */
158
    public function getLanguages($codes = false)
159
    {
160
        $ch = curl_init();
161
        curl_setopt($ch, CURLOPT_URL, 'https://translate.yandex.net/api/v1.5/tr.json/getLangs');
162
        curl_setopt($ch, CURLOPT_POST, true);
163
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
164
        curl_setopt($ch, CURLOPT_POSTFIELDS, 'ui=en&key='.$this->key);
165
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
166
167
        $response = json_decode(curl_exec($ch));
168
        curl_close($ch);
169
        if (array_key_exists('langs', $response)) {
170
            return $codes ? array_keys(json_decode(json_encode($response->langs), true)) : $response->langs;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $codes ? array_ke...ue)) : $response->langs also could return the type array which is incompatible with the documented return type string.
Loading history...
171
        } else {
172
            throw new Exception('An unknown error has occured while trying to fetch the list of supported languages.');
173
        }
174
    }
175
}
176