Advertisement
daryast

Untitled

Apr 14th, 2017
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.92 KB | None | 0 0
  1. <?php
  2.  
  3. use Guzzle\Http\Client;
  4.  
  5. class Driver {
  6.  
  7. public $response;
  8.  
  9. public $longitude;
  10. public $latitude;
  11. public $type;
  12. public $type_request = 'work';
  13. public $subtype;
  14.  
  15. protected $request;
  16. protected $wanted;
  17. protected $search_string;
  18. protected $original_comment;
  19. protected $request_url;
  20. protected $service;
  21.  
  22. private static $client;
  23.  
  24. private $gibddServer;
  25.  
  26. const SAVE_LOG = false;
  27.  
  28. public function __construct($properties = null) {
  29.  
  30. $this->gibddServer = Yii::app()->params['service']."/webresources/search/";
  31. $this->initRequest();
  32. $this->response = new stdClass();
  33.  
  34. if(!empty($properties)) $this->setProperties($properties);
  35.  
  36. if(empty(self::$client)) {
  37.  
  38. self::$client = new Client($this->gibddServer);
  39. self::$client->setDefaultOption('headers', array('Content-Type' => 'application/json; charset=utf-8'));
  40. self::$client->setDefaultOption('timeout', 20);
  41.  
  42. }
  43.  
  44. }
  45.  
  46. protected function showException(Exception $exception) {
  47.  
  48. return '{"error": "Выброшено исключение: '.$exception->getMessage().'"}';
  49.  
  50. }
  51.  
  52. public function setProperties(array $properties) {
  53.  
  54. foreach($properties as $name => $value) {
  55.  
  56. $reflection = new ReflectionProperty(get_class($this), $name);
  57. if($reflection->isPublic()) $this->$name = $value;
  58.  
  59. }
  60.  
  61. }
  62.  
  63. protected function initRequest() {
  64.  
  65. $this->request = new stdClass();
  66. $this->request->client = new stdClass();
  67.  
  68. $this->request->client->username = Yii::app()->user->login;
  69. $this->request->client->password = Yii::app()->user->password;
  70. $this->request->client->ogaiCode = Yii::app()->user->ogai_code;
  71. $this->request->client->ip = '11.0.0.1';
  72. $this->request->client->schema = 'GIBDD_APR';
  73.  
  74. }
  75.  
  76. // На основе поискового запроса получаем данные со внешнего сервера (GIBDD_SERVER)
  77.  
  78. public function getData($request = array()) {
  79.  
  80. foreach ($request as $property=>$value) {
  81. $this->request->$property = $value;
  82. }
  83.  
  84. try {
  85.  
  86. $result = self::$client->post($this->request_url, null, json_encode($this->request))->send();
  87.  
  88. if(self::SAVE_LOG) {
  89.  
  90. $log = new ServiceLog();
  91.  
  92. $log->SERVICE = $this->service;
  93. $log->URL = $this->gibddServer .$this->request_url;
  94. $log->UPTIME = time();
  95. $log->ORIGINAL = $result->getBody();
  96. $log->CODE = $result->getStatusCode();
  97. $log->LOGIN = $this->request->client->username;
  98.  
  99. $log->save();
  100.  
  101. }
  102.  
  103. return (object) $result->json();
  104.  
  105. } catch (Exception $exception) {
  106. return $this->showException($exception);
  107. }
  108.  
  109. }
  110.  
  111.  
  112. // Сопоставляем заполненным полям адреса значения из КЛАДР
  113.  
  114. protected function loadKLADRData() {
  115.  
  116. if(!isset($this->response->drivers)) return false;
  117.  
  118. $fields = array('region', 'city', 'street'); // Названия субъектов адреса по КЛАДР, они же названия свойств
  119.  
  120. foreach ($this->response->drivers as $key => $value) {
  121.  
  122. $this->response->drivers[$key] = $value = (object) $value;
  123.  
  124. foreach($fields as $field) {
  125.  
  126. // Если сейчас ищем город или улицу, сужаем поиск по КЛАДР заранее найдённым идентификатором региона
  127. $region_id = ($field !== 'region') ? $this->response->drivers[$key]->region_kladr->short : null;
  128.  
  129. // Если ищем улицу, то в дополнение к сужению поиска идентификатором региона, вводим дополнительный
  130. // фильтр по идентификатору города
  131. if ($field === 'street') {
  132.  
  133. $city_id = $this->response->drivers[$key]->city_kladr->short;
  134. if(empty($region_id) and empty($city_id)) $region_id = 77; // регион по умолчанию
  135.  
  136. } else {
  137.  
  138. $city_id = null;
  139.  
  140. }
  141.  
  142. $this->response->drivers[$key]->{$field.'_kladr'} =
  143. isset($value->$field) ? KLADRNode::getKLADRData($value->$field, $field, $region_id, $city_id) : new KLADRNode();
  144.  
  145. }
  146.  
  147. }
  148.  
  149. return true;
  150.  
  151. }
  152.  
  153. protected function setIsWanted() {
  154.  
  155. if(!isset($this->response->drivers)) return false;
  156.  
  157. foreach ($this->response->drivers as $value) {
  158. if (isset($value->wanted)) {
  159. foreach ($value->wanted as $wanted) {
  160. if(!isset($wanted->num_cirk_sr) || $wanted->num_cirk_sr == null) $this->wanted = true;
  161. }
  162. }
  163. }
  164.  
  165. return true;
  166.  
  167. }
  168.  
  169. // Сохраняем данные в лог, $id - ключ соответствующей записи в логе поисковых запросов
  170.  
  171. protected function logWanted() {
  172.  
  173. if(!isset($this->response->drivers)) return false;
  174.  
  175. foreach ($this->response->drivers as $value) {
  176. if (isset($value->wanted)) {
  177. foreach ($value->wanted as $wanted) {
  178.  
  179. $query = 'INSERT INTO restraint ("sid", "restraint", "num_cirk_sr", "date_ust")
  180. VALUES (:sid, :restraint, :num_cirk_sr, :date_ust);';
  181.  
  182. $command = Yii::app()->dbOracleData->createCommand($query);
  183. $command->bindParam(':cid', $this->response->id);
  184. $command->bindParam(':restraint', $wanted->restraint);
  185. $command->bindParam(':num_cirk_sr', $wanted->num_cirk_sr);
  186. $command->bindParam(':date_ust', $wanted->date_ust);
  187.  
  188. $command->execute();
  189.  
  190. };
  191.  
  192. }
  193. }
  194.  
  195. return true;
  196.  
  197. }
  198.  
  199.  
  200. // Проверяем не вернул ли удалённый сервер ошибку, и если вернул,
  201. // выбираем соответствующее сообщение для ответа
  202. // $not_found - сообщение об ошибке для случая, когда по результатам поискового запроса
  203. // на удалённом сервере ничего не найдено
  204.  
  205. protected function checkForResponseErrors($not_found, $check_vehicles = false) {
  206.  
  207. // это значение будет сохранено в лог
  208. $this->original_comment = isset($this->response->responseComment) ? $this->response->responseComment : null;
  209.  
  210. if(!isset($this->response->responseCode)) {
  211.  
  212. if(!is_object($this->response)) $this->response = new stdClass();
  213.  
  214. $this->response->responseComment = 'Нет соединения с базой. Повторите попытку позже.';
  215. $this->response->responseCode = 'ERROR';
  216.  
  217. } else if($check_vehicles && (count($this->response->vehicles) == 0) && (count($this->response->wantedVehicles) == 0) && (count($this->response->wantedSP) == 0) && empty($this->response->responseComment)) {
  218.  
  219. $this->response->responseComment = 'Ничего не найдено — нет информации в базе транспортных средств.';
  220. $this->response->responseCode = 'ERROR';
  221.  
  222. } else if($this->response->responseCode === 'ERROR') {
  223.  
  224. if($this->response->responseComment == '') {
  225.  
  226. $this->response->responseComment = 'Неизвестная ошибка. Повторите попытку позже.';
  227.  
  228. } else if(strstr($this->response->responseComment, 'Нарушение прав доступа по времени')) {
  229.  
  230. $this->response->responseComment = 'Нарушение прав доступа по времени';
  231.  
  232. } else if((strstr($this->response->responseComment, 'ORA') || strstr($this->response->responseComment, 'could not find program unit'))) {
  233.  
  234. $this->response->responseComment = $not_found;
  235.  
  236. }
  237.  
  238. } else if($this->response->responseCode === 'OK') {
  239. $this->response->responseComment = null;
  240. }
  241.  
  242. }
  243.  
  244. // Сохраняем данные в лог поисковых запросов
  245. protected function log() {
  246.  
  247. $log = new SearchLog();
  248. $id = $log->log(
  249. $this->search_string,
  250. Yii::app()->user->id,
  251. $this->request->client->ogaiCode,
  252. $this->type,
  253. $this->request->client->username,
  254. Yii::app()->user->imei,
  255. $this->request->client->ip,
  256. 'lite_nd', // $this->type_request,
  257. $this->subtype,
  258. isset($this->response->responseCode) ? $this->response->responseCode : '',
  259. $this->longitude,
  260. $this->latitude,
  261. $this->wanted,
  262. isset($this->response->responseComment) ? $this->response->responseComment : '',
  263. $this->original_comment
  264. );
  265.  
  266. $this->response->id = $id;
  267. return $id;
  268.  
  269. }
  270.  
  271. public function getDataByLicense($license) {
  272.  
  273. $this->subtype = 'driver_license';
  274. $this->type = 'Водительское удостоверение';
  275. $this->search_string = $license;
  276. $this->request_url = 'driver';
  277. $this->service = 'driver';
  278.  
  279. $this->request->driverLicense = Yii::app()->utils->translit($license);
  280.  
  281. $this->response = $this->getData();
  282.  
  283. $this->loadKLADRData();
  284. $this->setIsWanted();
  285. $this->checkForResponseErrors('ВУ номер '.$this->request->driverLicense.' не найдено в базе. Проверьте введенные значения.');
  286.  
  287. // Сохраняем общий лог поисковых запросов и лог по wanted
  288. if(self::SAVE_LOG) {
  289.  
  290. $logId = $this->log();
  291. $this->logWanted();
  292.  
  293. }
  294.  
  295. $serviceLogWriter = new ServiceLogWriter();
  296. $serviceLogWriter->write((array)$this->request,(array)$this->response,__FUNCTION__,$logId);
  297.  
  298. }
  299.  
  300. public function getDataByFio($name, $surname, $year, $patronymic = '') {
  301.  
  302. $this->subtype = 'fio';
  303. $this->type = 'Поиск по ФИО';
  304. $this->search_string = str_replace(" ", " ", $name . " " . $surname . " " . $patronymic . " " . $year);
  305. $this->request_url = 'driver';
  306. $this->service = 'driver/fio';
  307.  
  308. $arguments = array(
  309. 'name'=>'Имя водителя не заполнено',
  310. 'surname'=>'Фамилия водителя не заполнена',
  311. 'year'=>'Год рождения водителя не заполнен',
  312. 'patronymic'=>''
  313. );
  314.  
  315. $missing_arguments = false;
  316.  
  317. foreach($arguments as $argument => $error) {
  318.  
  319. ${$argument} = trim(${$argument});
  320.  
  321. if(($argument!=='patronymic') && empty(${$argument})) {
  322.  
  323. $this->response->responseCode = 'ERROR';
  324. $this->response->responseComment[] = $error;
  325. $missing_arguments = true;
  326.  
  327. }
  328.  
  329. ${$argument} = Yii::app()->utils->translit(${$argument});
  330. $this->request->$argument = ${$argument};
  331.  
  332. }
  333.  
  334. if(!$missing_arguments) {
  335.  
  336. $date = strtotime($year);
  337.  
  338. $this->request->year = date('Y', $date);
  339. $this->request->subdate = date('dm', $date);
  340. $this->response = $this->getData();
  341.  
  342. $this->loadKLADRData();
  343. $this->setIsWanted();
  344. $this->checkForResponseErrors('Водитель с ФИО ' . $surname . ' ' . $name . ' ' . $patronymic . ', г.р. ' . $year . ' не найден в базе. Проверьте введенные значения.');
  345.  
  346. }
  347.  
  348. // Сохраняем общий лог поисковых запросов и лог по wanted
  349. if(self::SAVE_LOG) {
  350.  
  351. $logId = $this->log();
  352. $this->logWanted();
  353.  
  354. }
  355.  
  356. $serviceLogWriter = new ServiceLogWriter();
  357. $serviceLogWriter->write((array)$this->request,(array)$this->response,__FUNCTION__,$logId);
  358. }
  359.  
  360. public function getDataByCar($plate_number, $type = 'plate_number') {
  361.  
  362. $this->search_string = Yii::app()->utils->translit($plate_number);
  363. $this->subtype = $type;
  364.  
  365. $types = array('chassis_number' => 'nshasi', 'body_number' => 'nkuzov', 'engine_number' => 'nmotor');
  366.  
  367. foreach($types as $key => $value) {
  368. if($this->subtype === $key) $this->subtype = $value;
  369. }
  370.  
  371. $param_names = array(
  372. "plate_number" => "ГРЗ", "sts" => "СТС", "pts" => "ПТС",
  373. "vin" => "VIN", "nshasi" => "Номер шасси",
  374. "nkuzov" => "Номер кузова", "nmotor" => "Номер двигателя",
  375. "chassis_number" => "Номер шасси", "body_number" => "Номер кузова",
  376. "engine_number" => "Номер двигателя"
  377. );
  378.  
  379. $request_types = array(
  380. 'vin' => 'vin',
  381. 'sts' => 'sts',
  382. 'pts' => "pts",
  383. 'nmotor' => 'engineNumber',
  384. 'nshasi' => 'chassisNumber',
  385. 'nkuzov' => 'bodyNumber',
  386. 'plate_number' => 'licensePlateNumber'
  387. );
  388.  
  389. $is_plate_number = ($this->subtype === 'plate_number');
  390.  
  391. $this->type = $is_plate_number ? 'Водительское удостоверение' : 'Спецпродукция «'.$param_names[$this->subtype].'»';
  392. $this->request_url = $this->service = $is_plate_number ? 'vehicle' : 'stealing';
  393. $this->request->$request_types[$this->subtype] = $this->search_string;
  394. $this->response = $this->getData();
  395.  
  396. if(!isset($this->response->vehicles)) {
  397.  
  398. if (empty($this->response)) {
  399. $this->response = new stdClass();
  400. }
  401.  
  402. $this->response->vehicles = array();
  403. $this->response->vehicles[0] = new stdClass();
  404.  
  405. }
  406.  
  407. $this->checkForResponseErrors('ТС номер ('.$param_names[$this->subtype].') '.$this->search_string.' не найдено в базе. Проверьте правильность.', true);
  408.  
  409. if(self::SAVE_LOG) {
  410.  
  411. $logId = $this->log();
  412.  
  413. }
  414.  
  415. $serviceLogWriter = new ServiceLogWriter();
  416. $serviceLogWriter->write((array)$this->request,(array)$this->response,__FUNCTION__,$logId);
  417. }
  418. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement