*/ private function parseDictReply(string $reply): array { $tmp = []; foreach (explode("\n", $reply) as $line) { list($code, $message) = explode(" ", $line, 2); if (!$code && $message) { array_push($tmp, $message); } } return $tmp; } public function handle(Request $request): Response { if (!Config::get(Config::DICT_SERVER)) { return (new Response())->withBody(json_encode(["result" => ["Dictionary lookups are disabled."]])); } $word = strip_tags(str_replace("­", "", $request->getAttribute('word'))); $origWord = $word; $result = []; for ($i = 0; $i < 3; $i++) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, sprintf("dict://%s/define:%s", Config::get(Config::DICT_SERVER), $word)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $dictReply = curl_exec($ch); if ($dictReply) { $retParsed = $this->parseDictReply($dictReply); if (count($retParsed) > 0) { array_push($result, "$word"); $result = array_merge($result, $retParsed); break; } else { $word = mb_substr($word, 0, mb_strlen($word) - 1); } } else { array_push($result, curl_error($ch)); } curl_close($ch); } if (count($result) == 0) { array_push($result, "No results for: $origWord"); } return (new Response())->withBody(json_encode(["result" => $result])); } }