HEX
Server: LiteSpeed
System: Linux premium260.web-hosting.com 4.18.0-553.45.1.lve.el8.x86_64 #1 SMP Wed Mar 26 12:08:09 UTC 2025 x86_64
User: aliazzsr (627)
PHP: 7.4.33
Disabled: NONE
Upload Files
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);
    }
}