Stichoza / google-translate-php

🔤 Free Google Translate API PHP Package. Translates totally free of charge.
MIT License
1.82k stars 382 forks source link

feat: retrieve a list of supported languages #211

Closed a-drew closed 3 months ago

a-drew commented 3 months ago

Summary

This PR adds languages methods to let the package user retrieve a complete list of supported languages on Google Translate. It's implemented in the new languages, localizedLanguages and static langs methods, added tests for full coverage and updated the README accordingly.

Details

Why

I've noticed that it's common feature of the paid translation apis (google, amazon, deelp, bing/azure) so adding it here for parity seemed like a good idea. I also use this package as one of my api drivers while locally testing my translation tools, so bringing it inline with the other drivers benefits me personally.

Feel free to change or even dismiss this PR if you find it's not needed.

Implementation

There are 2 options for users to retrieve the languages:

localizedLanguages($target) lets users pull a list iso codes mapped to the name of the language displayed in the $target language.

(new GoogleTranslate)->localizedLanguages('en');
(new GoogleTranslate)->languages('en');
GoogleTranslate::langs('en');

// Output
[
    ...
    'en' => English', 
    'es' => 'Spanish', 
    'it' => 'Italian', 
    ...
]

While languages & the static langs still let you pass in a $target display language for the same result, they also let you skip the display language and return only the list of iso-639 language codes.

(new GoogleTranslate)->languages();

GoogleTranslate::langs()

// Output
[ 'ab', 'ace', 'ach', 'aa', 'af', 'sq', 'alz', ... ]

All of this works by crawling the mobile translate site with the language menu open, https://translate.google.com/m?mui=sl. I've opted to use the built-in php ext-dom with its DOMDocument and DOMXPath but another option could be the symfony/dow-crawler package. ext-dom seems like a pretty standard extension that is often bundled with php without the need to install anything with pecl or composer.

Testing

Stichoza commented 3 months ago

Thank you for your work! 🙌🏼 It's a very useful functionality. And thanks for including Georgian language in tests and readme ❤️

Is it possible to avoid @ error silencer for $dom->loadHTML($html);?

a-drew commented 3 months ago

@Stichoza yes we can drop the @.

I've removed the error suppression in my last commit and don't see anything in console. I had it earlier when calling DOMDocument::loadHTML statically, but the static call's been removed in 8.3, so I had to create an instance anyway.

also did a quick fix for the failing exception test. should be all 🟢 once you run the workflow again.

Stichoza commented 3 months ago

Merged, Thank you!

Also pushed new tag v5.2.0