aa11aeac98a65e24336e0ef21515d84cc4b95866
[yaffs-website] / web / modules / contrib / video_embed_field / src / Plugin / video_embed_field / Provider / YouTube.php
1 <?php
2
3 namespace Drupal\video_embed_field\Plugin\video_embed_field\Provider;
4
5 use Drupal\video_embed_field\ProviderPluginBase;
6
7 /**
8  * A YouTube provider plugin.
9  *
10  * @VideoEmbedProvider(
11  *   id = "youtube",
12  *   title = @Translation("YouTube")
13  * )
14  */
15 class YouTube extends ProviderPluginBase {
16
17   /**
18    * {@inheritdoc}
19    */
20   public function renderEmbedCode($width, $height, $autoplay) {
21     $embed_code = [
22       '#type' => 'video_embed_iframe',
23       '#provider' => 'youtube',
24       '#url' => sprintf('https://www.youtube.com/embed/%s', $this->getVideoId()),
25       '#query' => [
26         'autoplay' => $autoplay,
27         'start' => $this->getTimeIndex(),
28         'rel' => '0',
29       ],
30       '#attributes' => [
31         'width' => $width,
32         'height' => $height,
33         'frameborder' => '0',
34         'allowfullscreen' => 'allowfullscreen',
35       ],
36     ];
37     if ($language = $this->getLanguagePreference()) {
38       $embed_code['#query']['cc_lang_pref'] = $language;
39     }
40     return $embed_code;
41   }
42
43   /**
44    * Get the time index for when the given video starts.
45    *
46    * @return int
47    *   The time index where the video should start based on the URL.
48    */
49   protected function getTimeIndex() {
50     preg_match('/[&\?]t=(?<timeindex>\d+)/', $this->getInput(), $matches);
51     return isset($matches['timeindex']) ? $matches['timeindex'] : 0;
52   }
53
54   /**
55    * Extract the language preference from the URL for use in closed captioning.
56    *
57    * @return string|FALSE
58    *   The language preference if one exists or FALSE if one could not be found.
59    */
60   protected function getLanguagePreference() {
61     preg_match('/[&\?]hl=(?<language>[a-z\-]*)/', $this->getInput(), $matches);
62     return isset($matches['language']) ? $matches['language'] : FALSE;
63   }
64
65   /**
66    * {@inheritdoc}
67    */
68   public function getRemoteThumbnailUrl() {
69     $url = 'http://img.youtube.com/vi/%s/%s.jpg';
70     $high_resolution = sprintf($url, $this->getVideoId(), 'maxresdefault');
71     $backup = sprintf($url, $this->getVideoId(), 'mqdefault');
72     try {
73       $this->httpClient->head($high_resolution);
74       return $high_resolution;
75     }
76     catch (\Exception $e) {
77       return $backup;
78     }
79   }
80
81   /**
82    * {@inheritdoc}
83    */
84   public static function getIdFromInput($input) {
85     preg_match('/^https?:\/\/(www\.)?((?!.*list=)youtube\.com\/watch\?.*v=|youtu\.be\/)(?<id>[0-9A-Za-z_-]*)/', $input, $matches);
86     return isset($matches['id']) ? $matches['id'] : FALSE;
87   }
88
89 }