Completed
Push — develop ( 13bd87...d494ed )
by Paul
02:08
created

Oembed::modifyRequest()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 10
nc 4
nop 2
1
<?php
2
3
namespace GeminiLabs\Castor;
4
5
use GeminiLabs\Castor\Helpers\Utility;
6
use DomDocument;
7
8
class Oembed
9
{
10
	public $oembed;
11
	public $utility;
12
13
	public $vimeo = [
14
		'api', 'autopause', 'autoplay', 'byline', 'color', 'height', 'loop', 'player_id',
15
		'portrait', 'title', 'width',
16
	];
17
18
	public $youtube = [
19
		'autohide', 'autoplay', 'cc_load_policy', 'color', 'controls', 'disablekb', 'enablejsapi',
20
		'end', 'fs', 'height', 'hl', 'iv_load_policy', 'list', 'listType', 'loop', 'modestbranding',
21
		'origin', 'playerapiid', 'playlist', 'playsinline', 'rel', 'showinfo', 'start', 'theme',
22
		'width',
23
	];
24
25
	public function __construct( Utility $utility )
26
	{
27
		$this->oembed  = _wp_oembed_get_object();
28
		$this->utility = $utility;
29
	}
30
31
	public function request( $url, $args = '' )
32
	{
33
		$request = $this->oembed->fetch( $this->oembed->get_provider( $url ), $url, [
34
			'width'  => 1280,
35
			'height' => 1280,
36
		]);
37
		return $request
38
			? $this->modifyRequest( $request, $args )
39
			: $request;
40
	}
41
42
	protected function domLoad( $html )
43
	{
44
		$dom = new DomDocument;
45
		$dom->loadHTML( $html );
46
		return $dom;
47
	}
48
49
	protected function modifyRequest( $request, $args )
50
	{
51
		$providerName = strtolower( $request->provider_name );
52
		$provider = property_exists( $this, $providerName )
53
			? $this->$providerName
54
			: [];
55
56
		$method = $this->utility->buildMethodName( $providerName . '_request', 'modify' );
57
58
		if( method_exists( $this, $method )) {
59
			return call_user_func( [$this, $method], $request, array_intersect_key(
60
				wp_parse_args( $args ),
61
				array_flip( $provider )
62
			));
63
		}
64
		return $request;
65
	}
66
67
	protected function modifyYoutubeRequest( $request, array $args )
68
	{
69
		$html = $this->domLoad( $request->html );
70
		$node = $html->getElementsByTagName( 'iframe' )->item(0);
71
		$url  = $node->getAttribute( 'src' );
72
73
		if( isset( $args['fs'] ) && $args['fs'] == 0 ) {
74
			$node->removeAttribute( 'allowfullscreen' );
75
		}
76
77
		$args['origin'] = urlencode( get_bloginfo( 'url' ));
78
79
		$node->setAttribute( 'src',
80
			add_query_arg( $args, remove_query_arg( 'feature', $url ))
81
		);
82
83
		$request->html = $html->saveHTML( $node );
84
85
		return $request;
86
	}
87
}
88