BlockPluginTrait.php 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. <?php
  2. namespace Drupal\Core\Block;
  3. use Drupal\Component\Transliteration\TransliterationInterface;
  4. use Drupal\Component\Utility\NestedArray;
  5. use Drupal\Core\Access\AccessResult;
  6. use Drupal\Core\Form\FormStateInterface;
  7. use Drupal\Core\Language\LanguageInterface;
  8. use Drupal\Core\Messenger\MessengerTrait;
  9. use Drupal\Core\Plugin\PluginWithFormsTrait;
  10. use Drupal\Core\Session\AccountInterface;
  11. use Drupal\Core\StringTranslation\StringTranslationTrait;
  12. /**
  13. * Provides the base implementation of a block plugin.
  14. *
  15. * @internal
  16. * This trait is used internally by the block system. Block plugins should
  17. * extend \Drupal\Core\Block\BlockBase.
  18. *
  19. * @see \Drupal\Core\Block\BlockBase
  20. * @see \Drupal\Core\Block\BlockPluginInterface
  21. *
  22. * @ingroup block_api
  23. */
  24. trait BlockPluginTrait {
  25. use StringTranslationTrait;
  26. use MessengerTrait;
  27. use PluginWithFormsTrait;
  28. /**
  29. * The transliteration service.
  30. *
  31. * @var \Drupal\Component\Transliteration\TransliterationInterface
  32. */
  33. protected $transliteration;
  34. /**
  35. * {@inheritdoc}
  36. */
  37. public function label() {
  38. if (!empty($this->configuration['label'])) {
  39. return $this->configuration['label'];
  40. }
  41. $definition = $this->getPluginDefinition();
  42. // Cast the admin label to a string since it is an object.
  43. // @see \Drupal\Core\StringTranslation\TranslatableMarkup
  44. return (string) $definition['admin_label'];
  45. }
  46. /**
  47. * {@inheritdoc}
  48. */
  49. public function __construct(array $configuration, $plugin_id, $plugin_definition) {
  50. parent::__construct($configuration, $plugin_id, $plugin_definition);
  51. $this->setConfiguration($configuration);
  52. }
  53. /**
  54. * {@inheritdoc}
  55. */
  56. public function getConfiguration() {
  57. return $this->configuration;
  58. }
  59. /**
  60. * {@inheritdoc}
  61. */
  62. public function setConfiguration(array $configuration) {
  63. $this->configuration = NestedArray::mergeDeep(
  64. $this->baseConfigurationDefaults(),
  65. $this->defaultConfiguration(),
  66. $configuration
  67. );
  68. }
  69. /**
  70. * Returns generic default configuration for block plugins.
  71. *
  72. * @return array
  73. * An associative array with the default configuration.
  74. */
  75. protected function baseConfigurationDefaults() {
  76. return [
  77. 'id' => $this->getPluginId(),
  78. 'label' => '',
  79. 'provider' => $this->pluginDefinition['provider'],
  80. 'label_display' => BlockPluginInterface::BLOCK_LABEL_VISIBLE,
  81. ];
  82. }
  83. /**
  84. * {@inheritdoc}
  85. */
  86. public function defaultConfiguration() {
  87. return [];
  88. }
  89. /**
  90. * {@inheritdoc}
  91. */
  92. public function setConfigurationValue($key, $value) {
  93. $this->configuration[$key] = $value;
  94. }
  95. /**
  96. * {@inheritdoc}
  97. */
  98. public function calculateDependencies() {
  99. return [];
  100. }
  101. /**
  102. * {@inheritdoc}
  103. */
  104. public function access(AccountInterface $account, $return_as_object = FALSE) {
  105. $access = $this->blockAccess($account);
  106. return $return_as_object ? $access : $access->isAllowed();
  107. }
  108. /**
  109. * Indicates whether the block should be shown.
  110. *
  111. * Blocks with specific access checking should override this method rather
  112. * than access(), in order to avoid repeating the handling of the
  113. * $return_as_object argument.
  114. *
  115. * @param \Drupal\Core\Session\AccountInterface $account
  116. * The user session for which to check access.
  117. *
  118. * @return \Drupal\Core\Access\AccessResult
  119. * The access result.
  120. *
  121. * @see self::access()
  122. */
  123. protected function blockAccess(AccountInterface $account) {
  124. // By default, the block is visible.
  125. return AccessResult::allowed();
  126. }
  127. /**
  128. * {@inheritdoc}
  129. *
  130. * Creates a generic configuration form for all block types. Individual
  131. * block plugins can add elements to this form by overriding
  132. * BlockBase::blockForm(). Most block plugins should not override this
  133. * method unless they need to alter the generic form elements.
  134. *
  135. * @see \Drupal\Core\Block\BlockBase::blockForm()
  136. */
  137. public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
  138. $definition = $this->getPluginDefinition();
  139. $form['provider'] = [
  140. '#type' => 'value',
  141. '#value' => $definition['provider'],
  142. ];
  143. $form['admin_label'] = [
  144. '#type' => 'item',
  145. '#title' => $this->t('Block description'),
  146. '#plain_text' => $definition['admin_label'],
  147. ];
  148. $form['label'] = [
  149. '#type' => 'textfield',
  150. '#title' => $this->t('Title'),
  151. '#maxlength' => 255,
  152. '#default_value' => $this->label(),
  153. '#required' => TRUE,
  154. ];
  155. $form['label_display'] = [
  156. '#type' => 'checkbox',
  157. '#title' => $this->t('Display title'),
  158. '#default_value' => ($this->configuration['label_display'] === BlockPluginInterface::BLOCK_LABEL_VISIBLE),
  159. '#return_value' => BlockPluginInterface::BLOCK_LABEL_VISIBLE,
  160. ];
  161. // Add context mapping UI form elements.
  162. $contexts = $form_state->getTemporaryValue('gathered_contexts') ?: [];
  163. $form['context_mapping'] = $this->addContextAssignmentElement($this, $contexts);
  164. // Add plugin-specific settings for this block type.
  165. $form += $this->blockForm($form, $form_state);
  166. return $form;
  167. }
  168. /**
  169. * {@inheritdoc}
  170. */
  171. public function blockForm($form, FormStateInterface $form_state) {
  172. return [];
  173. }
  174. /**
  175. * {@inheritdoc}
  176. *
  177. * Most block plugins should not override this method. To add validation
  178. * for a specific block type, override BlockBase::blockValidate().
  179. *
  180. * @see \Drupal\Core\Block\BlockBase::blockValidate()
  181. */
  182. public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
  183. // Remove the admin_label form item element value so it will not persist.
  184. $form_state->unsetValue('admin_label');
  185. $this->blockValidate($form, $form_state);
  186. }
  187. /**
  188. * {@inheritdoc}
  189. */
  190. public function blockValidate($form, FormStateInterface $form_state) {
  191. }
  192. /**
  193. * {@inheritdoc}
  194. *
  195. * Most block plugins should not override this method. To add submission
  196. * handling for a specific block type, override BlockBase::blockSubmit().
  197. *
  198. * @see \Drupal\Core\Block\BlockBase::blockSubmit()
  199. */
  200. public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
  201. // Process the block's submission handling if no errors occurred only.
  202. if (!$form_state->getErrors()) {
  203. $this->configuration['label'] = $form_state->getValue('label');
  204. $this->configuration['label_display'] = $form_state->getValue('label_display');
  205. $this->configuration['provider'] = $form_state->getValue('provider');
  206. $this->blockSubmit($form, $form_state);
  207. }
  208. }
  209. /**
  210. * {@inheritdoc}
  211. */
  212. public function blockSubmit($form, FormStateInterface $form_state) {
  213. }
  214. /**
  215. * {@inheritdoc}
  216. */
  217. public function getMachineNameSuggestion() {
  218. $definition = $this->getPluginDefinition();
  219. $admin_label = $definition['admin_label'];
  220. // @todo This is basically the same as what is done in
  221. // \Drupal\system\MachineNameController::transliterate(), so it might make
  222. // sense to provide a common service for the two.
  223. $transliterated = $this->transliteration()->transliterate($admin_label, LanguageInterface::LANGCODE_DEFAULT, '_');
  224. $transliterated = mb_strtolower($transliterated);
  225. $transliterated = preg_replace('@[^a-z0-9_.]+@', '', $transliterated);
  226. return $transliterated;
  227. }
  228. /**
  229. * {@inheritdoc}
  230. */
  231. public function getPreviewFallbackString() {
  232. return $this->t('"@block" block', ['@block' => $this->label()]);
  233. }
  234. /**
  235. * Wraps the transliteration service.
  236. *
  237. * @return \Drupal\Component\Transliteration\TransliterationInterface
  238. */
  239. protected function transliteration() {
  240. if (!$this->transliteration) {
  241. $this->transliteration = \Drupal::transliteration();
  242. }
  243. return $this->transliteration;
  244. }
  245. /**
  246. * Sets the transliteration service.
  247. *
  248. * @param \Drupal\Component\Transliteration\TransliterationInterface $transliteration
  249. * The transliteration service.
  250. */
  251. public function setTransliteration(TransliterationInterface $transliteration) {
  252. $this->transliteration = $transliteration;
  253. }
  254. }