[Задача 12794] Закончил и протестировал новый метод для отправки запроса на…

[Задача 12794] Закончил и протестировал новый метод для отправки запроса на исправление опечатки с использованием протокола json-rpc 2.0.
parent a0b22b96
<?php
require __DIR__ . "/../../../vendor/autoload.php";
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*Работа с опечатками - пользователь*/
......
<?php
use JsonRPC\Exception\AccessDeniedException;
use JsonRPC\Exception\ConnectionFailureException;
use JsonRPC\Exception\ServerErrorException;
if (!defined('BASEPATH'))
exit('No direct script access allowed');
......@@ -262,7 +266,7 @@ class Typo extends CI_Model {
}
if ( $data['status'] && $data["autoCorrection"] ) {
$this->correctTypo($data);
$this->correctTypo($data["id_message"], $data["corrected"]);
}
$this->db->set("status", $data['status']);
......@@ -309,66 +313,110 @@ class Typo extends CI_Model {
}
/**
* Отправляет запрос на исправление ошибки на сервер
* Отправляет запрос к клиентскому серверу на автоматическое
* исправление опечатки. Сервер клиента должен использовать
* библиотеку etersoft/typos_client.
* Сервер должен быть доступен на хосте клиента по пути  
* $this->config->item("correction_path").
*
* @param $data array Информация об опечатке
* @param int $typoId Идентификатор опечатки
* @param string $corrected Исправленный вариант
* @throws Exception Если произошла ошибка
*/
function correctTypo($data) {
function correctTypo(int $typoId, string $corrected) {
$correctPath = $this->config->item("correction_path");
$authToken = $this->config->item("typos_password");
$username = $this->config->item("typos_user");
/* Получаем исправление */
$this->db->select("m.link as link, m.text as text, m.comment as comment");
$this->db->select("m.link as link, m.text as text, m.comment as comment, m.context as context");
$this->db->from("messages as m");
$this->db->where("m.id", $data["id_message"]);
$this->db->where("m.id", $typoId);
$correction = $this->db->get()->row();
/* Получаем адрес необходимого сайта */
$parsed_url = parse_url($correction->link);
// Адрес на который шлем запрос исправления
$url = $parsed_url["scheme"] . "://" . $parsed_url["host"] . "/" . $correctPath;
/* Посылаем запрос с помощью cUrl */
$curl = curl_init($url);
curl_setopt_array($curl, array(
CURLOPT_USE_SSL => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_FAILONERROR => true,
CURLOPT_USERNAME => $username,
CURLOPT_PASSWORD => $authToken,
CURLOPT_POSTFIELDS => array(
'text' => $correction->text,
'corrected' => $data["corrected"],
'link' => $correction->link
),
));
log_message("debug", "sending request to $url");
log_message("debug", "corrected = {$data["corrected"]}");
if ( !($res = curl_exec($curl)) && curl_errno($curl) != 0 ) {
$errorCode = curl_errno($curl);
$errorText = curl_error($curl);
log_message("debug", "CorrectTypo errorCode: " . $errorCode);
log_message("debug", "CorrectTypo errorText: " . $errorText);
throw $this->getExceptionForCurlError($errorCode, $url);
try {
$client = new \JsonRPC\Client($url);
$client->getHttpClient()->withDebug();
$client->fixTypo($correction->text, $corrected, $correction->context, $correction->link);
} catch(ConnectionFailureException $e) {
throw new Exception("Не удалось подключиться к серверу исправления опечаток", 503);
} catch(AccessDeniedException $e) {
throw new Exception("Не удалось авторизироваться у сервера исправления опечаток", 401);
} catch(ServerErrorException $e) {
throw new Exception("Ошибка автоматического исправления опечатки на сервере", 500);
} catch(Exception $e) {
log_message("error", "Ошибка при исправлении опечатки: {$e->getMessage()}");
throw new Exception("Произошла неизвестная ошибка, попробуйте повторить попытку позже", 500);
}
log_message("debug", "response taken");
log_message("debug", "Response from $url: $res");
curl_close($curl);
}
/**
* Отправляет запрос на исправление ошибки на сервер
*
* @param $data array Информация об опечатке
* @throws Exception Если произошла ошибка
*/
// function correctTypo($data) {
// $correctPath = $this->config->item("correction_path");
// $authToken = $this->config->item("typos_password");
// $username = $this->config->item("typos_user");
//
// /* Получаем исправление */
// $this->db->select("m.link as link, m.text as text, m.comment as comment");
// $this->db->from("messages as m");
// $this->db->where("m.id", $data["id_message"]);
//
// $correction = $this->db->get()->row();
//
// /* Получаем адрес необходимого сайта */
// $parsed_url = parse_url($correction->link);
//
// // Адрес на который шлем запрос исправления
// $url = $parsed_url["scheme"] . "://" . $parsed_url["host"] . "/" . $correctPath;
//
// /* Посылаем запрос с помощью cUrl */
// $curl = curl_init($url);
//
// curl_setopt_array($curl, array(
// CURLOPT_USE_SSL => true,
// CURLOPT_RETURNTRANSFER => true,
// CURLOPT_POST => true,
// CURLOPT_FAILONERROR => true,
// CURLOPT_USERNAME => $username,
// CURLOPT_PASSWORD => $authToken,
// CURLOPT_POSTFIELDS => array(
// 'text' => $correction->text,
// 'corrected' => $data["corrected"],
// 'link' => $correction->link
// ),
// ));
//
// log_message("debug", "sending request to $url");
// log_message("debug", "corrected = {$data["corrected"]}");
//
// if ( !($res = curl_exec($curl)) && curl_errno($curl) != 0 ) {
// $errorCode = curl_errno($curl);
// $errorText = curl_error($curl);
//
// log_message("debug", "CorrectTypo errorCode: " . $errorCode);
// log_message("debug", "CorrectTypo errorText: " . $errorText);
//
// throw $this->getExceptionForCurlError($errorCode, $url);
// }
//
// log_message("debug", "response taken");
// log_message("debug", "Response from $url: $res");
//
// curl_close($curl);
// }
/**
* Создает исключение, которое описывает ошибку запроса curl
*
* @param $errorCode integer Код ошибки curl
......
......@@ -4,7 +4,8 @@
"type": "project",
"homepage": "https://etersoft.ru",
"require": {
"php": ">=5.2.4"
"php": ">=5.2.4",
"fguillot/json-rpc": "@stable"
},
"suggest": {
"paragonie/random_compat": "Provides better randomness in PHP 5.x"
......@@ -12,4 +13,4 @@
"require-dev": {
"mikey179/vfsStream": "1.1.*"
}
}
\ No newline at end of file
}
......@@ -4,9 +4,48 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
"This file is @generated automatically"
],
"hash": "d5d199cf81978ad090c9293bb48fe807",
"content-hash": "f2edfd91999a3e5fdab684e60b81d08b",
"packages": [],
"content-hash": "921458987087fb4d6736defd1e2c8055",
"packages": [
{
"name": "fguillot/json-rpc",
"version": "v1.2.5",
"source": {
"type": "git",
"url": "https://github.com/fguillot/JsonRPC.git",
"reference": "fa075cc89c1ae5f0c4123d27772e5caeac045946"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/fguillot/JsonRPC/zipball/fa075cc89c1ae5f0c4123d27772e5caeac045946",
"reference": "fa075cc89c1ae5f0c4123d27772e5caeac045946",
"shasum": ""
},
"require": {
"php": ">=5.3.4"
},
"require-dev": {
"phpunit/phpunit": "4.8.*"
},
"type": "library",
"autoload": {
"psr-0": {
"JsonRPC": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Frédéric Guillot"
}
],
"description": "Simple Json-RPC client/server library that just works",
"homepage": "https://github.com/fguillot/JsonRPC",
"time": "2018-02-21T23:58:51+00:00"
}
],
"packages-dev": [
{
"name": "mikey179/vfsStream",
......@@ -36,12 +75,14 @@
"BSD"
],
"homepage": "http://vfs.bovigo.org/",
"time": "2012-08-25 12:49:29"
"time": "2012-08-25T12:49:29+00:00"
}
],
"aliases": [],
"minimum-stability": "stable",
"stability-flags": [],
"stability-flags": {
"fguillot/json-rpc": 0
},
"prefer-stable": false,
"prefer-lowest": false,
"platform": {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment