View source
<?php
namespace Drupal\livechat\Form;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Logger\RfcLogLevel;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Drupal\Component\Serialization\Json;
use Symfony\Component\DependencyInjection\ContainerInterface;
class LiveChatLicenseForm extends ConfigFormBase {
protected $httpClient;
public function __construct(ConfigFactoryInterface $config_factory, Client $http_client) {
parent::__construct($config_factory);
$this->httpClient = $http_client;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('config.factory'), $container
->get('http_client'));
}
public function getFormId() {
return 'livechat_license_form';
}
protected function getEditableConfigNames() {
return [
LIVECHAT_CONFIGURATION_NAME,
];
}
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this
->config(LIVECHAT_CONFIGURATION_NAME);
$form['account'] = [
'#type' => 'details',
'#open' => TRUE,
'#title' => $this
->t('Account details'),
];
$form['account']['login'] = [
'#type' => 'email',
'#title' => $this
->t('LiveChat login'),
'#description' => $this
->t('User account login: my@email.com'),
'#default_value' => $config
->get('livechat_login'),
'#required' => TRUE,
];
if (!empty($config
->get('livechat_login')) && !empty($config
->get('livechat_license'))) {
$form['account']['license_number'] = [
'#type' => 'textfield',
'#title' => $this
->t('License number'),
'#default_value' => $config
->get('livechat_license'),
'#required' => TRUE,
'#attributes' => [
'disabled' => 'disabled',
],
];
}
return parent::buildForm($form, $form_state);
}
public function validateForm(array &$form, FormStateInterface $form_state) {
$login = $form_state
->getValue('login');
if (!empty($login)) {
try {
$license_number_request = LIVECHAT_API_LICENSE_NUMBER . '/' . $login;
$response = $this->httpClient
->get($license_number_request);
$data = $response
->getBody()
->getContents();
if (!empty($data)) {
$json = Json::decode($data);
if (!empty($json['number'])) {
if (livechat_validate_license($json['number'])) {
$form_state
->setValue('license_number', $json['number']);
}
else {
$form_state
->setErrorByName('login', $this
->t('LiveChat license number is incorrect.'));
}
}
elseif (!empty($json['error'])) {
$form_state
->setErrorByName('login', $json['error']);
}
}
} catch (RequestException $e) {
watchdog_exception('LiveChat', $e, $e
->getMessage(), [], RfcLogLevel::ERROR, $license_number_request);
$form_state
->setErrorByName('login', $e
->getMessage());
}
}
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$values = $form_state
->getValues();
$this
->config(LIVECHAT_CONFIGURATION_NAME)
->set('livechat_login', $values['login'])
->set('livechat_license', $values['license_number'])
->save();
parent::submitForm($form, $form_state);
}
}