Skip to content

Commit 4384d9f

Browse files
authored
Update to v3 api (#12)
* Update to v3 api * Do not set body for GET requests * Update readme * Add mise * Add changelog * Add publish action * Adjust readme * Add deprecations * Add test tasks * Do not specify phpunit version * Use test-silent in github actions * Add deprecations * Add phpdoc throws
1 parent f9731ce commit 4384d9f

12 files changed

Lines changed: 240 additions & 116 deletions

File tree

.github/workflows/main.yml

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ jobs:
1010
- '7.0'
1111
- '7.4'
1212
- '8.2'
13+
- '8.3'
14+
- '8.4'
1315
name: PHP ${{ matrix.php-version }} sample
1416
steps:
1517
- uses: actions/checkout@v3
@@ -20,4 +22,4 @@ jobs:
2022
- run: composer install
2123
- env:
2224
DETECTLANGUAGE_API_KEY: ${{ secrets.DETECTLANGUAGE_API_KEY }}
23-
run: bin/phpunit
25+
run: composer test-silent

.github/workflows/publish.yml

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
name: Release to Packagist
2+
on:
3+
release:
4+
types: [published]
5+
jobs:
6+
release:
7+
runs-on: ubuntu-latest
8+
steps:
9+
- name: Dispatch packagist update
10+
run: |
11+
curl -X POST https://packagist.org/api/update-package?username=${{ secrets.PACKAGIST_USERNAME }}&apiToken=${{ secrets.PACKAGIST_API_TOKEN }} \
12+
-d '{"repository":{"url":"https://github.com/detectlanguage/detectlanguage-php"}}' \
13+
-H "Content-Type: application/json"

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
.env.local
12
.DS_Store
23
.AppleDouble
34
.LSOverride
@@ -6,6 +7,7 @@ Icon
67
.Spotlight-V100
78
.Trashes
89
*.sublime-*
10+
.phpunit.result.cache
911
vendor
1012
composer.lock
1113
bin

CHANGELOG.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Changelog
2+
3+
All notable changes to this project will be documented in this file.
4+
5+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7+
8+
9+
## v3.0.0
10+
11+
### Added
12+
- `detectBatch` method for batch detections
13+
14+
### Changed
15+
- Switched to v3 API which uses updated language detection model
16+
- ⚠️ `detect` method result fields are `language` and `score`
17+
18+
### Deprecated
19+
- `simpleDetect()` - Use `detectCode()` instead.
20+
- Calling `detect()` with array argument. Use `detectBatch()` instead.
21+
22+
### Removed
23+
- Secure mode configuration. HTTPS is always used.

README.md

Lines changed: 43 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -28,26 +28,27 @@ Create or add the following to composer.json in your project root:
2828
}
2929
```
3030

31+
## Upgrading
32+
33+
When upgrading please check [changelog](CHANGELOG.md) for breaking changes.
34+
3135
## Usage
3236

3337
### Configuration
3438

3539
Before using Detect Language API client you have to setup your personal API key.
36-
You can get it by signing up at http://detectlanguage.com
40+
You can get it by signing up at https://detectlanguage.com
3741

3842
```php
3943
use \DetectLanguage\DetectLanguage;
4044

4145
DetectLanguage::setApiKey("YOUR API KEY");
42-
43-
// Enable secure mode if passing sensitive information
44-
// DetectLanguage::setSecure(true);
4546
```
4647

47-
### Language detection
48+
### Detect language
4849

4950
```php
50-
$results = DetectLanguage::detect("Buenos dias señor");
51+
$results = DetectLanguage::detect("Dolce far niente");
5152
```
5253

5354
#### Results
@@ -57,36 +58,35 @@ Array
5758
(
5859
[0] => stdClass Object
5960
(
60-
[language] => es
61-
[isReliable] => 1
62-
[confidence] => 10.24
61+
[language] => it
62+
[score] => 0.5074
6363
)
6464

6565
)
6666
```
6767

68-
### Simple language detection
68+
### Detect single code
6969

