File: /home/aliazzsr/api.crm.vqode.com/components/SabreConnector.php
<?php
namespace app\components;
use app\models\UserIdentity;
use yii\base\Component;
use yii\base\InvalidConfigException;
use yii\httpclient\Client;
use yii\httpclient\Response;
class SabreConnector extends Component
{
public $host;
public $token;
const ACTION_UPDATE_USER = 'UPDATE_USER';
const ACTION_ADD_USER = 'ADD_USER';
/** @var Logger */
protected $_logger;
/**
* @inheritdoc
*/
public function init()
{
$this->_logger = \Yii::$app->logger;
if (!$this->host || !$this->_logger || !$this->token) {
throw new InvalidConfigException('Sabre service is not configured');
}
parent::init();
}
/**
* Sends the command to Sabre service
* @param array $command
* @throws \Exception
*/
protected function postCommand(array $command)
{
$request = (new Client())->createRequest();
$request->setMethod('POST');
$request->setHeaders(['Authorization' => $this->token]);
$request->setUrl($this->host);
$request->setData($command);
$request->setFormat(Client::FORMAT_JSON);
/** @var Response $response */
$response = $request->send();
if (!$response->isOk) {
$this->_logger->error('[Sabre Error] Command sent: ' . var_export($command, true));
$this->_logger->error('[Sabre Error] Response: (' . $response->getStatusCode() . ') ' . $response->getContent());
throw new \Exception('Sabre service synchronization error');
}
}
/**
* Updates user's details on Sabre service
* @param SabreUser $userDetails
* @throws \Exception
*/
public function updateUser(SabreUser $userDetails)
{
$command = [
'action' => self::ACTION_UPDATE_USER,
'user' => $userDetails->toArray(),
];
return $this->postCommand($command);
}
/**
* Creates a new user by the details on Sabre service
* @param SabreUser $userDetails
* @throws \Exception
*/
public function createUser(SabreUser $userDetails)
{
$command = [
'action' => self::ACTION_ADD_USER,
'user' => $userDetails->toArray(),
];
return $this->postCommand($command);
}
}