Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace App\Services;
- use ErrorException;
- use GuzzleHttp\Client;
- use GuzzleHttp\Exception\RequestException;
- class Translate
- {
- /**
- * @var Client HTTP Client
- */
- protected $client;
- /**
- * @var string|null Source language - from where the page should be translated
- */
- protected $source;
- /**
- * @var string Target language - to which language page should be translated
- */
- protected $target;
- /**
- * @var string Url what need to be translated
- */
- protected $url;
- const IFRAME_REGEX = '**some regex**';
- const URL_REGEX = '**some regex**';
- public function __construct(string $target = 'en', string $source = null)
- {
- $this->client = new Client();
- $this->setSource($source)
- ->setTarget($target);
- }
- public function setTarget(string $target) : self
- {
- $this->target = $target;
- return $this;
- }
- public function setSource(string $source = null) : self
- {
- $this->source = $source ?? 'auto';
- return $this;
- }
- public function setUrl(string $url) : self
- {
- $this->url = $url;
- return $this;
- }
- public function translate()
- {
- try {
- $response = $this->client->get(
- sprintf("example.com?hl=%s&sl=%s&u=%s",
- $this->target,
- $this->source,
- $this->url
- )
- );
- $body = $response->getBody();
- //Find iframe url
- preg_match(self::IFRAME_REGEX, $body, $matches);
- $iframeUrl = $matches[1];
- //Send request to iframe url
- $response = $this->client->get($iframeUrl);
- $body = $response->getBody();
- //Find translated page url
- preg_match(self::URL_REGEX, $body, $matches);
- $pageUrl = preg_replace('|&|', '&', $matches[1]);
- $response = $this->client->get($pageUrl);
- $body = $response->getBody();
- return $this->formatBody($body);
- } catch (RequestException $e) {
- throw new ErrorException($e->getMessage());
- }
- }
- private function formatBody(string $body)
- {
- return iconv("Windows-1251", "UTF-8", $body);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement