Updating Media dependent modules to versions compatible with core Media.
[yaffs-website] / web / modules / contrib / media_entity_twitter / src / Plugin / Field / FieldFormatter / TwitterEmbedFormatter.php
1 <?php
2
3 namespace Drupal\media_entity_twitter\Plugin\Field\FieldFormatter;
4
5 use Drupal\Core\Field\FieldItemInterface;
6 use Drupal\Core\Field\FieldItemListInterface;
7 use Drupal\Core\Field\FormatterBase;
8 use Drupal\media_entity_twitter\Plugin\media\Source\Twitter;
9
10 /**
11  * Plugin implementation of the 'twitter_embed' formatter.
12  *
13  * @FieldFormatter(
14  *   id = "twitter_embed",
15  *   label = @Translation("Twitter embed"),
16  *   field_types = {
17  *     "link", "string", "string_long"
18  *   }
19  * )
20  */
21 class TwitterEmbedFormatter extends FormatterBase {
22
23   /**
24    * Extracts the embed code from a field item.
25    *
26    * @param \Drupal\Core\Field\FieldItemInterface $item
27    *   The field item.
28    *
29    * @return string|null
30    *   The embed code, or NULL if the field type is not supported.
31    */
32   protected function getEmbedCode(FieldItemInterface $item) {
33     switch ($item->getFieldDefinition()->getType()) {
34       case 'link':
35         return $item->uri;
36
37       case 'string':
38       case 'string_long':
39         return $item->value;
40
41       default:
42         break;
43     }
44   }
45
46   /**
47    * {@inheritdoc}
48    */
49   public function viewElements(FieldItemListInterface $items, $langcode) {
50     $element = [];
51     foreach ($items as $delta => $item) {
52       $matches = [];
53
54       foreach (Twitter::$validationRegexp as $pattern => $key) {
55         if (preg_match($pattern, $this->getEmbedCode($item), $item_matches)) {
56           $matches[] = $item_matches;
57         }
58       }
59
60       if (!empty($matches)) {
61         $matches = reset($matches);
62       }
63
64       if (!empty($matches['user']) && !empty($matches['id'])) {
65         $element[$delta] = [
66           '#theme' => 'media_entity_twitter_tweet',
67           '#path' => 'https://twitter.com/' . $matches['user'] . '/statuses/' . $matches['id'],
68           '#attributes' => [
69             'class' => ['twitter-tweet', 'element-hidden'],
70             'data-conversation' => 'none',
71             'lang' => 'en',
72           ],
73         ];
74       }
75     }
76
77     if (!empty($element)) {
78       $element['#attached'] = [
79         'library' => [
80           'media_entity_twitter/integration',
81         ],
82       ];
83     }
84
85     return $element;
86   }
87
88 }