4280cd416e7d069d796817202822c8a038ed5759
[yaffs-website] / web / core / modules / system / tests / modules / display_variant_test / src / Plugin / DisplayVariant / TestDisplayVariant.php
1 <?php
2
3 namespace Drupal\display_variant_test\Plugin\DisplayVariant;
4
5 use Drupal\Core\Cache\CacheableMetadata;
6 use Drupal\Core\Display\VariantBase;
7 use Drupal\Core\Display\PageVariantInterface;
8 use Drupal\Core\Display\ContextAwareVariantInterface;
9
10 /**
11  * Provides a display variant that requires configuration.
12  *
13  * @DisplayVariant(
14  *   id = "display_variant_test",
15  *   admin_label = @Translation("Test display variant")
16  * )
17  */
18 class TestDisplayVariant extends VariantBase implements PageVariantInterface, ContextAwareVariantInterface {
19
20   /**
21    * The render array representing the main page content.
22    *
23    * @var array
24    */
25   protected $mainContent = [];
26
27   /**
28    * The page title: a string (plain title) or a render array (formatted title).
29    *
30    * @var string|array
31    */
32   protected $title = '';
33
34   /**
35    * An array of collected contexts.
36    *
37    * This is only used on runtime, and is not stored.
38    *
39    * @var \Drupal\Component\Plugin\Context\ContextInterface[]
40    */
41   protected $contexts = [];
42
43   /**
44    * Gets the contexts.
45    *
46    * @return \Drupal\Component\Plugin\Context\ContextInterface[]
47    *   An array of set contexts, keyed by context name.
48    */
49   public function getContexts() {
50     return $this->contexts;
51   }
52
53   /**
54    * Sets the contexts.
55    *
56    * @param \Drupal\Component\Plugin\Context\ContextInterface[] $contexts
57    *   An array of contexts, keyed by context name.
58    *
59    * @return $this
60    */
61   public function setContexts(array $contexts) {
62     $this->contexts = $contexts;
63     return $this;
64   }
65
66   /**
67    * {@inheritdoc}
68    */
69   public function setMainContent(array $main_content) {
70     $this->mainContent = $main_content;
71     return $this;
72   }
73
74   /**
75    * {@inheritdoc}
76    */
77   public function setTitle($title) {
78     $this->title = $title;
79     return $this;
80   }
81
82   /**
83    * {@inheritdoc}
84    */
85   public function build() {
86     $config = $this->getConfiguration();
87     if (empty($config['required_configuration'])) {
88       throw new \Exception('Required configuration is missing!');
89     }
90
91     $contexts = $this->getContexts();
92     if (!isset($contexts['context'])) {
93       throw new \Exception('Required context is missing!');
94     }
95
96     $build = [];
97     $build['content']['default'] = [
98       '#markup' => $config['required_configuration'] . ' ' . $contexts['context']->getContextValue(),
99     ];
100
101     CacheableMetadata::createFromObject($this)->applyTo($build);
102
103     return $build;
104   }
105
106 }