YoutubeTwigExtension.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. namespace Grav\Plugin\Youtube\Twig;
  3. use Grav\Common\Grav;
  4. class YoutubeTwigExtension extends \Twig_Extension
  5. {
  6. /**
  7. * Returns extension name.
  8. *
  9. * @return string
  10. */
  11. public function getName()
  12. {
  13. return 'YoutubeTwigExtension';
  14. }
  15. /**
  16. * {@inheritdoc}
  17. */
  18. public function getFunctions()
  19. {
  20. return [
  21. new \Twig_SimpleFunction('youtube_embed_url', [$this, 'embedUrl']),
  22. ];
  23. }
  24. /**
  25. * Builds YouTube video embed URL.
  26. *
  27. * @param string $video_id
  28. * @param array $player_parameters
  29. * @param bool $privacy_enhanced_mode
  30. * @return string
  31. */
  32. public function embedUrl($video_id, array $player_parameters = array(), $privacy_enhanced_mode = FALSE)
  33. {
  34. $grav = Grav::instance();
  35. // build base video embed URL (while respecting privacy enhanced mode setting)
  36. $url = 'https://www.youtube' . ($privacy_enhanced_mode ? '-nocookie' : '') . '.com/embed/' . $video_id;
  37. // filter player parameters to only those not matching YouTube defaults
  38. $filtered_player_parameters = array();
  39. foreach ($player_parameters as $key => $value) {
  40. $parameter_blueprint = $grav['config']->blueprints()->get('plugins.youtube.player_parameters.' . $key);
  41. // configured value matches YouTube default -> skip parameter
  42. if (isset($parameter_blueprint['default']) && $parameter_blueprint['default'] == $value) {
  43. continue;
  44. }
  45. $filtered_player_parameters[$key] = $value;
  46. }
  47. // append query string (if any)
  48. if (!empty($filtered_player_parameters) && ($query_string = http_build_query($filtered_player_parameters))) {
  49. $url .= '?' . $query_string;
  50. }
  51. return $url;
  52. }
  53. }