Completed
Push — 8.x-1.x ( c248cd...375743 )
by Janez
02:14
created

getFieldFormatterId()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
3
namespace Drupal\entity_embed\EntityEmbedDisplay;
4
5
use Drupal\Core\Access\AccessResult;
6
use Drupal\Core\Entity\EntityManagerInterface;
7
use Drupal\Core\Field\BaseFieldDefinition;
8
use Drupal\Core\Field\FormatterPluginManager;
9
use Drupal\Core\Form\FormStateInterface;
10
use Drupal\Core\Plugin\PluginDependencyTrait;
11
use Drupal\Core\Session\AccountInterface;
12
use Drupal\Core\TypedData\TypedDataManager;
13
use Drupal\node\Entity\Node;
14
use Symfony\Component\DependencyInjection\ContainerInterface;
15
16
abstract class FieldFormatterEntityEmbedDisplayBase extends EntityEmbedDisplayBase {
17
  use PluginDependencyTrait;
18
19
  /**
20
   * The field formatter plugin manager.
21
   *
22
   * @var \Drupal\Core\Field\FormatterPluginManager
23
   */
24
  protected $formatterPluginManager;
25
26
  /**
27
   * The typed data manager.
28
   *
29
   * @var \Drupal\Core\TypedData\TypedDataManager
30
   */
31
  protected $typedDataManager;
32
33
  /**
34
   * The field definition.
35
   *
36
   * @var \Drupal\Core\Field\BaseFieldDefinition
37
   */
38
  protected $fieldDefinition;
39
40
  /**
41
   * The field formatter.
42
   *
43
   * @var \Drupal\Core\Field\FormatterInterface
44
   */
45
  protected $fieldFormatter;
46
47
  /**
48
   * Constructs a FieldFormatterEntityEmbedDisplayBase object.
49
   *
50
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
51
   *   The entity manager service.
52
   * @param \Drupal\Core\Field\FormatterPluginManager $formatter_plugin_manager
53
   *   The field formatter plugin manager.
54
   * @param \Drupal\Core\TypedData\TypedDataManager $typed_data_manager
55
   *   The typed data manager.
56
   */
57
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityManagerInterface $entity_manager, FormatterPluginManager $formatter_plugin_manager, TypedDataManager $typed_data_manager) {
58
    $this->formatterPluginManager = $formatter_plugin_manager;
59
    $this->setConfiguration($configuration);
60
    $this->setEntityManager($entity_manager);
61
    $this->typedDataManager = $typed_data_manager;
62
    parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_manager);
63
  }
64
65
  /**
66
   * {@inheritdoc}
67
   */
68 View Code Duplication
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
69
    return new static(
70
      $configuration,
71
      $plugin_id,
72
      $plugin_definition,
73
      $container->get('entity.manager'),
74
      $container->get('plugin.manager.field.formatter'),
75
      $container->get('typed_data_manager')
76
    );
77
  }
78
79
  /**
80
   * Get the FieldDefinition object required to render this field's formatter.
81
   *
82
   * @return \Drupal\Core\Field\BaseFieldDefinition
83
   *   The field definition.
84
   *
85
   * @see \Drupal\entity_embed\FieldFormatterEntityEmbedDisplayBase::build()
86
   */
87
  public function getFieldDefinition() {
88
    if (!isset($this->fieldDefinition)) {
89
      $field_type = $this->getPluginDefinition()['field_type'];
90
      $this->fieldDefinition = BaseFieldDefinition::create($field_type);
91
      // Ensure the field name is unique for each Entity Embed Display plugin
92
      // instance.
93
      static $index = 0;
94
      $this->fieldDefinition->setName('_entity_embed_' . $index++);
95
    }
96
    return $this->fieldDefinition;
97
  }
98
99
  /**
100
   * Get the field value required to pass into the field formatter.
101
   *
102
   * @return mixed
103
   *   The field value.
104
   */
105
  abstract public function getFieldValue();
106
107
  /**
108
   * {@inheritdoc}
109
   */
110
  public function access(AccountInterface $account = NULL) {
111
    return parent::access($account)->andIf($this->isApplicableFieldFormatter());
112
  }
