Completed
Push — master ( 159d3b...c30b21 )
by David
02:37
created

Wordlift_Key_Validation_Service   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
dl 0
loc 41
rs 10
c 0
b 0
f 0
wmc 4
lcom 0
cbo 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A is_valid() 0 8 2
A validate_key() 0 14 2
1
<?php
2
/**
3
 * Wordlift_Key_Validation_Service class
4
 *
5
 * The {@link Wordlift_Key_Validation_Service} class provides WordLift's key validation services.
6
 *
7
 * @link    https://wordlift.io
8
 *
9
 * @package Wordlift
10
 * @since   3.9.0
11
 */
12
13
/**
14
 * Define the {@link Wordlift_Key_Validation_Service} class.
15
 *
16
 * @since 3.9.0
17
 */
18
class Wordlift_Key_Validation_Service {
19
20
	/**
21
	 * Validate the provided key.
22
	 *
23
	 * @since 3.9.0
24
	 *
25
	 * @param string $key WordLift's key to validate.
26
	 *
27
	 * @return bool True if the key is valid, otherwise false.
28
	 */
29
	public function is_valid( $key ) {
30
31
		// Request the dataset URI as a way to validate the key
32
		$response = wp_remote_get( wl_configuration_get_accounts_by_key_dataset_uri( $key ), unserialize( WL_REDLINK_API_HTTP_OPTIONS ) );
33
34
		// If the response is valid, the key is valid.
35
		return ! is_wp_error( $response ) && 200 === (int) $response['response']['code'];
36
	}
37
38
	/**
39
	 * This function is hooked to the `wl_validate_key` AJAX call.
40
	 *
41
	 * @since 3.9.0
42
	 */
43
	public function validate_key() {
0 ignored issues
show
Coding Style introduced by
validate_key uses the super-global variable $_POST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
44
45
		// Ensure we don't have garbage before us.
46
		ob_clean();
47
48
		// Check if we have a key.
49
		if ( ! isset( $_POST['key'] ) ) {
50
			wp_send_json_error( 'The key parameter is required.' );
51
		}
52
53
		// Set a response with valid set to true or false according to the key validity.
54
		wp_send_json( array( 'valid' => $this->is_valid( $_POST['key'] ) ) );
55
56
	}
57
58
}
59