YandexTranslateApi   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 156
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 156
rs 10
c 0
b 0
f 0
wmc 9

6 Methods

Rating   Name   Duplication   Size   Complexity  
A prepareTranslateResponse() 0 3 1
A createTranslateBulkContext() 0 16 1
A createTranslateContext() 0 15 1
A processTranslateResponse() 0 19 3
A prepareTranslateBulkResponse() 0 3 1
A processApiResponseContextErrors() 0 10 2
1
<?php
2
3
namespace GinoPane\PHPolyglot\API\Implementation\Translate\Yandex;
4
5
use GinoPane\NanoRest\Request\RequestContext;
6
use GinoPane\NanoRest\Response\ResponseContextAbstract;
7
use GinoPane\PHPolyglot\Supplemental\Language\Language;
8
use GinoPane\NanoRest\Exceptions\RequestContextException;
9
use GinoPane\PHPolyglot\Exception\InvalidResponseContent;
10
use GinoPane\PHPolyglot\Exception\BadResponseContextException;
11
use GinoPane\PHPolyglot\API\Supplemental\Yandex\YandexApiTrait;
12
use GinoPane\PHPolyglot\API\Response\Translate\TranslateResponse;
13
use GinoPane\PHPolyglot\API\Implementation\Translate\TranslateApiAbstract;
14
15
/**
16
 * Class YandexTranslateApi
17
 *
18
 * Yandex Translate API implementation
19
 *
20
 * API version 1.5
21
 *
22
 * @link   https://tech.yandex.com/translate/doc/dg/concepts/api-overview-docpage/
23
 * @link   https://tech.yandex.com/keys/?service=trnsl
24
 *
25
 * @author Sergey <Gino Pane> Karavay
26
 */
27
class YandexTranslateApi extends TranslateApiAbstract
28
{
29
    /**
30
     * API constant string for undetected language
31
     */
32
    protected const LANGUAGE_UNDETECTED = 'no';
33
34
    /**
35
     * URL path for translate action
36
     */
37
    const TRANSLATE_API_PATH = 'translate';
38
39
    /**
40
     * Main API endpoint
41
     *
42
     * @var string
43
     */
44
    protected $apiEndpoint = 'https://translate.yandex.net/api/v1.5/tr.json';
45
46
    /**
47
     * Mapping of properties to environment variables which must supply these properties
48
     *
49
     * @var array
50
     */
51
    protected $envProperties = [
52
        'apiKey' => 'YANDEX_TRANSLATE_API_KEY'
53
    ];
54
55
    use YandexApiTrait;
56
57
    /**
58
     * Create request context for translate request
59
     *
60
     * @param string   $text
61
     * @param Language $languageTo
62
     * @param Language $languageFrom
63
     *
64
     * @throws RequestContextException
65
     *
66
     * @return RequestContext
67
     */
68
    protected function createTranslateContext(
69
        string $text,
70
        Language $languageTo,
71
        Language $languageFrom
72
    ): RequestContext {
73
        $requestContext = (new RequestContext(sprintf("%s/%s", $this->apiEndpoint, self::TRANSLATE_API_PATH)))
74
            ->setRequestParameters(
75
                [
76
                    'lang' => $this->getLanguageString($languageTo, $languageFrom)
77
                ] + $this->getAuthData()
78
            )
79
            ->setData(['text' => $text])
80
            ->setMethod(RequestContext::METHOD_POST);
81
82
        return $this->fillGeneralRequestSettings($requestContext);
83
    }
84
85
    /**
86
     * Process response of translate request and prepare valid response
87
     *
88
     * @param ResponseContextAbstract $context
89
     *
90
     * @return TranslateResponse
91
     */
92
    protected function prepareTranslateResponse(ResponseContextAbstract $context): TranslateResponse
93
    {
94
        return $this->processTranslateResponse($context);
95
    }
96
97
    /**
98
     * Create request context for bulk translate request
99
     *
100
     * @param array    $texts
101
     * @param Language $languageTo
102
     * @param Language $languageFrom
103
     *
104
     * @throws RequestContextException
105
     *
106
     * @return RequestContext
107
     */
108
    protected function createTranslateBulkContext(
109
        array $texts,
110
        Language $languageTo,
111
        Language $languageFrom
112
    ): RequestContext {
113
        $requestContext = (new RequestContext(sprintf("%s/%s", $this->apiEndpoint, self::TRANSLATE_API_PATH)))
114
            ->setRequestParameters(
115
                [
116
                    'lang' => $this->getLanguageString($languageTo, $languageFrom)
117
                ] + $this->getAuthData()
118
            )
119
            ->setData(['text' => $texts])
120
            ->setMethod(RequestContext::METHOD_POST)
121
            ->setEncodeArraysUsingDuplication(true);
122
123
        return $this->fillGeneralRequestSettings($requestContext);
124
    }
125
126
    /**
127
     * Process response of bulk translate request and prepare valid response
128
     *
129
     * @param ResponseContextAbstract $context
130
     *
131
     * @return TranslateResponse
132
     */
133
    protected function prepareTranslateBulkResponse(ResponseContextAbstract $context): TranslateResponse
134
    {
135
        return $this->processTranslateResponse($context);
136
    }
137
138
    /**
139
     * Filters ResponseContext from common HTTP errors
140
     *
141
     * @param ResponseContextAbstract $responseContext
142
     *
143
     * @throws BadResponseContextException
144
     * @throws InvalidResponseContent
145
     */
146
    protected function processApiResponseContextErrors(ResponseContextAbstract $responseContext): void
147
    {
148
        $responseArray = $responseContext->getArray();
149
150
        $this->filterYandexSpecificErrors($responseArray);
151
152
        parent::processApiResponseContextErrors($responseContext);
153
154
        if (empty($responseArray['text'])) {
155
            throw new InvalidResponseContent(sprintf('There is no required field "%s" in response', 'text'));
156
        }
157
    }
158
159
    /**
160
     * @param ResponseContextAbstract $context
161
     *
162
     * @return TranslateResponse
163
     */
164
    private function processTranslateResponse(ResponseContextAbstract $context): TranslateResponse
165
    {
166
        $responseArray = $context->getArray();
167
168
        $response = new TranslateResponse();
169
170
        $response->setTranslations((array)$responseArray['text']);
171
172
        if (isset($responseArray['lang'])) {
173
            list($fromLanguage, $toLanguage) = explode("-", $responseArray['lang']);
174
175
            if ($fromLanguage !== self::LANGUAGE_UNDETECTED) {
176
                $response->setLanguageFrom($fromLanguage);
177
            }
178
179
            $response->setLanguageTo($toLanguage);
180
        }
181
182
        return $response;
183
    }
184
}
185