Skip to content

Update to v3 api #12

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 13 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ jobs:
- '7.0'
- '7.4'
- '8.2'
- '8.3'
- '8.4'
name: PHP ${{ matrix.php-version }} sample
steps:
- uses: actions/checkout@v3
Expand All @@ -20,4 +22,4 @@ jobs:
- run: composer install
- env:
DETECTLANGUAGE_API_KEY: ${{ secrets.DETECTLANGUAGE_API_KEY }}
run: bin/phpunit
run: composer test-silent
13 changes: 13 additions & 0 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
name: Release to Packagist
on:
release:
types: [published]
jobs:
release:
runs-on: ubuntu-latest
steps:
- name: Dispatch packagist update
run: |
curl -X POST https://packagist.org/api/update-package?username=${{ secrets.PACKAGIST_USERNAME }}&apiToken=${{ secrets.PACKAGIST_API_TOKEN }} \
-d '{"repository":{"url":"https://github.com/detectlanguage/detectlanguage-php"}}' \
-H "Content-Type: application/json"
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
.env.local
.DS_Store
.AppleDouble
.LSOverride
Expand All @@ -6,6 +7,7 @@ Icon
.Spotlight-V100
.Trashes
*.sublime-*
.phpunit.result.cache
vendor
composer.lock
bin
23 changes: 23 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).


## v3.0.0

### Added
- `detectBatch` method for batch detections

### Changed
- Switched to v3 API which uses updated language detection model
- ⚠️ `detect` method result fields are `language` and `score`

### Deprecated
- `simpleDetect()` - Use `detectCode()` instead.
- Calling `detect()` with array argument. Use `detectBatch()` instead.

### Removed
- Secure mode configuration. HTTPS is always used.
63 changes: 43 additions & 20 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,26 +28,27 @@ Create or add the following to composer.json in your project root:
}
```

## Upgrading

When upgrading please check [changelog](CHANGELOG.md) for breaking changes.

## Usage

### Configuration

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

```php
use \DetectLanguage\DetectLanguage;

DetectLanguage::setApiKey("YOUR API KEY");

// Enable secure mode if passing sensitive information
// DetectLanguage::setSecure(true);
```

### Language detection
### Detect language

```php
$results = DetectLanguage::detect("Buenos dias señor");
$results = DetectLanguage::detect("Dolce far niente");
```

#### Results
Expand All @@ -57,36 +58,35 @@ Array
(
[0] => stdClass Object
(
[language] => es
[isReliable] => 1
[confidence] => 10.24
[language] => it
[score] => 0.5074
)

)
```

### Simple language detection
### Detect single code

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

```php
$languageCode = DetectLanguage::simpleDetect("Buenos dias señor");
$languageCode = DetectLanguage::detectCode("Dolce far niente");
```

#### Result

```php
"es"
"it"
```

### Batch detection

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

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

