Completed
Push — 8.x-1.x ( 655474...d6da75 )
by Janez
02:45
created

LinkEmbedFormatter::viewElements()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 21
rs 8.7624
cc 5
eloc 12
nc 6
nop 2
1
<?php
2
3
/**
4
 * @file
5
 * Contains \Drupal\url_embed\Plugin\Field\FieldFormatter\LinkEmbedFormatter.
6
 */
7
8
namespace Drupal\url_embed\Plugin\Field\FieldFormatter;
9
10
use Drupal\Core\Field\FieldItemListInterface;
11
use Drupal\Core\Field\FormatterBase;
12
use Drupal\url_embed\UrlEmbedHelperTrait;
13
14
/**
15
 * Plugin implementation of the 'url_embed' formatter.
16
 *
17
 * @FieldFormatter(
18
 *   id = "url_embed",
19
 *   label = @Translation("Embedded URL"),
20
 *   field_types = {
21
 *     "link"
22
 *   }
23
 * )
24
 */
25
class LinkEmbedFormatter extends FormatterBase {
26
  use UrlEmbedHelperTrait;
27
28
  /**
29
   * {@inheritdoc}
30
   */
31
  public function viewElements(FieldItemListInterface $items, $langcode) {
32
    $element = array();
33
34
    foreach ($items as $delta => $item) {
35
      if ($url = $item->getUrl()->toString()) {
36
        try {
37
          if ($info = $this->urlEmbed()->getEmbed($url)) {
38
            $element[$delta] = array(
39
              '#type' => 'inline_template',
40
              '#template' => $info->getCode(),
41
            );
42
          }
43
        }
44
        catch (\Exception $exception) {
45
          watchdog_exception('url_embed', $exception);
46
        }
47
      }
48
    }
49
50
    return $element;
51
  }
52
53
}
54