Completed
Pull Request — develop (#1350)
by Naveen
03:08
created

Youtube_Client::get_api_key()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Wordlift\Videoobject\Provider\Client;
4
5
use Wordlift\Common\Singleton;
6
7
/**
8
 * @since 3.31.0
9
 * @author Naveen Muthusamy <[email protected]>
10
 * This class acts an api client for youtube.
11
 */
12
class Youtube_Client extends Singleton implements Client {
13
14
	static $requests_sent = 0;
15
16
	public static function get_api_key_option_name() {
17
		return "__wl_video_object_youtube_api_key";
18
	}
19
20
	public static function get_api_key() {
21
		return get_option( self::get_api_key_option_name(), false );
22
	}
23
24
	public function get_api_url() {
25
		return 'https://www.googleapis.com/youtube/v3/videos';
26
	}
27
28
29
	public function get_data( $video_urls ) {
30
		$video_ids = $this->get_video_ids_as_string( $video_urls );
31
		$url       = add_query_arg( array(
32
			'part' => 'snippet,contentDetails,statistics,liveStreamingDetails',
33
			'id'   => $video_ids,
34
			'key'  => $this->get_api_key()
35
		), $this->get_api_url() );
36
37
		$response = wp_remote_get( $url );
38
39
		self::$requests_sent += 1;
40
41
		return wp_remote_retrieve_body( $response );
42
	}
43
44
45
	private function get_video_ids_as_string( $video_urls ) {
46
		// validate the urls.
47
		$video_urls = array_filter( $video_urls, function ( $url ) {
48
			return filter_var( $url, FILTER_VALIDATE_URL );
49
		} );
50
51
		// extract the video ids.
52
		return join( ",", self::get_video_ids( $video_urls ) );
53
	}
54
55
56
	private static function get_video_ids( $video_urls ) {
57
58
		$video_ids = array_map( function ( $url ) {
59
60
			$parsed_url_data = parse_url( $url );
61
62
			if ( ( ! is_array( $parsed_url_data ) || ! array_key_exists( 'query', $parsed_url_data ) )
63
			     && strpos( $url, "youtu.be" ) === false ) {
64
				return false;
65
			}
66
			// For youtu.be urls, the video id is present in path.
67
			if ( strpos( $url, "youtu.be" ) !== false ) {
68
				$parsed_url_data['query'] = "v=" . substr( $parsed_url_data['path'], 1 );
69
			}
70
71
			$query_data_result = array();
72
			parse_str( $parsed_url_data['query'], $query_data_result );
73
74
			if ( ! array_key_exists( 'v', $query_data_result ) ) {
75
				return false;
76
			}
77
78
			return $query_data_result['v'];
79
80
		}, $video_urls );
81
82
		return array_values( array_filter( $video_ids ) );
83
84
	}
85
86
87
}