113
114
  /**
115
   * Checks if the field formatter is applicable.
116
   *
117
   * @return \Drupal\Core\Access\AccessResult
118
   *   Returns the access result.
119
   */
120
  protected function isApplicableFieldFormatter() {
121
    $definition = $this->formatterPluginManager->getDefinition($this->getFieldFormatterId());
122
    return AccessResult::allowedIf($definition['class']::isApplicable($this->getFieldDefinition()));
123
  }
124
125
  /**
126
   * Returns the field formatter id.
127
   *
128
   * @return string|null
129
   *   Returns field formatter id or null.
130
   */
131
  public function getFieldFormatterId() {
132
    return $this->getDerivativeId();
133
  }
134
135
  /**
136
   * {@inheritdoc}
137
   */
138
  public function build() {
139
    // Create a temporary node object to which our fake field value can be
140
    // added.
141
    $node = Node::create(array('type' => '_entity_embed'));
142
143
    $definition = $this->getFieldDefinition();
144
145
    /* @var \Drupal\Core\Field\FieldItemListInterface $items $items */
146
    // Create a field item list object, 1 is the value, array('target_id' => 1)
147
    // would work too, or multiple values. 1 is passed down from the list to the
148
    // field item, which knows that an integer is the ID.
149
    $items = $this->typedDataManager->create(
150
      $definition,
151
      $this->getFieldValue($definition),
152
      $definition->getName(),
153
      $node->getTypedData()
154
    );
155
156
    // Prepare, expects an array of items, keyed by parent entity ID.
157
    $formatter = $this->getFieldFormatter();
158
    $formatter->prepareView(array($node->id() => $items));
159
    $build = $formatter->viewElements($items, $this->getLangcode());
160
    // For some reason $build[0]['#printed'] is TRUE, which means it will fail
161
    // to render later. So for now we manually fix that.
162
    // @todo Investigate why this is needed.
163
    show($build[0]);
164
    return $build[0];
165
  }
166
167
  /**
168
   * {@inheritdoc}
169
   */
170
  public function defaultConfiguration() {
171
    return $this->formatterPluginManager->getDefaultSettings($this->getFieldFormatterId());
172
  }
173
174
  /**
175
   * {@inheritdoc}
176
   */
177
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
178
    return $this->getFieldFormatter()->settingsForm($form, $form_state);
179
  }
180
181
  /**
182
   * Constructs a field formatter.
183
   *
184
   * @return \Drupal\Core\Field\FormatterInterface
185
   *   The formatter object.
186
   */
187 View Code Duplication
  public function getFieldFormatter() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
188
    if (!isset($this->fieldFormatter)) {
189
      $display = array(
190
        'type' => $this->getFieldFormatterId(),
191
        'settings' => $this->getConfiguration(),
192
        'label' => 'hidden',
193
      );
194
195
      // Create the formatter plugin. Will use the default formatter for that
196
      // field type if none is passed.
197
      $this->fieldFormatter = $this->formatterPluginManager->getInstance(
198
        array(
199
          'field_definition' => $this->getFieldDefinition(),
200
          'view_mode' => '_entity_embed',
201
          'configuration' => $display,
202
        )
203
      );
204
    }
205
206
    return $this->fieldFormatter;
207
  }
208
209
  /**
210
   * Creates a new faux-field definition.
211
   *
212
   * @param string $type
213
   *   The type of the field.
214
   *
215
   * @return \Drupal\Core\Field\BaseFieldDefinition
216
   *   A new field definition.
217
   */
218
  protected function createFieldDefinition($type) {
219
    $definition = BaseFieldDefinition::create($type);
220
    static $index = 0;
221
    $definition->setName('_entity_embed_' . $index++);
222
    return $definition;
223
  }
224
225
  /**
226
   * {@inheritdoc}
227
   */
228
  public function calculateDependencies() {
229
    $this->addDependencies(parent::calculateDependencies());
230
231
    $definition = $this->formatterPluginManager->getDefinition($this->getFieldFormatterId());
232
    $this->addDependency('module', $definition['provider']);
233
    // @todo Investigate why this does not work currently.
234
    //$this->calculatePluginDependencies($this->getFieldFormatter());
235
236
    return $this->dependencies;
237
  }
238
239
}
240