LanguageToolApiClient   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 26
c 2
b 0
f 0
dl 0
loc 73
rs 10
wmc 6

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A spellCheck() 0 14 2
A getSupportedLanguages() 0 9 1
A requestAPI() 0 16 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace PhpSpellcheck\Spellchecker\LanguageTool;
6
7
/**
8
 * @TODO refactor by using PSR HTTP Client
9
 */
10
class LanguageToolApiClient
11
{
12
    /**
13
     * @var string
14 2
     */
15
    private $baseUrl;
16 2
17 2
    public function __construct(string $baseUrl)
18
    {
19 1
        $this->baseUrl = $baseUrl;
20
    }
21 1
22 1
    /**
23 1
     * @param array<string> $languages
24
     * @param array<mixed> $options
25 1
     *
26 1
     * @return array<string, mixed>
27 1
     */
28 1
    public function spellCheck(string $text, array $languages, array $options): array
29 1
    {
30
        $options['text'] = $text;
31
        $options['language'] = array_shift($languages);
32
33 1
        if (!empty($languages)) {
34
            $options['altLanguages'] = implode(',', $languages);
35 1
        }
36 1
37 1
        return $this->requestAPI(
38 1
            '/v2/check',
39 1
            'POST',
40
            'Content-type: application/x-www-form-urlencoded; Accept: application/json',
41 1
            $options
42
        );
43
    }
44
45
    /**
46
     * @return array<string>
47
     */
48 2
    public function getSupportedLanguages(): array
49
    {
50
        return array_column(
51 2
            $this->requestAPI(
52 2
                '/v2/languages',
53
                'GET',
54
                'Accept: application/json'
55 2
            ),
56 1
            'longCode'
57
        );
58
    }
59 2
60
    /**
61 2
     * @param array<mixed> $queryParams
62 2
     *
63 2
     * @throws \RuntimeException
64
     *
65 2
     * @return array<mixed>
66
     */
67
    public function requestAPI(string $endpoint, string $method, string $header, array $queryParams = []): array
68
    {
69 2
        $httpData = [
70
            'method' => $method,
71 2
            'header' => $header,
72
        ];
73
74
        if (!empty($queryParams)) {
75 2
            $httpData['content'] = http_build_query($queryParams);
76
        }
77
78
        $content = \Safe\file_get_contents($this->baseUrl . $endpoint, false, stream_context_create(['http' => $httpData]));
79
        /** @var array<mixed> $contentAsArray */
80
        $contentAsArray = \Safe\json_decode($content, true);
81
82
        return $contentAsArray;
83
    }
84
}
85