FieldFormatterEntityEmbedDisplayBase   A
last analyzed

Complexity

Total Complexity 14

Size/Duplication

Total Lines 225
Duplicated Lines 14.22 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
dl 32
loc 225
rs 10
c 0
b 0
f 0
wmc 14
lcom 1
cbo 1

13 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A create() 11 11 1
A getFieldDefinition() 0 11 2
getFieldValue() 0 1 ?
A access() 0 3 1
A isApplicableFieldFormatter() 0 4 1
A getFieldFormatterId() 0 3 1
B build() 0 28 1
A defaultConfiguration() 0 3 1
A buildConfigurationForm() 0 3 1
A getFieldFormatter() 21 21 2
A createFieldDefinition() 0 6 1
A calculateDependencies() 0 9 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace Drupal\entity_embed\EntityEmbedDisplay;
4
5
use Drupal\Core\Access\AccessResult;
6
use Drupal\Core\Entity\EntityTypeManagerInterface;
7
use Drupal\Core\Field\BaseFieldDefinition;
8
use Drupal\Core\Field\FormatterPluginManager;
9
use Drupal\Core\Form\FormStateInterface;
10
use Drupal\Core\Language\LanguageManagerInterface;
11
use Drupal\Core\Plugin\PluginDependencyTrait;
12
use Drupal\Core\Session\AccountInterface;
13
use Drupal\Core\TypedData\TypedDataManager;
14
use Drupal\node\Entity\Node;
15
use Symfony\Component\DependencyInjection\ContainerInterface;
16
17
/**
18
 *
19
 */
20
abstract class FieldFormatterEntityEmbedDisplayBase extends EntityEmbedDisplayBase {
21
  use PluginDependencyTrait;
22
23
  /**
24
   * The field formatter plugin manager.
25
   *
26
   * @var \Drupal\Core\Field\FormatterPluginManager
27
   */
28
  protected $formatterPluginManager;
29
30
  /**
31
   * The typed data manager.
32
   *
33
   * @var \Drupal\Core\TypedData\TypedDataManager
34
   */
35
  protected $typedDataManager;
36
37
  /**
38
   * The field definition.
39
   *
40
   * @var \Drupal\Core\Field\BaseFieldDefinition
41
   */
42
  protected $fieldDefinition;
43
44
  /**
45
   * The field formatter.
46
   *
47
   * @var \Drupal\Core\Field\FormatterInterface
48
   */
49
  protected $fieldFormatter;
50
51
  /**
52
   * Constructs a FieldFormatterEntityEmbedDisplayBase object.
53
   *
54
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
55
   *   The entity type manager service.
56
   * @param \Drupal\Core\Field\FormatterPluginManager $formatter_plugin_manager
57
   *   The field formatter plugin manager.
58
   * @param \Drupal\Core\TypedData\TypedDataManager $typed_data_manager
59
   *   The typed data manager.
60
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
61
   *   The language manager.
62
   */
63
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, FormatterPluginManager $formatter_plugin_manager, TypedDataManager $typed_data_manager, LanguageManagerInterface $language_manager) {
64
    $this->formatterPluginManager = $formatter_plugin_manager;
65
    $this->setConfiguration($configuration);
66
    $this->typedDataManager = $typed_data_manager;
67
    parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager, $language_manager);
68
  }
69
70
  /**
71
   * {@inheritdoc}
72
   */
73 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...
74
    return new static(
75
      $configuration,
76
      $plugin_id,
77
      $plugin_definition,
78
      $container->get('entity_type.manager'),
79
      $container->get('plugin.manager.field.formatter'),
80
      $container->get('typed_data_manager'),
81
      $container->get('language_manager')
82
    );
83
  }
84
85
  /**
86
   * Get the FieldDefinition object required to render this field's formatter.
87
   *
88
   * @return \Drupal\Core\Field\BaseFieldDefinition
89
   *   The field definition.
90
   *
91
   * @see \Drupal\entity_embed\FieldFormatterEntityEmbedDisplayBase::build()
92
   */
93
  public function getFieldDefinition() {
94
    if (!isset($this->fieldDefinition)) {
95
      $field_type = $this->getPluginDefinition()['field_type'];
96
      $this->fieldDefinition = BaseFieldDefinition::create($field_type);
97
      // Ensure the field name is unique for each Entity Embed Display plugin
98
      // instance.
99
      static $index = 0;
100
      $this->fieldDefinition->setName('_entity_embed_' . $index++);
101
    }
102
    return $this->fieldDefinition;
103
  }
