Complex classes like TranslateClient often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use TranslateClient, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 29 | class TranslateClient |
||
| 30 | { |
||
| 31 | /** |
||
| 32 | * @var TranslateClient Because nobody cares about singletons |
||
| 33 | */ |
||
| 34 | private static $staticInstance; |
||
| 35 | |||
| 36 | /** |
||
| 37 | * @var \GuzzleHttp\Client HTTP Client |
||
| 38 | */ |
||
| 39 | private $httpClient; |
||
| 40 | |||
| 41 | /** |
||
| 42 | * @var string Source language - from where the string should be translated |
||
| 43 | */ |
||
| 44 | private $sourceLanguage; |
||
| 45 | |||
| 46 | /** |
||
| 47 | * @var string Target language - to which language string should be translated |
||
| 48 | */ |
||
| 49 | private $targetLanguage; |
||
| 50 | |||
| 51 | /** |
||
| 52 | * @var string|bool Last detected source language |
||
| 53 | */ |
||
| 54 | private static $lastDetectedSource; |
||
| 55 | |||
| 56 | /** |
||
| 57 | * @var string Google Translate URL base |
||
| 58 | */ |
||
| 59 | private $urlBase = 'http://translate.google.com/translate_a/single'; |
||
| 60 | |||
| 61 | /** |
||
| 62 | * @var array Dynamic guzzleHTTP client options |
||
| 63 | */ |
||
| 64 | private $httpOptions = []; |
||
| 65 | |||
| 66 | /** |
||
| 67 | * @var array URL Parameters |
||
| 68 | */ |
||
| 69 | private $urlParams = [ |
||
| 70 | 'client' => 't', |
||
| 71 | 'hl' => 'en', |
||
| 72 | 'dt' => 't', |
||
| 73 | 'sl' => null, // Source language |
||
| 74 | 'tl' => null, // Target language |
||
| 75 | 'q' => null, // String to translate |
||
| 76 | 'ie' => 'UTF-8', // Input encoding |
||
| 77 | 'oe' => 'UTF-8', // Output encoding |
||
| 78 | 'multires' => 1, |
||
| 79 | 'otf' => 0, |
||
| 80 | 'pc' => 1, |
||
| 81 | 'trs' => 1, |
||
| 82 | 'ssel' => 0, |
||
| 83 | 'tsel' => 0, |
||
| 84 | 'kc' => 1, |
||
| 85 | 'tk' => null, |
||
| 86 | ]; |
||
| 87 | |||
| 88 | /** |
||
| 89 | * @var array Regex key-value patterns to replace on response data |
||
| 90 | */ |
||
| 91 | private $resultRegexes = [ |
||
| 92 | '/,+/' => ',', |
||
| 93 | '/\[,/' => '[', |
||
| 94 | ]; |
||
| 95 | |||
| 96 | /** |
||
| 97 | * @var TokenProviderInterface |
||
| 98 | */ |
||
| 99 | private $tokenProvider; |
||
| 100 | |||
| 101 | /** |
||
| 102 | * @var string Default token generator class name |
||
| 103 | */ |
||
| 104 | private $defaultTokenProvider = GoogleTokenGenerator::class; |
||
| 105 | |||
| 106 | /** |
||
| 107 | * Class constructor. |
||
| 108 | * |
||
| 109 | * For more information about HTTP client configuration options, visit |
||
| 110 | * "Creating a client" section of GuzzleHttp docs. |
||
| 111 | * 5.x - http://guzzle.readthedocs.org/en/5.3/clients.html#creating-a-client |
||
| 112 | * |
||
| 113 | * @param string $source Source language (Optional) |
||
| 114 | * @param string $target Target language (Optional) |
||
| 115 | * @param array $options Associative array of http client configuration options (Optional) |
||
| 116 | * |
||
| 117 | * @throws Exception If token provider does not implement TokenProviderInterface |
||
| 118 | */ |
||
| 119 | public function __construct($source = null, $target = 'en', $options = [], TokenProviderInterface $tokener = null) |
||
| 137 | |||
| 138 | /** |
||
| 139 | * Override translate method for static call. |
||
| 140 | * |
||
| 141 | * @throws BadMethodCallException If calling nonexistent method |
||
| 142 | * @throws InvalidArgumentException If parameters are passed incorrectly |
||
| 143 | * @throws InvalidArgumentException If the provided argument is not of type 'string' |
||
| 144 | * @throws ErrorException If the HTTP request fails |
||
| 145 | * @throws UnexpectedValueException If received data cannot be decoded |
||
| 146 | */ |
||
| 147 | public static function __callStatic($name, $args) |
||
| 167 | |||
| 168 | /** |
||
| 169 | * Override translate method for instance call. |
||
| 170 | * |
||
| 171 | * @throws BadMethodCallException If calling nonexistent method |
||
| 172 | * @throws InvalidArgumentException If parameters are passed incorrectly |
||
| 173 | * @throws InvalidArgumentException If the provided argument is not of type 'string' |
||
| 174 | * @throws ErrorException If the HTTP request fails |
||
| 175 | * @throws UnexpectedValueException If received data cannot be decoded |
||
| 176 | */ |
||
| 177 | public function __call($name, $args) |
||
| 200 | |||
| 201 | /** |
||
| 202 | * Check if static instance exists and instantiate if not. |
||
| 203 | * |
||
| 204 | * @return void |
||
| 205 | */ |
||
| 206 | private static function checkStaticInstance() |
||
| 212 | |||
| 213 | /** |
||
| 214 | * Set source language we are transleting from. |
||
| 215 | * |
||
| 216 | * @param string $source Language code |
||
| 217 | * |
||
| 218 | * @return TranslateClient |
||
| 219 | */ |
||
| 220 | public function setSource($source = null) |
||
| 226 | |||
| 227 | /** |
||
| 228 | * Set translation language we are transleting to. |
||
| 229 | * |
||
| 230 | * @param string $target Language code |
||
| 231 | * |
||
| 232 | * @return TranslateClient |
||
| 233 | */ |
||
| 234 | public function setTarget($target) |
||
| 240 | |||
| 241 | /** |
||
| 242 | * Set guzzleHttp client options. |
||
| 243 | * |
||
| 244 | * @param array $options guzzleHttp client options. |
||
| 245 | * |
||
| 246 | * @return TranslateClient |
||
| 247 | */ |
||
| 248 | public function setHttpOption(array $options) |
||
| 254 | |||
| 255 | /** |
||
| 256 | * Get response array. |
||
| 257 | * |
||
| 258 | * @param string|array $data String or array of strings to translate |
||
| 259 | * |
||
| 260 | * @throws InvalidArgumentException If the provided argument is not of type 'string' |
||
| 261 | * @throws ErrorException If the HTTP request fails |
||
| 262 | * @throws UnexpectedValueException If received data cannot be decoded |
||
| 263 | * |
||
| 264 | * @return array Response |
||
| 265 | */ |
||
| 266 | private function getResponse($data) |
||
| 267 | { |
||
| 268 | if (!is_string($data) && !is_array($data)) { |
||
| 269 | throw new InvalidArgumentException('Invalid argument provided'); |
||
| 270 | } |
||
| 271 | |||
| 272 | $data = is_array($data) ? implode(' \ ~ \ ~ ', $data) : $data; |
||
| 273 | $tokenData = is_array($data) ? implode('', $data) : $data; |
||
| 274 | |||
| 275 | $queryArray = array_merge($this->urlParams, [ |
||
| 276 | 'text' => $data, |
||
| 277 | 'sl' => $this->sourceLanguage, |
||
| 278 | 'tl' => $this->targetLanguage, |
||
| 279 | 'tk' => $this->tokenProvider->generateToken($this->sourceLanguage, $this->targetLanguage, $tokenData), |
||
| 280 | ]); |
||
| 281 | |||
| 282 | $queryUrl = preg_replace('/%5B(?:[0-9]|[1-9][0-9]+)%5D=/', '=', http_build_query($queryArray)); |
||
| 283 | |||
| 284 | try { |
||
| 285 | $response = $this->httpClient->post($this->urlBase, ['body' => $queryUrl] + $this->httpOptions); |
||
| 286 | } catch (GuzzleRequestException $e) { |
||
| 287 | throw new ErrorException($e->getMessage()); |
||
| 288 | } |
||
| 289 | |||
| 290 | $body = $response->getBody(); // Get response body |
||
| 291 | |||
| 292 | // Modify body to avoid json errors |
||
| 293 | $bodyJson = preg_replace(array_keys($this->resultRegexes), array_values($this->resultRegexes), $body); |
||
| 294 | |||
| 295 | // Decode JSON data |
||
| 296 | if (($bodyArray = json_decode($bodyJson, true)) === null) { |
||
| 297 | throw new UnexpectedValueException('Data cannot be decoded or it\'s deeper than the recursion limit'); |
||
| 298 | } |
||
| 299 | |||
| 300 | return $bodyArray; |
||
| 301 | } |
||
| 302 | |||
| 303 | /** |
||
| 304 | * Translate text. |
||
| 305 | * |
||
| 306 | * This can be called from instance method translate() using __call() magic method. |
||
| 307 | * Use $instance->translate($string) instead. |
||
| 308 | * |
||
| 309 | * @param string|array $data Text or array of texts to translate |
||
| 310 | * |
||
| 311 | * @throws InvalidArgumentException If the provided argument is not of type 'string' |
||
| 312 | * @throws ErrorException If the HTTP request fails |
||
| 313 | * @throws UnexpectedValueException If received data cannot be decoded |
||
| 314 | * |
||
| 315 | * @return string|bool Translated text |
||
| 316 | */ |
||
| 317 | private function instanceTranslate($data) |
||
| 318 | { |
||
| 319 | // Whether or not is the data an array |
||
| 320 | $isArray = is_array($data); |
||
| 321 | |||
| 322 | // Rethrow exceptions |
||
| 323 | try { |
||
| 324 | $responseArray = $this->getResponse($data); |
||
| 325 | } catch (Exception $e) { |
||
| 326 | throw $e; |
||
| 327 | } |
||
| 328 | |||
| 329 | // if response in text and the content has zero the empty returns true, lets check |
||
| 330 | // if response is string and not empty and create array for further logic |
||
| 331 | if (is_string($responseArray) && $responseArray != '') { |
||
| 332 | $responseArray = [$responseArray]; |
||
| 333 | } |
||
| 334 | |||
| 335 | // Check if translation exists |
||
| 336 | if (!isset($responseArray[0]) || empty($responseArray[0])) { |
||
| 337 | return false; |
||
| 338 | } |
||
| 339 | |||
| 340 | // Detect languages |
||
| 341 | $detectedLanguages = []; |
||
| 342 | |||
| 343 | // Another case of detected language |
||
| 344 | if (isset($responseArray[count($responseArray) - 2][0][0])) { |
||
| 345 | $detectedLanguages[] = $responseArray[count($responseArray) - 2][0][0]; |
||
| 346 | } elseif (isset($responseArray[1])) { |
||
| 347 | + $detectedLanguages[] = $responseArray[1]; |
||
| 348 | } |
||
| 349 | |||
| 350 | // Set initial detected language to null |
||
| 351 | $this::$lastDetectedSource = false; |
||
| 352 | |||
| 353 | // Iterate and set last detected language |
||
| 354 | foreach ($detectedLanguages as $lang) { |
||
| 355 | if ($this->isValidLocale($lang)) { |
||
| 356 | $this::$lastDetectedSource = $lang; |
||
| 357 | break; |
||
| 358 | } |
||
| 359 | } |
||
| 360 | |||
| 361 | // Reduce array to generate translated sentenece |
||
| 362 | if ($isArray) { |
||
| 363 | $carry = []; |
||
| 364 | $tmpstr = ''; |
||
| 365 | $split = []; |
||
|
|
|||
| 366 | foreach ($responseArray[0] as $item) { |
||
| 367 | $tmpstr .= $item[0]; |
||
| 368 | if (strpos($tmpstr, ' \ ~ \ ~ ')) { |
||
| 369 | $split = explode(' \ ~ \ ~ ', $tmpstr); |
||
| 370 | $tmpstr = array_pop($split); |
||
| 371 | foreach ($split as $st) { |
||
| 372 | $carry[] = $st; |
||
| 373 | } |
||
| 374 | } |
||
| 375 | } |
||
| 376 | $carry[] = $tmpstr; |
||
| 377 | |||
| 378 | return $carry; |
||
| 379 | } |
||
| 380 | // the response can be sometimes an translated string. |
||
| 381 | elseif (is_string($responseArray)) { |
||
| 382 | return $responseArray; |
||
| 383 | } else { |
||
| 384 | if (is_array($responseArray[0])) { |
||
| 385 | return array_reduce($responseArray[0], function ($carry, $item) { |
||
| 386 | $carry .= $item[0]; |
||
| 387 | |||
| 388 | return $carry; |
||
| 389 | }); |
||
| 390 | } else { |
||
| 391 | return $responseArray[0]; |
||
| 392 | } |
||
| 393 | } |
||
| 394 | } |
||
| 395 | |||
| 396 | /** |
||
| 397 | * Translate text statically. |
||
| 398 | * |
||
| 399 | * This can be called from static method translate() using __callStatic() magic method. |
||
| 400 | * Use TranslateClient::translate($source, $target, $string) instead. |
||
| 401 | * |
||
| 402 | * @param string $source Source language |
||
| 403 | * @param string $target Target language |
||
| 404 | * @param string $string Text to translate |
||
| 405 | * |
||
| 406 | * @throws InvalidArgumentException If the provided argument is not of type 'string' |
||
| 407 | * @throws ErrorException If the HTTP request fails |
||
| 408 | * @throws UnexpectedValueException If received data cannot be decoded |
||
| 409 | * |
||
| 410 | * @return string|bool Translated text |
||
| 411 | */ |
||
| 412 | private static function staticTranslate($source, $target, $string) |
||
| 426 | |||
| 427 | /** |
||
| 428 | * Get last detected language. |
||
| 429 | * |
||
| 430 | * @return string|bool Last detected language or boolean FALSE |
||
| 431 | */ |
||
| 432 | private static function staticGetLastDetectedSource() |
||
| 436 | |||
| 437 | /** |
||
| 438 | * Check if given locale is valid. |
||
| 439 | * |
||
| 440 | * @param string $lang Langauge code to verify |
||
| 441 | * |
||
| 442 | * @return bool |
||
| 443 | */ |
||
| 444 | private function isValidLocale($lang) |
||
| 448 | } |
||
| 449 |
This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.
Both the
$myVarassignment in line 1 and the$higherassignment in line 2 are dead. The first because$myVaris never used and the second because$higheris always overwritten for every possible time line.