Completed
Pull Request — develop (#1249)
by Naveen
02:49
created

Key_Validation_Notice   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 81
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
dl 0
loc 81
rs 10
c 0
b 0
f 0
wmc 8
lcom 1
cbo 3

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 12 2
A get_notification_template() 0 6 1
A is_key_valid() 0 15 2
A display_key_validation_notice() 0 18 3
1
<?php
2
3
namespace Wordlift\Admin;
4
5
use Wordlift\Cache\Ttl_Cache;
6
7
/**
8
 * @since 3.28.0
9
 * @author Naveen Muthusamy <[email protected]>
10
 */
11
class Key_Validation_Notice {
12
13
	const CACHE_KEY = 'is_key_valid';
14
15
	/**
16
	 * @var \Wordlift_Key_Validation_Service
17
	 */
18
	private $key_validation_service;
19
20
	/**
21
	 * @var \Wordlift_Configuration_Service
22
	 */
23
	private $configuration_service;
24
	/**
25
	 * @var Ttl_Cache
26
	 */
27
	private $ttl_cache_service;
28
29
	/**
30
	 * Key_Validation_Notice constructor.
31
	 *
32
	 * @param \Wordlift_Key_Validation_Service $key_validation_service
33
	 * @param \Wordlift_Configuration_Service $configuration_service
34
	 */
35
	public function __construct( $key_validation_service, $configuration_service ) {
36
37
		$this->key_validation_service = $key_validation_service;
38
39
		$this->configuration_service = $configuration_service;
40
41
		$this->ttl_cache_service = new Ttl_Cache( 'key-validation-notification', 60 * 60 * 8 );
42
43
		if ( apply_filters( 'wl_feature__enable__notices', true ) ) {
44
			$this->display_key_validation_notice();
45
		}
46
	}
47
48
49
	public function get_notification_template() {
50
		return <<<EOF
51
<p></p>
52
EOF;
53
54
	}
55
56
	private function is_key_valid() {
57
58
		$key = $this->configuration_service->get_key();
59
60
		// Check cache if the result is present, if not get the results
61
		// save it and return the data.
62
		if ( $this->ttl_cache_service->get( self::CACHE_KEY ) !== null ) {
63
			return $this->ttl_cache_service->get( self::CACHE_KEY );
64
		}
65
66
		$is_valid = $this->key_validation_service->is_key_valid( $key );
67
		$this->ttl_cache_service->put( self::CACHE_KEY, $is_valid );
68
69
		return $is_valid;
70
	}
71
72
	private function display_key_validation_notice() {
73
		add_action( 'admin_notices', function () {
74
75
			$key = $this->configuration_service->get_key();
76
77
			if ( ! $key ) {
78
				// Dont show warning or make API call, return early.
79
				return;
80
			}
81
82
			if ( $this->is_key_valid() ) {
83
				return;
84
			}
85
86
			echo $this->get_notification_template();
87
88
		} );
89
	}
90
91
}
92
93