Completed
Push — 8.x-1.x ( 8d65d1...72a93e )
by Janez
02:43
created

EntityEmbedFilter::process()   D

Complexity

Conditions 13
Paths 2

Size

Total Lines 82
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Importance

Changes 17
Bugs 3 Features 1
Metric Value
cc 13
eloc 43
c 17
b 3
f 1
nc 2
nop 2
dl 0
loc 82
rs 4.9922

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Drupal\entity_embed\Plugin\Filter;
4
5
use Drupal\Component\Utility\Html;
6
use Drupal\Core\Entity\EntityTypeManagerInterface;
7
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
8
use Drupal\Core\Render\BubbleableMetadata;
9
use Drupal\Core\Render\RenderContext;
10
use Drupal\Core\Render\RendererInterface;
11
use Drupal\entity_embed\EntityEmbedBuilderInterface;
12
use Drupal\entity_embed\Exception\EntityNotFoundException;
13
use Drupal\entity_embed\Exception\RecursiveRenderingException;
14
use Drupal\filter\FilterProcessResult;
15
use Drupal\filter\Plugin\FilterBase;
16
use RecursiveArrayIterator;
17
use RecursiveIteratorIterator;
18
use Symfony\Component\DependencyInjection\ContainerInterface;
19
use Drupal\embed\DomHelperTrait;
20
21
/**
22
 * Provides a filter to display embedded entities based on data attributes.
23
 *
24
 * @Filter(
25
 *   id = "entity_embed",
26
 *   title = @Translation("Display embedded entities"),
27
 *   description = @Translation("Embeds entities using data attributes: data-entity-type, data-entity-uuid, and data-view-mode."),
28
 *   type = Drupal\filter\Plugin\FilterInterface::TYPE_TRANSFORM_REVERSIBLE
29
 * )
30
 */
31
class EntityEmbedFilter extends FilterBase implements ContainerFactoryPluginInterface {
32
33
  use DomHelperTrait;
34
35
  /**
36
   * The renderer service.
37
   *
38
   * @var \Drupal\Core\Render\RendererInterface
39
   */
40
  protected $renderer;
41
42
  /**
43
   * The entity type manager.
44
   *
45
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
46
   */
47
  protected $entityTypeManager;
48
49
  /**
50
   * The entity embed builder service.
51
   *
52
   * @var \Drupal\entity_embed\EntityEmbedBuilderInterface
53
   */
54
  protected $builder;
55
56
  /**
57
   * Constructs a EntityEmbedFilter object.
58
   *
59
   * @param array $configuration
60
   *   A configuration array containing information about the plugin instance.
61
   * @param string $plugin_id
62
   *   The plugin ID for the plugin instance.
63
   * @param mixed $plugin_definition
64
   *   The plugin implementation definition.
65
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
66
   *   The entity type manager.
67
   * @param \Drupal\Core\Render\RendererInterface $renderer
68
   *   The renderer.
69
   * @param \Drupal\entity_embed\EntityEmbedBuilderInterface $builder
70
   *   The entity embed builder service.
71
   */
72
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, RendererInterface $renderer, EntityEmbedBuilderInterface $builder) {
73
    parent::__construct($configuration, $plugin_id, $plugin_definition);
74
    $this->entityTypeManager = $entity_type_manager;
75
    $this->renderer = $renderer;
76
    $this->builder = $builder;
77
  }
78
79
  /**
80
   * {@inheritdoc}
81
   */
82
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
83
    return new static(
84
      $configuration,
85
      $plugin_id,
86
      $plugin_definition,
87
      $container->get('entity_type.manager'),
88
      $container->get('renderer'),
89
      $container->get('entity_embed.builder')
90
    );
91
  }
92
93
  /**
94
   * {@inheritdoc}
95
   */
