View source
<?php
namespace Drupal\uc_store\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\PrivateKey;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
class PoweredByBlock extends BlockBase implements ContainerFactoryPluginInterface {
protected $routeMatch;
protected $privateKey;
public function __construct(array $configuration, $plugin_id, $plugin_definition, PrivateKey $private_key, RouteMatchInterface $route_match) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->privateKey = $private_key;
$this->routeMatch = $route_match;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('private_key'), $container
->get('current_route_match'));
}
public function getCacheMaxAge() {
return 0;
}
public function defaultConfiguration() {
return [
'label_display' => FALSE,
'message' => 0,
];
}
public function blockForm($form, FormStateInterface $form_state) {
$configuration = $this->configuration;
$form['message'] = [
'#type' => 'radios',
'#title' => $this
->t('Footer message for store pages'),
'#options' => array_merge([
0 => $this
->t('Randomly select a message from the list below.'),
], $this
->options()),
'#default_value' => isset($configuration['message']) ? $configuration['message'] : '',
'#weight' => 10,
];
return $form;
}
public function blockSubmit($form, FormStateInterface $form_state) {
$this->configuration['message'] = $form_state
->getValue('message');
}
public function build() {
$id = $this->configuration['message'];
$path = $this->routeMatch
->getRouteName();
$messages = $this
->options();
if ($id == 0) {
$private_key = $this->privateKey
->get();
$id = hexdec(substr(md5($path . $private_key), 0, 2)) % count($messages) + 1;
}
return [
'#markup' => $messages[$id],
];
}
protected function options() {
$url = [
':url' => Url::fromUri('https://www.drupal.org/project/ubercart')
->toString(),
];
return [
1 => $this
->t('<a href=":url">Powered by Ubercart</a>', $url),
2 => $this
->t('<a href=":url">Drupal e-commerce</a> provided by Ubercart.', $url),
3 => $this
->t('Supported by Ubercart, an <a href=":url">open source e-commerce suite</a>.', $url),
4 => $this
->t('Powered by Ubercart, the <a href=":url">free shopping cart software</a>.', $url),
];
}
protected function getRequiredCacheContexts() {
return [
'url',
];
}
}