70-
If you need just a language code you can use `simpleDetect`. It returns just the language code.
70+
If you need just a language code you can use `detectCode`. It returns just the language code.
7171

7272
```php
73-
$languageCode = DetectLanguage::simpleDetect("Buenos dias señor");
73+
$languageCode = DetectLanguage::detectCode("Dolce far niente");
7474
```
7575

7676
#### Result
7777

7878
```php
79-
"es"
79+
"it"
8080
```
8181

8282
### Batch detection
8383

8484
It is possible to detect language of several texts with one request.
8585
This method is faster than doing one request per text.
86-
To use batch detection just pass array of texts to `detect` method.
86+
To use batch detection just pass array of texts to `detectBatch` method.
8787

8888
```php
89-
$results = DetectLanguage::detect(array("Buenos dias señor", "Hello world"));
89+
$results = DetectLanguage::detectBatch(array("Dolce far niente", "Hello world"));
9090
```
9191

9292
#### Results
@@ -100,9 +100,8 @@ Array
100100
(
101101
[0] => stdClass Object
102102
(
103-
[language] => es
104-
[isReliable] => 1
105-
[confidence] => 10.24
103+
[language] => it
104+
[score] => 0.5074
106105
)
107106

108107
)
@@ -112,8 +111,7 @@ Array
112111
[0] => stdClass Object
113112
(
114113
[language] => en
115-
[isReliable] => 1
116-
[confidence] => 11.94
114+
[score] => 0.9098
117115
)
118116