104
105
  /**
106
   * Get the field value required to pass into the field formatter.
107
   *
108
   * @return mixed
109
   *   The field value.
110
   */
111
  abstract public function getFieldValue();
112
113
  /**
114
   * {@inheritdoc}
115
   */
116
  public function access(AccountInterface $account = NULL) {
117
    return parent::access($account)->andIf($this->isApplicableFieldFormatter());
118
  }
119
120
  /**
121
   * Checks if the field formatter is applicable.
122
   *
123
   * @return \Drupal\Core\Access\AccessResult
124
   *   Returns the access result.
125
   */
126
  protected function isApplicableFieldFormatter() {
127
    $definition = $this->formatterPluginManager->getDefinition($this->getFieldFormatterId());
128
    return AccessResult::allowedIf($definition['class']::isApplicable($this->getFieldDefinition()));
129
  }
130
131
  /**
132
   * Returns the field formatter id.
133
   *
134
   * @return string|null
135
   *   Returns field formatter id or null.
136
   */
137
  public function getFieldFormatterId() {
138
    return $this->getDerivativeId();
139
  }
140
141
  /**
142
   * {@inheritdoc}
143
   */
144
  public function build() {
145
    // Create a temporary node object to which our fake field value can be
146
    // added.
147
    $node = Node::create(array('type' => '_entity_embed'));
148
149
    $definition = $this->getFieldDefinition();
150
151
    /* @var \Drupal\Core\Field\FieldItemListInterface $items $items */
152
    // Create a field item list object, 1 is the value, array('target_id' => 1)
153
    // would work too, or multiple values. 1 is passed down from the list to the
154
    // field item, which knows that an integer is the ID.
155
    $items = $this->typedDataManager->create(
156
      $definition,
157
      $this->getFieldValue($definition),
158
      $definition->getName(),
159
      $node->getTypedData()
160
    );
161
162
    // Prepare, expects an array of items, keyed by parent entity ID.
163
    $formatter = $this->getFieldFormatter();
164
    $formatter->prepareView(array($node->id() => $items));
165
    $build = $formatter->viewElements($items, $this->getLangcode());
166
    // For some reason $build[0]['#printed'] is TRUE, which means it will fail
167
    // to render later. So for now we manually fix that.
168
    // @todo Investigate why this is needed.
169
    show($build[0]);
170
    return $build[0];
171
  }
172
173
  /**
174
   * {@inheritdoc}
175
   */
176
  public function defaultConfiguration() {
177
    return $this->formatterPluginManager->getDefaultSettings($this->getFieldFormatterId());
178
  }
179
180
  /**
181
   * {@inheritdoc}
182
   */
183
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
184
    return $this->getFieldFormatter()->settingsForm($form, $form_state);
185
  }
186
187
  /**
188
   * Constructs a field formatter.
189
   *
190
   * @return \Drupal\Core\Field\FormatterInterface
191
   *   The formatter object.
192
   */
193 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...
194
    if (!isset($this->fieldFormatter)) {
195
      $display = array(
196
        'type' => $this->getFieldFormatterId(),
197
        'settings' => $this->getConfiguration(),
198
        'label' => 'hidden',
199
      );
200
201
      // Create the formatter plugin. Will use the default formatter for that
202
      // field type if none is passed.
203
      $this->fieldFormatter = $this->formatterPluginManager->getInstance(
204
        array(
205
          'field_definition' => $this->getFieldDefinition(),
206
          'view_mode' => '_entity_embed',
207
          'configuration' => $display,
208
        )
209
      );
210
    }
211
212
    return $this->fieldFormatter;
213
  }
214
215
  /**
216
   * Creates a new faux-field definition.
217
   *
218
   * @param string $type
219
   *   The type of the field.
220
   *
221
   * @return \Drupal\Core\Field\BaseFieldDefinition
222
   *   A new field definition.
223
   */
224
  protected function createFieldDefinition($type) {
225
    $definition = BaseFieldDefinition::create($type);
226
    static $index = 0;
227
    $definition->setName('_entity_embed_' . $index++);
228
    return $definition;
229
  }
230
231
  /**
232
   * {@inheritdoc}
233
   */
234
  public function calculateDependencies() {
235
    $this->addDependencies(parent::calculateDependencies());
236
237
    $definition = $this->formatterPluginManager->getDefinition($this->getFieldFormatterId());
238
    $this->addDependency('module', $definition['provider']);
239
    // @todo Investigate why this does not work currently.
240
    // $this->calculatePluginDependencies($this->getFieldFormatter());
241
    return $this->dependencies;
242
  }
243
244
}
245