#### Results
Expand All @@ -100,9 +100,8 @@ Array
(
[0] => stdClass Object
(
[language] => es
[isReliable] => 1
[confidence] => 10.24
[language] => it
[score] => 0.5074
)

)
Expand All @@ -112,8 +111,7 @@ Array
[0] => stdClass Object
(
[language] => en
[isReliable] => 1
[confidence] => 11.94
[score] => 0.9098
)

)
Expand Down Expand Up @@ -143,6 +141,31 @@ stdClass Object
)
```

### Get list of supported languages

```php
$results = DetectLanguage::getLanguages();
```

#### Result

```php
Array
(
[0] => stdClass Object
(
[code] => aa
[name] => Afar
)

[1] => stdClass Object
(
[code] => ab
[name] => Abkhazian
)
...
```

## License

Detect Language API Client is free software, and may be redistributed under the terms specified in the MIT-LICENSE file.
4 changes: 4 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,9 @@
"psr-0": {
"DetectLanguage": "lib/"
}
},
"scripts": {
"test": "php -d memory_limit=512M vendor/phpunit/phpunit/phpunit",
"test-silent": "php -d memory_limit=512M -d error_reporting='E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED' vendor/phpunit/phpunit/phpunit"
}
}
72 changes: 37 additions & 35 deletions lib/DetectLanguage/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,20 +28,27 @@ class Client
/**
* Perform a request
*
* @param string $method Method name
* @param array $params The parameters to use for the POST body
* @param string $method HTTP method name (GET, POST, etc.)
* @param string $path API endpoint path
* @param array|null $payload Request payload data
*
* @return object
* @return array Response data
* @throws \DetectLanguage\Error When API request fails, invalid response received, or authentication fails
*/
public static function request($method, $params = null)
public static function request($method, $path, $payload = null)
{
$url = self::getUrl($method);
$url = self::getUrl($path);

if ($payload !== null)
$body = json_encode($payload);
else
$body = null;

$request_method = self::getRequestMethodName();
$response_body = self::$request_method($url, $params);
$engine_method = self::getEngineMethodName();
$response_body = self::$engine_method($method,$url, $body);
$response = json_decode($response_body);

if (!is_object($response))
if (!is_object($response) && !is_array($response))
throw new Error("Invalid server response: $response_body");

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

/**
* Get request method name.
*
* @return string
*/
protected static function getRequestMethodName()
protected static function getEngineMethodName()
{
$request_engine = self::$requestEngine;

Expand All @@ -79,23 +81,27 @@ protected static function getRequestMethodName()
/**
* Perform request using native PHP streams
*
* @param string $method HTTP method name
* @param string $url Request URL
* @param array $params The parameters to use for the POST body
* @param string|null $body Request body
*
* @return string Response body
*/
protected static function requestStream($url, $params)
protected static function requestStream($method, $url, $body)
{
$opts = array('http' =>
array(
'method' => 'POST',
'method' => $method,
'header' => implode("\n", self::getHeaders()),
'content' => json_encode($params),
'timeout' => self::$requestTimeout,
'ignore_errors' => true,
)
);

if ($body !== null) {
$opts['http']['content'] = $body;
}

$context = stream_context_create($opts);

return file_get_contents($url, false, $context);
Expand All @@ -104,25 +110,31 @@ protected static function requestStream($url, $params)
/**
* Perform request using CURL extension.
*
* @param string $method HTTP method name
* @param string $url Request URL
* @param array $params The parameters to use for the POST body
* @param string|null $body Request body
*
* @return string Response body
* @throws \DetectLanguage\Error When CURL request fails, times out, or connection fails
*/
protected static function requestCurl($url, $params)
protected static function requestCurl($method, $url, $body)
{
$ch = curl_init();

$options = array(
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => self::getHeaders(),
CURLOPT_POSTFIELDS => json_encode($params),
CURLOPT_CONNECTTIMEOUT => self::$connectTimeout,
CURLOPT_TIMEOUT => self::$requestTimeout,
CURLOPT_USERAGENT => self::getUserAgent(),
CURLOPT_RETURNTRANSFER => true
);

if ($body !== null) {
$options[CURLOPT_POSTFIELDS] = $body;
}

curl_setopt_array($ch, $options);

$result = curl_exec($ch);
Expand All @@ -142,27 +154,17 @@ protected static function requestCurl($url, $params)
* Build URL for given method
*
* @param string $method Method name
* @return string
* @return string Complete API URL
*/
protected static function getUrl($method)
{
return self::getProtocol() . '://' . DetectLanguage::$host . '/' . DetectLanguage::$apiVersion . '/' . $method;
}

/**
* Get protocol for request.
*
* @return string 'https' or 'http'
*/
protected static function getProtocol()
{
return DetectLanguage::$secure ? 'https' : 'http';
return 'https://' . DetectLanguage::$host . '/' . DetectLanguage::$apiVersion . '/' . $method;
}

/**
* Build request headers.
*
* @return array
* @return array Array of HTTP headers
*/
protected static function getHeaders()
{
Expand All @@ -177,7 +179,7 @@ protected static function getHeaders()
/**
* Get User-Agent for the request.
*
* @return string
* @return string User-Agent string
*/
protected static function getUserAgent()
{
Expand Down
Loading