Version 1
[yaffs-website] / web / core / modules / block / tests / modules / block_test / src / Plugin / Block / TestContextAwareBlock.php
diff --git a/web/core/modules/block/tests/modules/block_test/src/Plugin/Block/TestContextAwareBlock.php b/web/core/modules/block/tests/modules/block_test/src/Plugin/Block/TestContextAwareBlock.php
new file mode 100644 (file)
index 0000000..7db350d
--- /dev/null
@@ -0,0 +1,46 @@
+<?php
+
+namespace Drupal\block_test\Plugin\Block;
+
+use Drupal\Core\Block\BlockBase;
+use Drupal\Core\Session\AccountInterface;
+use Drupal\user\UserInterface;
+
+/**
+ * Provides a context-aware block.
+ *
+ * @Block(
+ *   id = "test_context_aware",
+ *   admin_label = @Translation("Test context-aware block"),
+ *   context = {
+ *     "user" = @ContextDefinition("entity:user", required = FALSE)
+ *   }
+ * )
+ */
+class TestContextAwareBlock extends BlockBase {
+
+  /**
+   * {@inheritdoc}
+   */
+  public function build() {
+    /** @var $user \Drupal\user\UserInterface */
+    $user = $this->getContextValue('user');
+    return [
+      '#prefix' => '<div id="' . $this->getPluginId() . '--username">',
+      '#suffix' => '</div>',
+      '#markup' => $user ? $user->getUsername() : 'No context mapping selected.' ,
+    ];
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  protected function blockAccess(AccountInterface $account) {
+    if ($this->getContextValue('user') instanceof UserInterface) {
+      drupal_set_message('User context found.');
+    }
+
+    return parent::blockAccess($account);
+  }
+
+}