Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- use Guzzle\Http\Client;
- class Driver {
- public $response;
- public $longitude;
- public $latitude;
- public $type;
- public $type_request = 'work';
- public $subtype;
- protected $request;
- protected $wanted;
- protected $search_string;
- protected $original_comment;
- protected $request_url;
- protected $service;
- private static $client;
- private $gibddServer;
- const SAVE_LOG = false;
- public function __construct($properties = null) {
- $this->gibddServer = Yii::app()->params['service']."/webresources/search/";
- $this->initRequest();
- $this->response = new stdClass();
- if(!empty($properties)) $this->setProperties($properties);
- if(empty(self::$client)) {
- self::$client = new Client($this->gibddServer);
- self::$client->setDefaultOption('headers', array('Content-Type' => 'application/json; charset=utf-8'));
- self::$client->setDefaultOption('timeout', 20);
- }
- }
- protected function showException(Exception $exception) {
- return '{"error": "Выброшено исключение: '.$exception->getMessage().'"}';
- }
- public function setProperties(array $properties) {
- foreach($properties as $name => $value) {
- $reflection = new ReflectionProperty(get_class($this), $name);
- if($reflection->isPublic()) $this->$name = $value;
- }
- }
- protected function initRequest() {
- $this->request = new stdClass();
- $this->request->client = new stdClass();
- $this->request->client->username = Yii::app()->user->login;
- $this->request->client->password = Yii::app()->user->password;
- $this->request->client->ogaiCode = Yii::app()->user->ogai_code;
- $this->request->client->ip = '11.0.0.1';
- $this->request->client->schema = 'GIBDD_APR';
- }
- // На основе поискового запроса получаем данные со внешнего сервера (GIBDD_SERVER)
- public function getData($request = array()) {
- foreach ($request as $property=>$value) {
- $this->request->$property = $value;
- }
- try {
- $result = self::$client->post($this->request_url, null, json_encode($this->request))->send();
- if(self::SAVE_LOG) {
- $log = new ServiceLog();
- $log->SERVICE = $this->service;
- $log->URL = $this->gibddServer .$this->request_url;
- $log->UPTIME = time();
- $log->ORIGINAL = $result->getBody();
- $log->CODE = $result->getStatusCode();
- $log->LOGIN = $this->request->client->username;
- $log->save();
- }
- return (object) $result->json();
- } catch (Exception $exception) {
- return $this->showException($exception);
- }
- }
- // Сопоставляем заполненным полям адреса значения из КЛАДР
- protected function loadKLADRData() {
- if(!isset($this->response->drivers)) return false;
- $fields = array('region', 'city', 'street'); // Названия субъектов адреса по КЛАДР, они же названия свойств
- foreach ($this->response->drivers as $key => $value) {
- $this->response->drivers[$key] = $value = (object) $value;
- foreach($fields as $field) {
- // Если сейчас ищем город или улицу, сужаем поиск по КЛАДР заранее найдённым идентификатором региона
- $region_id = ($field !== 'region') ? $this->response->drivers[$key]->region_kladr->short : null;
- // Если ищем улицу, то в дополнение к сужению поиска идентификатором региона, вводим дополнительный
- // фильтр по идентификатору города
- if ($field === 'street') {
- $city_id = $this->response->drivers[$key]->city_kladr->short;
- if(empty($region_id) and empty($city_id)) $region_id = 77; // регион по умолчанию
- } else {
- $city_id = null;
- }
- $this->response->drivers[$key]->{$field.'_kladr'} =
- isset($value->$field) ? KLADRNode::getKLADRData($value->$field, $field, $region_id, $city_id) : new KLADRNode();
- }
- }
- return true;
- }
- protected function setIsWanted() {
- if(!isset($this->response->drivers)) return false;
- foreach ($this->response->drivers as $value) {
- if (isset($value->wanted)) {
- foreach ($value->wanted as $wanted) {
- if(!isset($wanted->num_cirk_sr) || $wanted->num_cirk_sr == null) $this->wanted = true;
- }
- }
- }
- return true;
- }
- // Сохраняем данные в лог, $id - ключ соответствующей записи в логе поисковых запросов
- protected function logWanted() {
- if(!isset($this->response->drivers)) return false;
- foreach ($this->response->drivers as $value) {
- if (isset($value->wanted)) {
- foreach ($value->wanted as $wanted) {
- $query = 'INSERT INTO restraint ("sid", "restraint", "num_cirk_sr", "date_ust")
- VALUES (:sid, :restraint, :num_cirk_sr, :date_ust);';
- $command = Yii::app()->dbOracleData->createCommand($query);
- $command->bindParam(':cid', $this->response->id);
- $command->bindParam(':restraint', $wanted->restraint);
- $command->bindParam(':num_cirk_sr', $wanted->num_cirk_sr);
- $command->bindParam(':date_ust', $wanted->date_ust);
- $command->execute();
- };
- }
- }
- return true;
- }
- // Проверяем не вернул ли удалённый сервер ошибку, и если вернул,
- // выбираем соответствующее сообщение для ответа
- // $not_found - сообщение об ошибке для случая, когда по результатам поискового запроса
- // на удалённом сервере ничего не найдено
- protected function checkForResponseErrors($not_found, $check_vehicles = false) {
- // это значение будет сохранено в лог
- $this->original_comment = isset($this->response->responseComment) ? $this->response->responseComment : null;
- if(!isset($this->response->responseCode)) {
- if(!is_object($this->response)) $this->response = new stdClass();
- $this->response->responseComment = 'Нет соединения с базой. Повторите попытку позже.';
- $this->response->responseCode = 'ERROR';
- } else if($check_vehicles && (count($this->response->vehicles) == 0) && (count($this->response->wantedVehicles) == 0) && (count($this->response->wantedSP) == 0) && empty($this->response->responseComment)) {
- $this->response->responseComment = 'Ничего не найдено — нет информации в базе транспортных средств.';
- $this->response->responseCode = 'ERROR';
- } else if($this->response->responseCode === 'ERROR') {
- if($this->response->responseComment == '') {
- $this->response->responseComment = 'Неизвестная ошибка. Повторите попытку позже.';
- } else if(strstr($this->response->responseComment, 'Нарушение прав доступа по времени')) {
- $this->response->responseComment = 'Нарушение прав доступа по времени';
- } else if((strstr($this->response->responseComment, 'ORA') || strstr($this->response->responseComment, 'could not find program unit'))) {
- $this->response->responseComment = $not_found;
- }
- } else if($this->response->responseCode === 'OK') {
- $this->response->responseComment = null;
- }
- }
- // Сохраняем данные в лог поисковых запросов
- protected function log() {
- $log = new SearchLog();
- $id = $log->log(
- $this->search_string,
- Yii::app()->user->id,
- $this->request->client->ogaiCode,
- $this->type,
- $this->request->client->username,
- Yii::app()->user->imei,
- $this->request->client->ip,
- 'lite_nd', // $this->type_request,
- $this->subtype,
- isset($this->response->responseCode) ? $this->response->responseCode : '',
- $this->longitude,
- $this->latitude,
- $this->wanted,
- isset($this->response->responseComment) ? $this->response->responseComment : '',
- $this->original_comment
- );
- $this->response->id = $id;
- return $id;
- }
- public function getDataByLicense($license) {
- $this->subtype = 'driver_license';
- $this->type = 'Водительское удостоверение';
- $this->search_string = $license;
- $this->request_url = 'driver';
- $this->service = 'driver';
- $this->request->driverLicense = Yii::app()->utils->translit($license);
- $this->response = $this->getData();
- $this->loadKLADRData();
- $this->setIsWanted();
- $this->checkForResponseErrors('ВУ номер '.$this->request->driverLicense.' не найдено в базе. Проверьте введенные значения.');
- // Сохраняем общий лог поисковых запросов и лог по wanted
- if(self::SAVE_LOG) {
- $logId = $this->log();
- $this->logWanted();
- }
- $serviceLogWriter = new ServiceLogWriter();
- $serviceLogWriter->write((array)$this->request,(array)$this->response,__FUNCTION__,$logId);
- }
- public function getDataByFio($name, $surname, $year, $patronymic = '') {
- $this->subtype = 'fio';
- $this->type = 'Поиск по ФИО';
- $this->search_string = str_replace(" ", " ", $name . " " . $surname . " " . $patronymic . " " . $year);
- $this->request_url = 'driver';
- $this->service = 'driver/fio';
- $arguments = array(
- 'name'=>'Имя водителя не заполнено',
- 'surname'=>'Фамилия водителя не заполнена',
- 'year'=>'Год рождения водителя не заполнен',
- 'patronymic'=>''
- );
- $missing_arguments = false;
- foreach($arguments as $argument => $error) {
- ${$argument} = trim(${$argument});
- if(($argument!=='patronymic') && empty(${$argument})) {
- $this->response->responseCode = 'ERROR';
- $this->response->responseComment[] = $error;
- $missing_arguments = true;
- }
- ${$argument} = Yii::app()->utils->translit(${$argument});
- $this->request->$argument = ${$argument};
- }
- if(!$missing_arguments) {
- $date = strtotime($year);
- $this->request->year = date('Y', $date);
- $this->request->subdate = date('dm', $date);
- $this->response = $this->getData();
- $this->loadKLADRData();
- $this->setIsWanted();
- $this->checkForResponseErrors('Водитель с ФИО ' . $surname . ' ' . $name . ' ' . $patronymic . ', г.р. ' . $year . ' не найден в базе. Проверьте введенные значения.');
- }
- // Сохраняем общий лог поисковых запросов и лог по wanted
- if(self::SAVE_LOG) {
- $logId = $this->log();
- $this->logWanted();
- }
- $serviceLogWriter = new ServiceLogWriter();
- $serviceLogWriter->write((array)$this->request,(array)$this->response,__FUNCTION__,$logId);
- }
- public function getDataByCar($plate_number, $type = 'plate_number') {
- $this->search_string = Yii::app()->utils->translit($plate_number);
- $this->subtype = $type;
- $types = array('chassis_number' => 'nshasi', 'body_number' => 'nkuzov', 'engine_number' => 'nmotor');
- foreach($types as $key => $value) {
- if($this->subtype === $key) $this->subtype = $value;
- }
- $param_names = array(
- "plate_number" => "ГРЗ", "sts" => "СТС", "pts" => "ПТС",
- "vin" => "VIN", "nshasi" => "Номер шасси",
- "nkuzov" => "Номер кузова", "nmotor" => "Номер двигателя",
- "chassis_number" => "Номер шасси", "body_number" => "Номер кузова",
- "engine_number" => "Номер двигателя"
- );
- $request_types = array(
- 'vin' => 'vin',
- 'sts' => 'sts',
- 'pts' => "pts",
- 'nmotor' => 'engineNumber',
- 'nshasi' => 'chassisNumber',
- 'nkuzov' => 'bodyNumber',
- 'plate_number' => 'licensePlateNumber'
- );
- $is_plate_number = ($this->subtype === 'plate_number');
- $this->type = $is_plate_number ? 'Водительское удостоверение' : 'Спецпродукция «'.$param_names[$this->subtype].'»';
- $this->request_url = $this->service = $is_plate_number ? 'vehicle' : 'stealing';
- $this->request->$request_types[$this->subtype] = $this->search_string;
- $this->response = $this->getData();
- if(!isset($this->response->vehicles)) {
- if (empty($this->response)) {
- $this->response = new stdClass();
- }
- $this->response->vehicles = array();
- $this->response->vehicles[0] = new stdClass();
- }
- $this->checkForResponseErrors('ТС номер ('.$param_names[$this->subtype].') '.$this->search_string.' не найдено в базе. Проверьте правильность.', true);
- if(self::SAVE_LOG) {
- $logId = $this->log();
- }
- $serviceLogWriter = new ServiceLogWriter();
- $serviceLogWriter->write((array)$this->request,(array)$this->response,__FUNCTION__,$logId);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement