Passed
Push — master ( 8eca98...e5c4f5 )
by Paul
03:33
created

Cache::getCloudflareIps()   A

Complexity

Conditions 5
Paths 2

Size

Total Lines 23
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 5.3256

Importance

Changes 0
Metric Value
cc 5
eloc 16
nc 2
nop 0
dl 0
loc 23
ccs 13
cts 17
cp 0.7647
crap 5.3256
rs 9.4222
c 0
b 0
f 0
1
<?php
2
3
namespace GeminiLabs\SiteReviews\Database;
4
5
use GeminiLabs\SiteReviews\Application;
6
use GeminiLabs\SiteReviews\Database\SqlQueries;
7
8
class Cache
9
{
10
	const EXPIRY_TIME = WEEK_IN_SECONDS;
11
12
	/**
13
 	 * @return array
14
	 */
15 1
	public function getCloudflareIps()
16
	{
17 1
		$ipAddresses = get_transient( Application::ID.'_cloudflare_ips' );
18 1
		if( $ipAddresses === false ) {
19 1
			$ipAddresses = array_fill_keys( ['v4', 'v6'], [] );
20 1
			foreach( array_keys( $ipAddresses ) as $version ) {
21 1
				$url = 'https://www.cloudflare.com/ips-'.$version;
22 1
				$response = wp_remote_get( $url );
23 1
				if( is_wp_error( $response )) {
24
					glsr_log()->error( $response->get_error_message() );
25
					continue;
26
				}
27 1
				if(( $statusCode = wp_remote_retrieve_response_code( $response )) != '200' ) {
28
					glsr_log()->error( 'Unable to connect to '.$url.' ['.$statusCode.']' );
29
					continue;
30
				}
31 1
				$ipAddresses[$version] = array_filter(
32 1
					(array)preg_split( '/\R/', wp_remote_retrieve_body( $response ))
33
				);
34
			}
35 1
			set_transient( Application::ID.'_cloudflare_ips', $ipAddresses, static::EXPIRY_TIME );
36
		}
37 1
		return $ipAddresses;
38
	}
39
40
	/**
41
	 * @param string $metaKey
42
	 * @return array
43
	 */
44
	public function getReviewCountsFor( $metaKey )
45
	{
46
		$counts = wp_cache_get( Application::ID, $metaKey.'_count' );
47
		if( $counts === false ) {
48
			$counts = [];
49
			$results = glsr( SqlQueries::class )->getReviewCountsFor( $metaKey );
50
			foreach( $results as $result ) {
51
				$counts[$result->name] = $result->num_posts;
52
			}
53
			wp_cache_set( Application::ID, $counts, $metaKey.'_count' );
54
		}
55
		return $counts;
56
	}
57
58
	/**
59
	 * @return string
60
	 */
61
	public function getRemotePostTest()
62
	{
63
		$test = get_transient( Application::ID.'_remote_post_test' );
64
		if( $test === false ) {
65
			$response = wp_remote_post( 'https://api.wordpress.org/stats/php/1.0/' );
66
			$test = !is_wp_error( $response )
67
				&& in_array( $response['response']['code'], range( 200, 299 ))
68
				? 'Works'
69
				: 'Does not work';
70
			set_transient( Application::ID.'_remote_post_test', $test, static::EXPIRY_TIME );
71
		}
72
		return $test;
73
	}
74
}
75