VimeoTwigExtension.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace Grav\Plugin\Vimeo\Twig;
  3. use Grav\Common\GravTrait;
  4. /**
  5. * Class VimeoTwigExtension
  6. * @package Grav\Plugin\Vimeo\Twig
  7. */
  8. class VimeoTwigExtension extends \Twig_Extension
  9. {
  10. use GravTrait;
  11. const VIMEO_PLAYER_URL = '//player.vimeo.com/video/';
  12. /**
  13. * Filters player parameters to only those not matching Vimeo defaults
  14. * @param array $params Player parameters
  15. * @return array
  16. */
  17. private function filterParameters($params=[])
  18. {
  19. $filtered = [];
  20. $grav = static::getGrav();
  21. $blueprints = $grav['config']->blueprints();
  22. foreach ($params as $key => $value) {
  23. // Skip if string value is empty
  24. if (is_string($value)){
  25. $value = trim($value);
  26. if (empty($value)) continue;
  27. }
  28. // Skip if there is an default value and it's different to the looping parameter value
  29. $blueprint_param = $blueprints->get("plugins.vimeo.player_parameters.{$key}");
  30. if (isset($blueprint_param['default']) && ($blueprint_param['default'] == $value)) {
  31. continue;
  32. }
  33. if ($key == 'color') $value = str_replace('#', '', $value); // Remove # from hexadecimal color value
  34. $filtered[$key] = $value;
  35. }
  36. return $filtered;
  37. }
  38. /**
  39. * Returns an array of available twig functions
  40. * @return array
  41. */
  42. public function getFunctions()
  43. {
  44. return [
  45. new \Twig_SimpleFunction('vimeo_embed_url', [$this, 'embedUrl']),
  46. new \Twig_SimpleFunction('vimeo_embed_video', [$this, 'embedVideo']),
  47. ];
  48. }
  49. /**
  50. * Builds the Vimeo embed url
  51. * @param string $video_id Vimeo Video ID
  52. * @param array $params Player parameters
  53. * @return string
  54. */
  55. public function embedUrl($video_id, $params = [])
  56. {
  57. $url = static::VIMEO_PLAYER_URL.$video_id;
  58. $params = $this->filterParameters($params);
  59. if ((!empty($params)) && ($query = http_build_query($params))) $url.= "?{$query}";
  60. return $url;
  61. }
  62. /**
  63. * Builds the Vimeo embed iframe
  64. * @param string $video_id Vimeo Video ID
  65. * @param array $params Player parameters
  66. * @param bool $div Surrounds the iframe code with a div element
  67. * @return string
  68. */
  69. public function embedVideo($video_id, $params = [], $div=true)
  70. {
  71. $url = $this->embedUrl($video_id, $params);
  72. $code = "<iframe src=\"{$url}\" frameborder=\"0\" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>";
  73. if ($div) $code = "<div class=\"grav-vimeo\">{$code}</div>";
  74. return $code;
  75. }
  76. }