Repository: JoggApp/laravel-google-translate
Branch: master
Commit: 160d71c10e0a
Files: 15
Total size: 32.8 KB
Directory structure:
gitextract_whxtlv0s/
├── .github/
│ └── workflows/
│ └── run-tests.yml
├── .gitignore
├── CHANGELOG.md
├── LICENSE.txt
├── README.md
├── composer.json
├── config/
│ └── googletranslate.php
├── google.md
├── phpunit.xml.dist
├── src/
│ ├── GoogleTranslate.php
│ ├── GoogleTranslateClient.php
│ ├── GoogleTranslateFacade.php
│ ├── GoogleTranslateServiceProvider.php
│ └── Traits/
│ └── SupportedLanguages.php
└── tests/
└── GoogleTranslateTest.php
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/workflows/run-tests.yml
================================================
name: "Run Tests"
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
strategy:
fail-fast: true
matrix:
php: [8.0, 8.1]
laravel: [9.*]
dependency-version: [prefer-lowest, prefer-stable]
name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.dependency-version }}
steps:
- name: Checkout code
uses: actions/checkout@v1
- name: Cache dependencies
uses: actions/cache@v1
with:
path: ~/.composer/cache/files
key: dependencies-laravel-${{ matrix.laravel }}-php-${{ matrix.php }}-composer-${{ hashFiles('composer.json') }}
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick
coverage: none
- name: Install dependencies
run: composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction --no-suggest
- name: Execute tests
run: vendor/bin/phpunit
================================================
FILE: .gitignore
================================================
/vendor
composer.lock
.DS_Store
Thumbs.db
phpunit.xml
/.idea
.phpunit.result.cache
================================================
FILE: CHANGELOG.md
================================================
All the notable changes to the Laravel Google Translate package are documented in this file:
## 9.0 (1-1-2023)
- Change method name (fix typo)
## 8.1.0 (14-07-2022)
- Fixes by [Florian Ressel](https://github.com/resslinger) across various PRs.
- Thank you Florian :heart:
## 8.0.0 (07-03-2022)
- Set minimum PHP requirement to PHP 8.0
- [PR by Florian Ressel to add support for Laravel 9](https://github.com/JoggApp/laravel-google-translate/pull/36)
- [PR by Florian Ressel to add the source language as param to translate method](https://github.com/JoggApp/laravel-google-translate/pull/34)
## 7.0.0 (24-01-2021)
- Add PHP 8 Support
- Drop PHP 7.3 Support
- [PR by Josias](https://github.com/JoggApp/laravel-google-translate/pull/24)
## 6.0.1 (10-09-2020)
- Fix https://github.com/JoggApp/laravel-google-translate/issues/13
## 6.0.0 (10-09-2020)
- Added Laravel v8.x support.
- Dropped Laravel v6.x & PHPUnit v8 support.
## v5.0.1 (30-06-2020)
- Patched the format delegation bug.
- Thank you to [Simon](https://github.com/smorris1709) for the [PR](https://github.com/JoggApp/laravel-google-translate/pull/18).
## 5.0.0 (03-03-2020)
- Added Laravel v7.x support.
- Dropped PHP v7.2 support, now PHP v7.3 is the minimum requirement.
## 4.0.1 (14-01-2020)
- Added Github Actions workflow
## v4.0.0 (07-01-2020)
- Use v2 of Google translate client
- Thank you to [Flears Network](https://github.com/RossUK88) for the [PR](https://github.com/JoggApp/laravel-google-translate/pull/12).
## v3.0.2 (22-11-2019)
- Added input validation.
- Thank you to [Ross](https://github.com/RossUK88) for the [PR](https://github.com/JoggApp/laravel-google-translate/pull/9).
## v3.0.1 (14-11-2019)
- Added the support for the format param.
- Thank you to [Ross](https://github.com/RossUK88) for the [PR](https://github.com/JoggApp/laravel-google-translate/pull/8).
## v3.0.0 (04-09-2019)
- Now supports Laravel v6.0
- Support for Laravel v5.8 will be dropped in v3.1
## v2.0.5 (27-04-2019)
- Support the 'zh-TW' locale code.
- Thank you to [Jaric](https://github.com/jaric) for sending the initial [PR](https://github.com/JoggApp/laravel-google-translate/pull/4).
## v2.0.4 (27-02-2019)
- Remove phpunit depcrications
## v2.0.3 (27-02-2019)
- update phpunit
## v2.0.2 (27-02-2019)
- update phpunit
## v2.0.1 (27-02-2019)
- patch fix
## v2.0.0 (27-02-2019)
- Now supports Laravel v5.8
## v1.0.1 (26-01-2019)
- Included the missing 'he' locale code.
## v1.0.0 (23-10-2018)
- Initial release
================================================
FILE: LICENSE.txt
================================================
The MIT License (MIT)
Copyright (c) Jogg Inc <info@jogg.co>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
================================================
FILE: README.md
================================================
# This package is no longer actively developed. [More details here/Call for maintainers](https://github.com/JoggApp/laravel-google-translate/discussions/51)
# Laravel package for the Google Translate API
[](https://github.com/JoggApp/laravel-google-translate/releases)

[](https://packagist.org/packages/JoggApp/laravel-google-translate)
This package makes using the Google Translate API in your laravel app a breeze with minimum to no configuration, clean syntax and a consistent package API.

## Installation
- You can install this package via composer using this command:
```bash
composer require joggapp/laravel-google-translate
```
- The package will automatically register itself.
- We have documented how to setup the project and get the necessary configurations from the Google Cloud Platform console in a step by step detailed manner [over here.](https://github.com/JoggApp/laravel-google-translate/blob/master/google.md)
- You can publish the config file using the following command:
```bash
php artisan vendor:publish --provider="JoggApp\GoogleTranslate\GoogleTranslateServiceProvider"
```
This will create the package's config file called `googletranslate.php` in the `config` directory. These are the contents of the published config file:
```php
return [
/*
|----------------------------------------------------------------------------------------------------
| The ISO 639-1 code of the language in lowercase to which the text will be translated to by default.
|----------------------------------------------------------------------------------------------------
*/
'default_target_translation' => 'en',
/*
|-------------------------------------------------------------------------------
| Path to the json file containing the authentication credentials.
|
| The process to get this file is documented in a step by step detailed manner
| over here:
| https://github.com/JoggApp/laravel-google-translate/blob/master/google.md
|-------------------------------------------------------------------------------
*/
'api_key' => env('GOOGLE_TRANSLATE_API_KEY'),
];
```
## How to use
- After setting up the config file values you are all set to use the following methods :smile:
- Detecting the language. You can pass both, a single string or an array of multiple strings to it:
```php
GoogleTranslate::detectLanguage('Hello world'): array
GoogleTranslate::detectLanguage(['Hello world', 'Laravel is the best']);
// Returns multi-dimensional array containing result set for all the array elements.
```
- Translating the string(s): The `translate` method accepts a third optional argument which can be the code of the language you want the string to be translated in. You can specify the default option in the config file:
```php
// GoogleTranslate::translate($input, $from = null, $to = null, $format = 'text'): array
GoogleTranslate::translate('Hello world'): array
GoogleTranslate::translate(['Hello world', 'Laravel is the best']);
// Returns multi-dimensional array containing result set for all the array elements.
```
- Get all the available translations from 'Google Translation' for a particular language by passing its language code:
```php
GoogleTranslate::getAvailableTranslationsFor('en'): array
```
- Translate unless the language is same as the first argument. This method is a clean way to ask the package to detect the language of the given string, if it is same as the first argument, translation isn't performed. It accepts an optional third argument which is the language code you want the string to be translated in. You can specify the default option in the config file. If the languages are same, the input string is returned as it is, else an array is returned containing the translation results:
```php
GoogleTranslate::unlessLanguageIs('en', string $text);
```
- Translating and just returning back the translated string. It accepts an optional second argument which is the language code you want the string to be translated in. You can specify the default option in the config file.
```php
GoogleTranslate::justTranslate(string $text): string
```
- There is is an optional third parameter for format to take advantage for better html translation support. Google Translate API currently supports 'text' and 'html' as parameters. The default for this parameter is 'text' as it has the best use case for most translations.
[Google Translate API Docs](https://cloud.google.com/translate/docs/reference/rest/v2/translate)
```php
GoogleTranslate::unlessLanguageIs('en', string $text, string $format);
```
- There is also a nice blade helper called `@translate` that comes with the package to make its use more neat in the view files. It accepts an optional second argument which is the language code you want the string to be translated in. You can specify the default option in the config file.
```
@translate('Hello World')
```
## Testing
You can run the tests with:
```bash
vendor/bin/phpunit
```
## Changelog
Please see the [CHANGELOG](CHANGELOG.md) for more information about what has changed recently.
## Security
If you discover any security related issues, please email them to [harish@jogg.co](mailto:harish@jogg.co) instead of using the issue tracker.
## Credits
- [Harish Toshniwal](https://github.com/introwit)
- [All Contributors](../../contributors)
## License
The MIT License (MIT). Please see the [License File](LICENSE.txt) for more information.
================================================
FILE: composer.json
================================================
{
"name": "joggapp/laravel-google-translate",
"description": "Laravel package for the Google Translate API",
"keywords": [
"laravel",
"package",
"google",
"translate",
"google translate",
"api"
],
"license": "MIT",
"authors": [
{
"name": "Harish Toshniwal",
"email": "harish@jogg.co"
}
],
"autoload": {
"psr-4": {
"JoggApp\\GoogleTranslate\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"JoggApp\\GoogleTranslate\\Tests\\": "tests"
}
},
"require": {
"php": "^8.0",
"google/cloud-translate": "^1.2",
"illuminate/support": "9.*"
},
"require-dev": {
"mockery/mockery": "^1.1",
"orchestra/testbench" : "7.*",
"phpunit/phpunit": "^9.0"
},
"extra": {
"laravel": {
"providers": [
"JoggApp\\GoogleTranslate\\GoogleTranslateServiceProvider"
],
"aliases":{
"GoogleTranslate": "JoggApp\\GoogleTranslate\\GoogleTranslateFacade"
}
}
},
"config": {
"sort-packages": true
},
"minimum-stability": "dev",
"prefer-stable": true
}
================================================
FILE: config/googletranslate.php
================================================
<?php
return [
/*
|----------------------------------------------------------------------------------------------------
| The ISO 639-1 code of the default source language.
|----------------------------------------------------------------------------------------------------
*/
'default_source_translation' => 'en',
/*
|----------------------------------------------------------------------------------------------------
| The ISO 639-1 code of the language in lowercase to which the text will be translated to by default.
|----------------------------------------------------------------------------------------------------
*/
'default_target_translation' => 'en',
/*
|-------------------------------------------------------------------------------
| Api Key generated within Google Cloud Dashboard.
|
| The process to get this file is documented in a step by step detailed manner
| over here:
| https://github.com/JoggApp/laravel-google-translate/blob/master/google.md
|-------------------------------------------------------------------------------
*/
'api_key' => env('GOOGLE_TRANSLATE_API_KEY'),
];
================================================
FILE: google.md
================================================
- After logging in the Google Cloud Platform console you will need to enable the Cloud Translate API via the API Library section.
- Now, we first need to create a new project in the Google Cloud Platform console.
- You will see a screen like this once you click on "New Project" on the dashoard:
<img width="576" alt="screen shot 2018-10-11 at 12 11 19 am" src="https://user-images.githubusercontent.com/11228182/46759117-29c62600-ccec-11e8-99a2-b23ee035a75d.png">
- Select the project you just created, and go the "APIs & Services" -> "Credentials" using the navigation.
- Click at the "Create credentials" dropdown button and choose "API key". To prevent unauthorized use and quota theft, restrict your key to limit how it can be used.
- Now, you can use this key to set a package-specific environment variable:
```
GOOGLE_TRANSLATE_API_KEY=AIzaS.....
```
================================================
FILE: phpunit.xml.dist
================================================
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false">
<testsuites>
<testsuite name="Package Tests">
<directory suffix="Test.php">./tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./src</directory>
</whitelist>
</filter>
</phpunit>
================================================
FILE: src/GoogleTranslate.php
================================================
<?php
namespace JoggApp\GoogleTranslate;
use Exception;
use InvalidArgumentException;
use JoggApp\GoogleTranslate\Traits\SupportedLanguages;
class GoogleTranslate
{
use SupportedLanguages;
private $translateClient;
private $givenLanguageCode;
public function __construct(GoogleTranslateClient $client)
{
$this->translateClient = $client;
}
public function detectLanguage($input): array
{
if (is_array($input)) {
return $this->detectLanguageBatch($input);
}
$this->validateInput($input);
$response = $this
->translateClient
->detectLanguage($input);
return [
'text' => $input,
'language_code' => $response['languageCode'],
'confidence' => $response['confidence']
];
}
public function detectLanguageBatch(array $input): array
{
$this->validateInput($input);
$responses = $this
->translateClient
->detectLanguageBatch($input);
foreach ($responses as $response) {
$translations[] = [
'text' => $response['input'],
'language_code' => $response['languageCode'],
'confidence' => $response['confidence']
];
}
return $translations;
}
public function translate($input, $from = null, $to = null, $format = 'text'): array
{
$this->validateInput($input);
$translateFrom = $from ?? config('googletranslate.default_source_translation');
$translateTo = $to ?? config('googletranslate.default_target_translation');
$translateFrom = $this->sanitizeLanguageCode($translateFrom);
$translateTo = $this->sanitizeLanguageCode($translateTo);
if (is_array($input)) {
return $this->translateBatch($input, $translateFrom, $translateTo, $format);
}
$response = $this
->translateClient
->translate($input, $translateFrom, $translateTo, $format);
return [
'source_text' => $input,
'source_language_code' => $translateFrom,
'translated_text' => $response['text'],
'translated_language_code' => $translateTo
];
}
public function justTranslate(string $input, $from = null, $to = null): string
{
$this->validateInput($input);
$translateFrom = $from ?? config('googletranslate.default_source_translation');
$translateTo = $to ?? config('googletranslate.default_target_translation');
$translateFrom = $this->sanitizeLanguageCode($translateFrom);
$translateTo = $this->sanitizeLanguageCode($translateTo);
$response = $this
->translateClient
->translate($input, $translateFrom, $translateTo);
return $response['text'];
}
public function translateBatch(array $input, string $translateFrom, string $translateTo, $format = 'text'): array
{
$translateFrom = $this->sanitizeLanguageCode($translateFrom);
$translateTo = $this->sanitizeLanguageCode($translateTo);
$this->validateInput($input);
$responses = $this
->translateClient
->translateBatch($input, $translateFrom, $translateTo, $format);
foreach ($responses as $response) {
$translations[] = [
'source_text' => $response['input'],
'source_language_code' => $translateFrom,
'translated_text' => $response['text'],
'translated_language_code' => $translateTo
];
}
return $translations;
}
public function getAvailableTranslationsFor(string $languageCode): array
{
$languageCode = $this->sanitizeLanguageCode($languageCode);
return $this->translateClient
->getAvailableTranslationsFor($languageCode);
}
public function unlessLanguageIs(string $languageCode, string $input, $from = null, $to = null)
{
$translateFrom = $from ?? config('googletranslate.default_source_translation');
$translateTo = $to ?? config('googletranslate.default_target_translation');
$translateFrom = $this->sanitizeLanguageCode($translateFrom);
$translateTo = $this->sanitizeLanguageCode($translateTo);
$languageCode = $this->sanitizeLanguageCode($languageCode);
$languageMisMatch = $languageCode != $this->detectLanguage($input)['language_code'];
if ($languageMisMatch) {
return $this->translate($input, $translateFrom, $translateTo);
}
return $input;
}
public function sanitizeLanguageCode(string $languageCode)
{
$languageCode = trim(strtolower($languageCode));
if ($languageCode === 'zh-tw') {
$languageCode = 'zh-TW';
}
if (in_array($languageCode, $this->languages())) {
return $languageCode;
}
throw new Exception(
"Invalid or unsupported ISO 639-1 language code -{$languageCode}-,
get the list of valid and supported language codes by running GoogleTranslate::languages()"
);
}
protected function validateInput($input): void
{
if(is_array($input) && in_array(null, $input)) {
throw new InvalidArgumentException('Input string cannot be null');
}
if(is_null($input)) {
throw new InvalidArgumentException('Input string cannot be null');
}
return;
}
}
================================================
FILE: src/GoogleTranslateClient.php
================================================
<?php
namespace JoggApp\GoogleTranslate;
use Exception;
use Google\Cloud\Translate\V2\TranslateClient;
use JoggApp\GoogleTranslate\Traits\SupportedLanguages;
class GoogleTranslateClient
{
use SupportedLanguages;
private $translate;
public function __construct(array $config)
{
$this->checkForInvalidConfiguration($config);
$this->translate = new TranslateClient([
'key' => $config['api_key'],
]);
}
public function detectLanguage(string $text)
{
return $this->translate
->detectLanguage($text);
}
public function detectLanguageBatch(array $input)
{
return $this->translate
->detectLanguageBatch($input);
}
public function translate(string $text, string $translateFrom, string $translateTo, string $format = 'text')
{
return $this->translate
->translate($text, ['source' => $translateFrom, 'target' => $translateTo, 'format' => $format]);
}
public function translateBatch(array $input, string $translateFrom, string $translateTo, string $format = 'text')
{
return $this->translate
->translateBatch($input, ['source' => $translateFrom, 'target' => $translateTo, 'format' => $format]);
}
public function getAvailableTranslationsFor(string $languageCode)
{
return $this->translate
->localizedLanguages(['target' => $languageCode]);
}
private function checkForInvalidConfiguration(array $config)
{
if ( ! isset($config['api_key']) || $config['api_key'] === null) {
throw new Exception('Google Api Key is required.');
}
$codeInConfig = $config['default_target_translation'];
$languageCodeIsValid = is_string($codeInConfig)
&& ctype_lower($codeInConfig)
&& in_array($codeInConfig, $this->languages());
if ( ! $languageCodeIsValid) {
throw new Exception(
'The default_target_translation value in the config/googletranslate.php file should
be a valid lowercase ISO 639-1 code of the language'
);
}
}
}
================================================
FILE: src/GoogleTranslateFacade.php
================================================
<?php
namespace JoggApp\GoogleTranslate;
use Illuminate\Support\Facades\Facade;
/**
* @see \JoggApp\GoogleTranslate\GoogleTranslate
*/
class GoogleTranslateFacade extends Facade
{
protected static function getFacadeAccessor()
{
return 'laravel-google-translate';
}
}
================================================
FILE: src/GoogleTranslateServiceProvider.php
================================================
<?php
namespace JoggApp\GoogleTranslate;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
class GoogleTranslateServiceProvider extends ServiceProvider
{
public function boot()
{
$this->publishes([
__DIR__ . '/../config/googletranslate.php' => config_path('googletranslate.php'),
]);
$defaultLanguage = config('googletranslate.default_target_translation');
Blade::directive('translate', function ($expression) use ($defaultLanguage) {
$expression = explode(',', $expression);
$input = $expression[0];
$languageCode = isset($expression[1]) ? $expression[1] : $defaultLanguage;
return "<?php echo GoogleTranslate::justTranslate($input, $languageCode); ?>";
});
}
public function register()
{
$this->mergeConfigFrom(__DIR__ . '/../config/googletranslate.php', 'googletranslate');
$this->app->bind(GoogleTranslateClient::class, function () {
return new GoogleTranslateClient(config('googletranslate'));
});
$this->app->bind(GoogleTranslate::class, function () {
$client = app(GoogleTranslateClient::class);
return new GoogleTranslate($client);
});
$this->app->alias(GoogleTranslate::class, 'laravel-google-translate');
}
}
================================================
FILE: src/Traits/SupportedLanguages.php
================================================
<?php
namespace JoggApp\GoogleTranslate\Traits;
trait SupportedLanguages
{
public function languages(): array
{
return [
'af', 'am', 'ar', 'az', 'be', 'bg', 'bn', 'bs', 'ca',
'ceb', 'co', 'cs', 'cy', 'da', 'de', 'el', 'en',
'eo', 'es', 'et', 'eu', 'fa', 'fi', 'fr', 'fy',
'ga', 'gd', 'gl', 'gu', 'ha', 'haw', 'he', 'hi', 'hmn',
'hr', 'ht', 'hu', 'hy', 'id', 'ig', 'is', 'it',
'iw', 'ja', 'jw', 'ka', 'kk', 'km', 'kn', 'ko',
'ku', 'ky', 'la', 'lb', 'lo', 'lt', 'lv', 'mg',
'mi', 'mk', 'ml', 'mn', 'mr', 'ms', 'mt', 'my',
'ne', 'nl', 'no', 'ny', 'pa', 'pl', 'ps', 'pt',
'ro', 'ru', 'sd', 'si', 'sk', 'sl', 'sm', 'sn',
'so', 'sq', 'sr', 'st', 'su', 'sv', 'sw', 'ta',
'te', 'tg', 'th', 'tl', 'tr', 'uk', 'ur', 'uz',
'vi', 'xh', 'yi', 'yo', 'zh', 'zh-TW', 'zu'
];
}
}
================================================
FILE: tests/GoogleTranslateTest.php
================================================
<?php
namespace JoggApp\GoogleTranslate\Tests;
use Illuminate\Support\Facades\Config;
use JoggApp\GoogleTranslate\GoogleTranslate;
use JoggApp\GoogleTranslate\GoogleTranslateClient;
use Mockery;
use Orchestra\Testbench\TestCase as BaseTestCase;
class GoogleTranslateTest extends BaseTestCase
{
public $testString = 'A test string';
public $testHtmlString = '<p>A test string</p>';
private $translateClient;
private $translate;
public function __construct()
{
parent::__construct();
$this->translateClient = Mockery::mock(GoogleTranslateClient::class);
$this->translate = new GoogleTranslate($this->translateClient);
}
/** @test */
public function it_can_detect_the_language_of_string_passed_to_it()
{
$this->translateClient
->shouldReceive('detectLanguage')->with($this->testString)
->once()
->andReturn(['languageCode' => 'en', 'confidence' => '']);
$response = $this->translate->detectLanguage($this->testString);
$this->assertIsArray($response);
$this->assertArrayHasKey('text', $response);
$this->assertArrayHasKey('language_code', $response);
$this->assertArrayHasKey('confidence', $response);
}
/** @test */
public function it_can_detect_the_language_of_an_array_of_strings_passed_to_it()
{
$this->translateClient
->shouldReceive('detectLanguageBatch')->with([$this->testString, $this->testString])
->once()
->andReturn([
['languageCode' => 'en', 'confidence' => '', 'input' => $this->testString],
['languageCode' => 'en', 'confidence' => '', 'input' => $this->testString]
]);
$response = $this->translate->detectLanguage([$this->testString, $this->testString]);
$this->assertIsArray($response);
$this->assertArrayHasKey('text', $response[0]);
$this->assertArrayHasKey('language_code', $response[0]);
$this->assertArrayHasKey('confidence', $response[0]);
$this->assertArrayHasKey('text', $response[1]);
$this->assertArrayHasKey('language_code', $response[1]);
$this->assertArrayHasKey('confidence', $response[1]);
}
/** @test */
public function it_can_translate_the_string_passed_to_it()
{
$this->translateClient
->shouldReceive('translate')->with($this->testString, 'en', 'hi', 'text')
->once()
->andReturn(['source' => 'en', 'text' => '']);
$response = $this->translate->translate($this->testString, 'en', 'hi');
$this->assertIsArray($response);
$this->assertArrayHasKey('source_text', $response);
$this->assertArrayHasKey('source_language_code', $response);
$this->assertArrayHasKey('translated_text', $response);
$this->assertArrayHasKey('translated_language_code', $response);
}
/** @test */
public function it_can_translate_the_html_string_passed_to_it()
{
$this->translateClient
->shouldReceive('translate')->with($this->testHtmlString, 'en', 'hi', 'html')
->once()
->andReturn(['source' => 'en', 'text' => '']);
$response = $this->translate->translate($this->testHtmlString, 'en', 'hi', 'html');
$this->assertIsArray($response);
$this->assertArrayHasKey('source_text', $response);
$this->assertArrayHasKey('source_language_code', $response);
$this->assertArrayHasKey('translated_text', $response);
$this->assertArrayHasKey('translated_language_code', $response);
}
/** @test */
public function it_can_translate_an_array_of_strings_passed_to_it()
{
$this->translateClient
->shouldReceive('translateBatch')->with([$this->testString, $this->testString], 'en', 'hi', 'text')
->once()
->andReturn([
['source' => 'en', 'text' => '', 'input' => $this->testString],
['source' => 'en', 'text' => '', 'input' => $this->testString]
]);
$response = $this->translate->translate([$this->testString, $this->testString], 'en', 'hi');
$this->assertIsArray($response);
$this->assertArrayHasKey('source_text', $response[0]);
$this->assertArrayHasKey('source_language_code', $response[0]);
$this->assertArrayHasKey('translated_text', $response[0]);
$this->assertArrayHasKey('translated_language_code', $response[0]);
$this->assertArrayHasKey('source_text', $response[1]);
$this->assertArrayHasKey('source_language_code', $response[1]);
$this->assertArrayHasKey('translated_text', $response[1]);
$this->assertArrayHasKey('translated_language_code', $response[1]);
}
/** @test */
public function test_the_just_translate_method_returns_just_the_translated_string()
{
$this->translateClient
->shouldReceive('translate')->with($this->testString, 'en', 'hi')
->once()
->andReturn(['text' => 'A test string']);
$response = $this->translate->justTranslate($this->testString, 'en', 'hi');
$this->assertEquals('A test string', $response);
}
/** @test */
public function test_the_unless_language_is_method_does_not_translate_the_language_of_given_text_if_it_is_same_as_defined_in_that_method()
{
$this->translateClient
->shouldReceive('detectLanguage')->with($this->testString)
->once()
->andReturn(['languageCode' => 'en', 'confidence' => '']);
$response = $this->translate->unlessLanguageIs('en', $this->testString, 'hi', 'en');
$this->assertEquals($this->testString, $response);
}
/** @test */
public function test_the_unless_language_is_method_translates_the_language_of_given_text_only_if_it_is_same_as_defined_in_that_method()
{
$this->translateClient
->shouldReceive('detectLanguage')->with($this->testString)
->once()
->andReturn(['languageCode' => 'en', 'confidence' => '']);
$this->translateClient
->shouldReceive('translate')->with($this->testString, 'hi', 'en', 'text')
->once()
->andReturn(['source' => 'en', 'text' => '']);
$response = $this->translate->unlessLanguageIs('hi', $this->testString, 'hi', 'en');
$this->assertIsArray($response);
$this->assertArrayHasKey('source_text', $response);
$this->assertArrayHasKey('source_language_code', $response);
$this->assertArrayHasKey('translated_text', $response);
$this->assertArrayHasKey('translated_language_code', $response);
}
/** @test */
public function it_sanitizes_the_language_codes()
{
$response = $this->translate->sanitizeLanguageCode('en');
$this->assertEquals('en', $response);
$response = $this->translate->sanitizeLanguageCode(' en');
$this->assertEquals('en', $response);
$response = $this->translate->sanitizeLanguageCode('EN');
$this->assertEquals('en', $response);
// 'zh-TW' is the only language code defined by google that includes uppercase letters
$response = $this->translate->sanitizeLanguageCode('zh-TW');
$this->assertEquals('zh-TW', $response);
$this->expectExceptionMessage(
'Invalid or unsupported ISO 639-1 language code -xx-,
get the list of valid and supported language codes by running GoogleTranslate::languages()'
);
$this->translate->sanitizeLanguageCode('xx');
}
/** @test */
public function it_validates_input_against_null_strings()
{
$this->expectException(\InvalidArgumentException::class);
$this->translate->translate(null, 'en');
$this->translate->justTranslate(null, 'en');
}
/** @test */
public function it_validates_input_against_null_strings_in_a_batch()
{
$this->expectException(\InvalidArgumentException::class);
$this->translate->translateBatch([null, null], 'en', 'hi');
}
/** @test */
public function it_validates_input_agaisnt_null_strings_when_detecting_a_language()
{
$this->expectException(\InvalidArgumentException::class);
$this->translate->detectLanguage(null);
$this->translate->detectLanguage([null, null]);
$this->translate->detectLanguageBatch([null, null]);
}
}
gitextract_whxtlv0s/
├── .github/
│ └── workflows/
│ └── run-tests.yml
├── .gitignore
├── CHANGELOG.md
├── LICENSE.txt
├── README.md
├── composer.json
├── config/
│ └── googletranslate.php
├── google.md
├── phpunit.xml.dist
├── src/
│ ├── GoogleTranslate.php
│ ├── GoogleTranslateClient.php
│ ├── GoogleTranslateFacade.php
│ ├── GoogleTranslateServiceProvider.php
│ └── Traits/
│ └── SupportedLanguages.php
└── tests/
└── GoogleTranslateTest.php
SYMBOL INDEX (40 symbols across 6 files)
FILE: src/GoogleTranslate.php
class GoogleTranslate (line 9) | class GoogleTranslate
method __construct (line 17) | public function __construct(GoogleTranslateClient $client)
method detectLanguage (line 22) | public function detectLanguage($input): array
method detectLanguageBatch (line 41) | public function detectLanguageBatch(array $input): array
method translate (line 60) | public function translate($input, $from = null, $to = null, $format = ...
method justTranslate (line 86) | public function justTranslate(string $input, $from = null, $to = null)...
method translateBatch (line 103) | public function translateBatch(array $input, string $translateFrom, st...
method getAvailableTranslationsFor (line 126) | public function getAvailableTranslationsFor(string $languageCode): array
method unlessLanguageIs (line 134) | public function unlessLanguageIs(string $languageCode, string $input, ...
method sanitizeLanguageCode (line 153) | public function sanitizeLanguageCode(string $languageCode)
method validateInput (line 171) | protected function validateInput($input): void
FILE: src/GoogleTranslateClient.php
class GoogleTranslateClient (line 9) | class GoogleTranslateClient
method __construct (line 15) | public function __construct(array $config)
method detectLanguage (line 23) | public function detectLanguage(string $text)
method detectLanguageBatch (line 29) | public function detectLanguageBatch(array $input)
method translate (line 35) | public function translate(string $text, string $translateFrom, string ...
method translateBatch (line 41) | public function translateBatch(array $input, string $translateFrom, st...
method getAvailableTranslationsFor (line 47) | public function getAvailableTranslationsFor(string $languageCode)
method checkForInvalidConfiguration (line 53) | private function checkForInvalidConfiguration(array $config)
FILE: src/GoogleTranslateFacade.php
class GoogleTranslateFacade (line 10) | class GoogleTranslateFacade extends Facade
method getFacadeAccessor (line 12) | protected static function getFacadeAccessor()
FILE: src/GoogleTranslateServiceProvider.php
class GoogleTranslateServiceProvider (line 8) | class GoogleTranslateServiceProvider extends ServiceProvider
method boot (line 10) | public function boot()
method register (line 28) | public function register()
FILE: src/Traits/SupportedLanguages.php
type SupportedLanguages (line 5) | trait SupportedLanguages
method languages (line 7) | public function languages(): array
FILE: tests/GoogleTranslateTest.php
class GoogleTranslateTest (line 11) | class GoogleTranslateTest extends BaseTestCase
method __construct (line 20) | public function __construct()
method it_can_detect_the_language_of_string_passed_to_it (line 30) | public function it_can_detect_the_language_of_string_passed_to_it()
method it_can_detect_the_language_of_an_array_of_strings_passed_to_it (line 47) | public function it_can_detect_the_language_of_an_array_of_strings_pass...
method it_can_translate_the_string_passed_to_it (line 70) | public function it_can_translate_the_string_passed_to_it()
method it_can_translate_the_html_string_passed_to_it (line 88) | public function it_can_translate_the_html_string_passed_to_it()
method it_can_translate_an_array_of_strings_passed_to_it (line 106) | public function it_can_translate_an_array_of_strings_passed_to_it()
method test_the_just_translate_method_returns_just_the_translated_string (line 131) | public function test_the_just_translate_method_returns_just_the_transl...
method test_the_unless_language_is_method_does_not_translate_the_language_of_given_text_if_it_is_same_as_defined_in_that_method (line 144) | public function test_the_unless_language_is_method_does_not_translate_...
method test_the_unless_language_is_method_translates_the_language_of_given_text_only_if_it_is_same_as_defined_in_that_method (line 157) | public function test_the_unless_language_is_method_translates_the_lang...
method it_sanitizes_the_language_codes (line 180) | public function it_sanitizes_the_language_codes()
method it_validates_input_against_null_strings (line 203) | public function it_validates_input_against_null_strings()
method it_validates_input_against_null_strings_in_a_batch (line 211) | public function it_validates_input_against_null_strings_in_a_batch()
method it_validates_input_agaisnt_null_strings_when_detecting_a_language (line 218) | public function it_validates_input_agaisnt_null_strings_when_detecting...
Condensed preview — 15 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (36K chars).
[
{
"path": ".github/workflows/run-tests.yml",
"chars": 1132,
"preview": "name: \"Run Tests\"\n\non: [push, pull_request]\n\njobs:\n test:\n\n runs-on: ubuntu-latest\n strategy:\n fail-fast: tr"
},
{
"path": ".gitignore",
"chars": 83,
"preview": "/vendor\ncomposer.lock\n.DS_Store\nThumbs.db\nphpunit.xml\n/.idea\n.phpunit.result.cache\n"
},
{
"path": "CHANGELOG.md",
"chars": 2491,
"preview": "All the notable changes to the Laravel Google Translate package are documented in this file:\n\n## 9.0 (1-1-2023)\n- Change"
},
{
"path": "LICENSE.txt",
"chars": 1084,
"preview": "The MIT License (MIT)\n\nCopyright (c) Jogg Inc <info@jogg.co>\n\nPermission is hereby granted, free of charge, to any perso"
},
{
"path": "README.md",
"chars": 5960,
"preview": "# This package is no longer actively developed. [More details here/Call for maintainers](https://github.com/JoggApp/lara"
},
{
"path": "composer.json",
"chars": 1289,
"preview": "{\n \"name\": \"joggapp/laravel-google-translate\",\n \"description\": \"Laravel package for the Google Translate API\",\n "
},
{
"path": "config/googletranslate.php",
"chars": 1231,
"preview": "<?php\n\nreturn [\n /*\n |------------------------------------------------------------------------------------------"
},
{
"path": "google.md",
"chars": 863,
"preview": "- After logging in the Google Cloud Platform console you will need to enable the Cloud Translate API via the API Library"
},
{
"path": "phpunit.xml.dist",
"chars": 631,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<phpunit bootstrap=\"vendor/autoload.php\"\n colors=\"true\"\n convertE"
},
{
"path": "src/GoogleTranslate.php",
"chars": 5570,
"preview": "<?php\n\nnamespace JoggApp\\GoogleTranslate;\n\nuse Exception;\nuse InvalidArgumentException;\nuse JoggApp\\GoogleTranslate\\Trai"
},
{
"path": "src/GoogleTranslateClient.php",
"chars": 2175,
"preview": "<?php\n\nnamespace JoggApp\\GoogleTranslate;\n\nuse Exception;\nuse Google\\Cloud\\Translate\\V2\\TranslateClient;\nuse JoggApp\\Goo"
},
{
"path": "src/GoogleTranslateFacade.php",
"chars": 292,
"preview": "<?php\n\nnamespace JoggApp\\GoogleTranslate;\n\nuse Illuminate\\Support\\Facades\\Facade;\n\n/**\n * @see \\JoggApp\\GoogleTranslate\\"
},
{
"path": "src/GoogleTranslateServiceProvider.php",
"chars": 1367,
"preview": "<?php\n\nnamespace JoggApp\\GoogleTranslate;\n\nuse Illuminate\\Support\\Facades\\Blade;\nuse Illuminate\\Support\\ServiceProvider;"
},
{
"path": "src/Traits/SupportedLanguages.php",
"chars": 949,
"preview": "<?php\n\nnamespace JoggApp\\GoogleTranslate\\Traits;\n\ntrait SupportedLanguages\n{\n public function languages(): array\n "
},
{
"path": "tests/GoogleTranslateTest.php",
"chars": 8502,
"preview": "<?php\n\nnamespace JoggApp\\GoogleTranslate\\Tests;\n\nuse Illuminate\\Support\\Facades\\Config;\nuse JoggApp\\GoogleTranslate\\Goog"
}
]
About this extraction
This page contains the full source code of the JoggApp/laravel-google-translate GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 15 files (32.8 KB), approximately 8.4k tokens, and a symbol index with 40 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.