119117
)
@@ -143,6 +141,31 @@ stdClass Object
143141
)
144142
```
145143

144+
### Get list of supported languages
145+
146+
```php
147+
$results = DetectLanguage::getLanguages();
148+
```
149+
150+
#### Result
151+
152+
```php
153+
Array
154+
(
155+
[0] => stdClass Object
156+
(
157+
[code] => aa
158+
[name] => Afar
159+
)
160+
161+
[1] => stdClass Object
162+
(
163+
[code] => ab
164+
[name] => Abkhazian
165+
)
166+
...
167+
```
168+
146169
## License
147170

148171
Detect Language API Client is free software, and may be redistributed under the terms specified in the MIT-LICENSE file.

composer.json

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,5 +24,9 @@
2424
"psr-0": {
2525
"DetectLanguage": "lib/"
2626
}
27+
},
28+
"scripts": {
29+
"test": "php -d memory_limit=512M vendor/phpunit/phpunit/phpunit",
30+
"test-silent": "php -d memory_limit=512M -d error_reporting='E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED' vendor/phpunit/phpunit/phpunit"
2731
}
2832
}

lib/DetectLanguage/Client.php

Lines changed: 37 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -28,20 +28,27 @@ class Client
2828
/**
2929
* Perform a request
3030
*
31-
* @param string $method Method name
32-
* @param array $params The parameters to use for the POST body
31+
* @param string $method HTTP method name (GET, POST, etc.)
32+
* @param string $path API endpoint path
33+
* @param array|null $payload Request payload data
3334
*
34-
* @return object
35+
* @return array Response data
36+
* @throws \DetectLanguage\Error When API request fails, invalid response received, or authentication fails
3537
*/
36-
public static function request($method, $params = null)
38+
public static function request($method, $path, $payload = null)
3739
{
38-
$url = self::getUrl($method);
40+
$url = self::getUrl($path);
41+
42+
if ($payload !== null)
43+
$body = json_encode($payload);
44+
else
45+
$body = null;
3946

40-
$request_method = self::getRequestMethodName();
41-
$response_body = self::$request_method($url, $params);
47+
$engine_method = self::getEngineMethodName();
48+
$response_body = self::$engine_method($method,$url, $body);
4249
$response = json_decode($response_body);
4350

44-
if (!is_object($response))
51+
if (!is_object($response) && !is_array($response))
4552
throw new Error("Invalid server response: $response_body");
4653

4754
if (isset($response->error))
@@ -50,12 +57,7 @@ public static function request($method, $params = null)
5057
return $response;
5158
}
5259

53-
/**
54-
* Get request method name.
55-
*
56-
* @return string
57-
*/
58-
protected static function getRequestMethodName()
60+
protected static function getEngineMethodName()
5961
{
6062
$request_engine = self::$requestEngine;
6163

@@ -79,23 +81,27 @@ protected static function getRequestMethodName()
7981
/**
8082
* Perform request using native PHP streams
8183
*
84+
* @param string $method HTTP method name
8285
* @param string $url Request URL
83-
* @param array $params The parameters to use for the POST body
86+
* @param string|null $body Request body
8487
*
8588
* @return string Response body
8689
*/
87-
protected static function requestStream($url, $params)
90+
protected static function requestStream($method, $url, $body)
8891
{
8992
$opts = array('http' =>
9093
array(
91-
'method' => 'POST',
94+
'method' => $method,
9295
'header' => implode("\n", self::getHeaders()),
93-
'content' => json_encode($params),
9496
'timeout' => self::$requestTimeout,
9597
'ignore_errors' => true,
9698
)
9799
);
98100

101+
if ($body !== null) {
102+
$opts['http']['content'] = $body;
103+
}
104+
99105
$context = stream_context_create($opts);
100106

101107
return file_get_contents($url, false, $context);
@@ -104,25 +110,31 @@ protected static function requestStream($url, $params)
104110
/**
105111
* Perform request using CURL extension.
106112
*
113+
* @param string $method HTTP method name
107114
* @param string $url Request URL
108-
* @param array $params The parameters to use for the POST body
115+
* @param string|null $body Request body
109116
*
110117
* @return string Response body
118+
* @throws \DetectLanguage\Error When CURL request fails, times out, or connection fails
111119
*/
112-
protected static function requestCurl($url, $params)
120+
protected static function requestCurl($method, $url, $body)
113121
{
114122
$ch = curl_init();
115123

116124
$options = array(
125+
CURLOPT_CUSTOMREQUEST => $method,
117126
CURLOPT_URL => $url,
118127
CURLOPT_HTTPHEADER => self::getHeaders(),
119-
CURLOPT_POSTFIELDS => json_encode($params),
120128
CURLOPT_CONNECTTIMEOUT => self::$connectTimeout,
121129
CURLOPT_TIMEOUT => self::$requestTimeout,
122130
CURLOPT_USERAGENT => self::getUserAgent(),
123131
CURLOPT_RETURNTRANSFER => true
124132
);
125133

134+
if ($body !== null) {
135+
$options[CURLOPT_POSTFIELDS] = $body;
136+
}
137+
126138
curl_setopt_array($ch, $options);
127139

128140
$result = curl_exec($ch);
@@ -142,27 +154,17 @@ protected static function requestCurl($url, $params)
142154
* Build URL for given method
143155
*
144156
* @param string $method Method name
145-
* @return string
157+
* @return string Complete API URL
146158
*/
147159
protected static function getUrl($method)
148160
{
149-
return self::getProtocol() . '://' . DetectLanguage::$host . '/' . DetectLanguage::$apiVersion . '/' . $method;
150-
}
151-
152-
/**
153-
* Get protocol for request.
154-
*
155-
* @return string 'https' or 'http'
156-
*/
157-
protected static function getProtocol()
158-
{
159-
return DetectLanguage::$secure ? 'https' : 'http';
161+
return 'https://' . DetectLanguage::$host . '/' . DetectLanguage::$apiVersion . '/' . $method;
160162
}
161163

162164
/**
163165
* Build request headers.
164166
*
165-
* @return array
167+
* @return array Array of HTTP headers
166168
*/
167169
protected static function getHeaders()
168170
{
@@ -177,7 +179,7 @@ protected static function getHeaders()
177179
/**
178180
* Get User-Agent for the request.
179181
*
180-
* @return string
182+
* @return string User-Agent string
181183
*/
182184
protected static function getUserAgent()
183185
{

0 commit comments

Comments
 (0)