TawkToWidgetController.php in Tawk.to - Live chat application (Drupal 8) 8.2
File
src/Controller/TawkToWidgetController.php
View source
<?php
namespace Drupal\tawk_to\Controller;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\language\ConfigurableLanguageManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RequestStack;
class TawkToWidgetController extends ControllerBase {
const TAWK_TO_PLUGINS_URL = 'https://plugins.tawk.to';
protected $request;
protected $config;
protected $languageManager;
public function __construct(RequestStack $request, ConfigFactoryInterface $config, LanguageManagerInterface $language_manager) {
$this->request = $request;
$this->languageManager = $language_manager;
$currentLanguage = $this->languageManager
->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)
->getId();
$this->config = $config
->getEditable('tawk_to.settings');
if ($this->languageManager instanceof ConfigurableLanguageManagerInterface) {
$configOverride = $this->languageManager
->getLanguageConfigOverride($currentLanguage, 'tawk_to.settings');
if (!$configOverride
->isNew()) {
$this->config = $configOverride;
}
}
}
public static function create(ContainerInterface $container) {
return new static($container
->get('request_stack'), $container
->get('config.factory'), $container
->get('language_manager'));
}
private function tawkToGetIframeUrl() {
$pageId = $this->config
->get('tawk_to_widget_page_id');
$widgetId = $this->config
->get('tawk_to_widget_id');
return self::TAWK_TO_PLUGINS_URL . '/generic/widgets?currentWidgetId=' . $widgetId . '¤tPageId=' . $pageId;
}
public function widgetsContent() {
$items = [];
$items['baseUrl'] = self::TAWK_TO_PLUGINS_URL;
$items['iframeUrl'] = $this
->tawkToGetIframeUrl();
return [
'#theme' => 'tawk_to_iframe',
'#items' => $items,
];
}
public function setWidget() {
$pageId = $this->request
->getCurrentRequest()
->get('pageId');
$widgetId = $this->request
->getCurrentRequest()
->get('widgetId');
if (!$pageId || !$widgetId) {
return new JsonResponse([
'success' => FALSE,
]);
}
if (preg_match('/^[0-9A-Fa-f]{24}$/', $pageId) !== 1 || preg_match('/^[a-z0-9]{1,50}$/i', $widgetId) !== 1) {
return new JsonResponse([
'success' => FALSE,
]);
}
$this->config
->set('tawk_to_widget_page_id', $pageId)
->save();
$this->config
->set('tawk_to_widget_id', $widgetId)
->save();
return new JsonResponse([
'success' => TRUE,
]);
}
public function removeWidget() {
$this->config
->clear('tawk_to_widget_page_id')
->save();
$this->config
->clear('tawk_to_widget_id')
->save();
return new JsonResponse([
'success' => TRUE,
]);
}
}