View source
<?php
namespace Drupal\disqus\Plugin\Block;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\Component\Utility\Html;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Config\ImmutableConfig;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\disqus\DisqusCommentManager;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
abstract class DisqusBaseBlock extends BlockBase implements ContainerFactoryPluginInterface {
protected $currentUser;
protected $disqusManager;
protected $routeMatch;
protected $disqusConfig;
public function __construct(array $configuration, $plugin_id, $plugin_definition, RouteMatchInterface $route_match, DisqusCommentManager $disqus_manager, AccountInterface $current_user, ImmutableConfig $disqus_config) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->currentUser = $current_user;
$this->disqusManager = $disqus_manager;
$this->routeMatch = $route_match;
$this->disqusConfig = $disqus_config;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('current_route_match'), $container
->get('disqus.manager'), $container
->get('current_user'), $container
->get('config.factory')
->get('disqus.settings'));
}
public function defaultConfiguration() {
return [
'items' => 5,
];
}
public function blockForm($form, FormStateInterface $form_state) {
$form['disqus'] = [
'#type' => 'fieldset',
'#title' => $this
->t('Disqus settings'),
'#tree' => TRUE,
];
$form['disqus']['items'] = [
'#type' => 'select',
'#title' => $this
->t('Number of items to show'),
'#options' => [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
],
'#default_value' => $this->configuration['items'],
];
return $form;
}
public function blockSubmit($form, FormStateInterface $form_state) {
foreach ($form_state
->getValue('disqus') as $k => $v) {
$this->configuration[$k] = $v;
}
}
public function build() {
$function = $this
->functionId();
$url = Url::fromUri("//disqus.com/forums/{$this->disqusConfig->get('disqus_domain')}/{$function}.js", [
'external' => TRUE,
'query' => $this
->buildQuery(),
])
->toString();
return [
'widget' => [
'script_tag' => [
'#markup' => new FormattableMarkup('<script type="text/javascript" src="' . $url . '"></script>', []),
],
'#theme_wrappers' => [
'container',
],
'#attributes' => [
'id' => Html::getUniqueId('disqus-' . $function),
'class' => [
'dsq-widget',
],
],
],
];
}
protected abstract function functionId();
protected function buildQuery() {
return [
'domain' => $this->disqusConfig
->get('disqus_domain'),
'num_items' => $this->configuration['items'],
];
}
}