96
  public function process($text, $langcode) {
97
    $result = new FilterProcessResult($text);
98
99
    if (strpos($text, 'data-entity-type') !== FALSE && (strpos($text, 'data-entity-embed-display') !== FALSE || strpos($text, 'data-view-mode') !== FALSE)) {
100
      $dom = Html::load($text);
101
      $xpath = new \DOMXPath($dom);
102
103
      foreach ($xpath->query('//drupal-entity[@data-entity-type and (@data-entity-uuid or @data-entity-id) and (@data-entity-embed-display or @data-view-mode)]') as $node) {
104
        /** @var \DOMElement $node */
105
        $entity_type = $node->getAttribute('data-entity-type');
106
        $entity = NULL;
0 ignored issues
show
Unused Code introduced by
$entity is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
107
        $entity_output = '';
108
109
        // data-entity-embed-settings is deprecated, make sure we convert it to
110
        // data-entity-embed-display-settings.
111
        if (($settings = $node->getAttribute('data-entity-embed-settings')) && !$node->hasAttribute('data-entity-embed-display-settings')) {
112
          $node->setAttribute('data-entity-embed-display-settings', $settings);
113
          $node->removeAttribute('data-entity-embed-settings');
114
        }
115
116
        try {
117
          // Load the entity either by UUID (preferred) or ID.
118
          $id = NULL;
119
          $entity = NULL;
120
          if ($id = $node->getAttribute('data-entity-uuid')) {
121
            $entity = $this->entityTypeManager->getStorage($entity_type)
122
              ->loadByProperties(['uuid' => $id]);
123
            $entity = current($entity);
124
          }
125
          else {
126
            $id = $node->getAttribute('data-entity-id');
127
            $entity = $this->entityTypeManager->getStorage($entity_type)->load($id);
128
          }
129
130
          if ($entity) {
131
            // Protect ourselves from recursive rendering.
132
            static $depth = 0;
133
            $depth++;
134
            if ($depth > 20) {
135
              throw new RecursiveRenderingException(sprintf('Recursive rendering detected when rendering embedded %s entity %s.', $entity_type, $entity->id()));
136
            }
137
138
            // If a UUID was not used, but is available, add it to the HTML.
139
            if (!$node->getAttribute('data-entity-uuid') && $uuid = $entity->uuid()) {
140
              $node->setAttribute('data-entity-uuid', $uuid);
141
            }
142
143
            $context = $this->getNodeAttributesAsArray($node);
144
            $context += array('data-langcode' => $langcode);
145
            $build = $this->builder->buildEntityEmbed($entity, $context);
146
            // We need to render the embedded entity:
147
            // - without replacing placeholders, so that the placeholders are
148
            //   only replaced at the last possible moment. Hence we cannot use
149
            //   either renderPlain() or renderRoot(), so we must use render().
150
            // - without bubbling beyond this filter, because filters must
151
            //   ensure that the bubbleable metadata for the changes they make
152
            //   when filtering text makes it onto the FilterProcessResult
153
            //   object that they return ($result). To prevent that bubbling, we
154
            //   must wrap the call to render() in a render context.
155
            $entity_output = $this->renderer->executeInRenderContext(new RenderContext(), function () use (&$build) {
156
              return $this->renderer->render($build);
157
            });
158
            $result = $result->merge(BubbleableMetadata::createFromRenderArray($build));
159
160
            $depth--;
161
          }
162
          else {
163
            throw new EntityNotFoundException(sprintf('Unable to load embedded %s entity %s.', $entity_type, $id));
164
          }
165
        }
166
        catch(\Exception $e) {
167
          watchdog_exception('entity_embed', $e);
168
        }
169
170
        $this->replaceNodeContent($node, $entity_output);
171
      }
172
173
      $result->setProcessedText(Html::serialize($dom));
174
    }
175
176
    return $result;
177
  }
178
179
  /**
180
   * {@inheritdoc}
181
   */
182
  public function tips($long = FALSE) {
183
    if ($long) {
184
      return $this->t('
185
        <p>You can embed entities. Additional properties can be added to the embed tag like data-caption and data-align if supported. Example:</p>
186
        <code>&lt;drupal-entity data-entity-type="node" data-entity-uuid="07bf3a2e-1941-4a44-9b02-2d1d7a41ec0e" data-view-mode="teaser" /&gt;</code>');
187
    }
188
    else {
189
      return $this->t('You can embed entities.');
190
    }
191
  }
192
193
}
194