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

[Задача 12794] Закончил и протестировал новый метод для отправки запроса на исправление опечатки с использованием протокола json-rpc 2.0.
parent a0b22b96
<?php <?php
require __DIR__ . "/../../../vendor/autoload.php";
if ( ! defined('BASEPATH')) exit('No direct script access allowed'); if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*Работа с опечатками - пользователь*/ /*Работа с опечатками - пользователь*/
......
<?php <?php
use JsonRPC\Exception\AccessDeniedException;
use JsonRPC\Exception\ConnectionFailureException;
use JsonRPC\Exception\ServerErrorException;
if (!defined('BASEPATH')) if (!defined('BASEPATH'))
exit('No direct script access allowed'); exit('No direct script access allowed');
...@@ -262,7 +266,7 @@ class Typo extends CI_Model { ...@@ -262,7 +266,7 @@ class Typo extends CI_Model {
} }
if ( $data['status'] && $data["autoCorrection"] ) { if ( $data['status'] && $data["autoCorrection"] ) {
$this->correctTypo($data); $this->correctTypo($data["id_message"], $data["corrected"]);
} }
$this->db->set("status", $data['status']); $this->db->set("status", $data['status']);
...@@ -309,66 +313,110 @@ class Typo extends CI_Model { ...@@ -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 Если произошла ошибка * @throws Exception Если произошла ошибка
*/ */
function correctTypo($data) { function correctTypo(int $typoId, string $corrected) {
$correctPath = $this->config->item("correction_path"); $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->from("messages as m");
$this->db->where("m.id", $data["id_message"]); $this->db->where("m.id", $typoId);
$correction = $this->db->get()->row(); $correction = $this->db->get()->row();
/* Получаем адрес необходимого сайта */ /* Получаем адрес необходимого сайта */
$parsed_url = parse_url($correction->link); $parsed_url = parse_url($correction->link);
// Адрес на который шлем запрос исправления // Адрес на который шлем запрос исправления
$url = $parsed_url["scheme"] . "://" . $parsed_url["host"] . "/" . $correctPath; $url = $parsed_url["scheme"] . "://" . $parsed_url["host"] . "/" . $correctPath;
/* Посылаем запрос с помощью cUrl */ try {
$curl = curl_init($url); $client = new \JsonRPC\Client($url);
$client->getHttpClient()->withDebug();
curl_setopt_array($curl, array(
CURLOPT_USE_SSL => true, $client->fixTypo($correction->text, $corrected, $correction->context, $correction->link);
CURLOPT_RETURNTRANSFER => true, } catch(ConnectionFailureException $e) {
CURLOPT_POST => true, throw new Exception("Не удалось подключиться к серверу исправления опечаток", 503);
CURLOPT_FAILONERROR => true, } catch(AccessDeniedException $e) {
CURLOPT_USERNAME => $username, throw new Exception("Не удалось авторизироваться у сервера исправления опечаток", 401);
CURLOPT_PASSWORD => $authToken, } catch(ServerErrorException $e) {
CURLOPT_POSTFIELDS => array( throw new Exception("Ошибка автоматического исправления опечатки на сервере", 500);
'text' => $correction->text, } catch(Exception $e) {
'corrected' => $data["corrected"], log_message("error", "Ошибка при исправлении опечатки: {$e->getMessage()}");
'link' => $correction->link throw new Exception("Произошла неизвестная ошибка, попробуйте повторить попытку позже", 500);
),
));
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);
} }
/** /**
* Отправляет запрос на исправление ошибки на сервер
*
* @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 * Создает исключение, которое описывает ошибку запроса curl
* *
* @param $errorCode integer Код ошибки curl * @param $errorCode integer Код ошибки curl
......
...@@ -4,7 +4,8 @@ ...@@ -4,7 +4,8 @@
"type": "project", "type": "project",
"homepage": "https://etersoft.ru", "homepage": "https://etersoft.ru",
"require": { "require": {
"php": ">=5.2.4" "php": ">=5.2.4",
"fguillot/json-rpc": "@stable"
}, },
"suggest": { "suggest": {
"paragonie/random_compat": "Provides better randomness in PHP 5.x" "paragonie/random_compat": "Provides better randomness in PHP 5.x"
...@@ -12,4 +13,4 @@ ...@@ -12,4 +13,4 @@
"require-dev": { "require-dev": {
"mikey179/vfsStream": "1.1.*" "mikey179/vfsStream": "1.1.*"
} }
} }
\ No newline at end of file
...@@ -4,9 +4,48 @@ ...@@ -4,9 +4,48 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"hash": "d5d199cf81978ad090c9293bb48fe807", "content-hash": "921458987087fb4d6736defd1e2c8055",
"content-hash": "f2edfd91999a3e5fdab684e60b81d08b", "packages": [
"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": [ "packages-dev": [
{ {
"name": "mikey179/vfsStream", "name": "mikey179/vfsStream",
...@@ -36,12 +75,14 @@ ...@@ -36,12 +75,14 @@
"BSD" "BSD"
], ],
"homepage": "http://vfs.bovigo.org/", "homepage": "http://vfs.bovigo.org/",
"time": "2012-08-25 12:49:29" "time": "2012-08-25T12:49:29+00:00"
} }
], ],
"aliases": [], "aliases": [],
"minimum-stability": "stable", "minimum-stability": "stable",
"stability-flags": [], "stability-flags": {
"fguillot/json-rpc": 0
},
"prefer-stable": false, "prefer-stable": false,
"prefer-lowest": false, "prefer-lowest": false,
"platform": { "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