|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Aurolieen; |
| 4 | + |
| 5 | +use GuzzleHttp\Client; |
| 6 | + |
| 7 | +/** |
| 8 | + * Assessment 3. Thesaurus |
| 9 | + * |
| 10 | + * @note The assessment did not specify any restraints on whether or not the dictionary actually contains any words |
| 11 | + * besides the ones provided as examples. So returning an empty list of synonyms for pretty much every word would have |
| 12 | + * been the optimal solution. However, in the spirit of the puzzle I decided against this and used the Datamuse API to |
| 13 | + * actually obtain real synonyms for the input words should they exist. |
| 14 | + * |
| 15 | + * Class Thesaurus |
| 16 | + * @package Aurolieen |
| 17 | + */ |
| 18 | +class Thesaurus |
| 19 | +{ |
| 20 | + /** |
| 21 | + * Obtains all synonyms for the provided word if any exist and outputs the result in JSON format. |
| 22 | + * Only works for words in the English language. |
| 23 | + * |
| 24 | + * @param string $word The word for which to obtain the synonyms. |
| 25 | + * @return string A JSON formatted string of the following layout: |
| 26 | + * { "word":<input>, "synonyms":[...] } |
| 27 | + */ |
| 28 | + public function getSynonyms($word) |
| 29 | + { |
| 30 | + $output = [ |
| 31 | + 'word' => $word, |
| 32 | + 'synonyms' => [] |
| 33 | + ]; |
| 34 | + if (is_string($word) && strlen($word) > 0) { |
| 35 | + $synonyms = $this->getSynonymsFromDatamuseAPI($word); |
| 36 | + $output['synonyms'] = $synonyms; |
| 37 | + } |
| 38 | + return json_encode($output); |
| 39 | + } |
| 40 | + |
| 41 | + /** |
| 42 | + * Queries the Datamuse API to obtain synonyms for words in the English language. |
| 43 | + * |
| 44 | + * @link https://www.datamuse.com/api/ |
| 45 | + * @param string $word The word for which to obtain the synonyms. |
| 46 | + * @return array Returns a list of strings that are synonyms of the input. |
| 47 | + */ |
| 48 | + protected function getSynonymsFromDatamuseAPI($word) |
| 49 | + { |
| 50 | + $client = new Client(); |
| 51 | + $options = [ |
| 52 | + 'timeout' => 5, |
| 53 | + 'headers' => [ |
| 54 | + 'Accept' => 'application/json', |
| 55 | + 'Content-Type' => 'application/json' |
| 56 | + ] |
| 57 | + ]; |
| 58 | + $response = $client->get( |
| 59 | + sprintf('https://api.datamuse.com/words?rel_syn=%s', rawurlencode($word)), |
| 60 | + $options); |
| 61 | + if ($response->getStatusCode() !== 200) return []; |
| 62 | + $decoded = json_decode($response->getBody()); |
| 63 | + if (empty($decoded)) return []; |
| 64 | + return array_column($decoded, 'word'); |
| 65 | + } |
| 66 | +} |
0 commit comments