Completed
Push — master ( ccb772...cc3ecb )
by Stephanie
02:32
created

FrmFormApi   B

Complexity

Total Complexity 43

Size/Duplication

Total Lines 217
Duplicated Lines 5.53 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
dl 12
loc 217
rs 8.96
c 0
b 0
f 0
wmc 43
lcom 1
cbo 1

15 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A set_license() 0 9 3
A get_license() 0 3 1
A set_cache_key() 0 3 2
A get_cache_key() 0 3 1
B get_api_info() 0 37 10
A api_url() 0 3 1
A skip_categories() 0 3 1
B get_addon_for_license() 9 18 7
A get_pro_updater() 0 10 3
A get_cached() 3 16 6
A set_cached() 0 9 1
A reset_cached() 0 3 1
A error_for_license() 0 8 2
A get_error_from_response() 0 12 3

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like FrmFormApi often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use FrmFormApi, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
class FrmFormApi {
4
5
	protected $license = '';
6
	protected $cache_key = '';
7
	protected $cache_timeout = '+6 hours';
8
9
	/**
10
	 * @since 3.06
11
	 */
12
	public function __construct( $license = null ) {
13
		$this->set_license( $license );
14
		$this->set_cache_key();
15
	}
16
17
	/**
18
	 * @since 3.06
19
	 */
20
	private function set_license( $license ) {
21
		if ( $license === null ) {
22
			$edd_update = $this->get_pro_updater();
23
			if ( ! empty( $edd_update ) ) {
24
				$license = $edd_update->license;
25
			}
26
		}
27
		$this->license = $license;
28
	}
29
30
	/**
31
	 * @since 3.06
32
	 * @return string
33
	 */
34
	public function get_license() {
35
		return $this->license;
36
	}
37
38
	/**
39
	 * @since 3.06
40
	 */
41
	protected function set_cache_key() {
42
		$this->cache_key = 'frm_addons_l' . ( empty( $this->license ) ? '' : md5( $this->license ) );
43
	}
44
45
	/**
46
	 * @since 3.06
47
	 * @return string
48
	 */
49
	public function get_cache_key() {
50
		return $this->cache_key;
51
	}
52
53
	/**
54
	 * @since 3.06
55
	 * @return array
56
	 */
57
	public function get_api_info() {
58
		$url = $this->api_url();
59
		if ( ! empty( $this->license ) ) {
60
			$url .= '?l=' . urlencode( base64_encode( $this->license ) );
61
		}
62
63
		$addons = $this->get_cached();
64
		if ( ! empty( $addons ) ) {
65
			return $addons;
66
		}
67
68
		$response = wp_remote_get( $url );
69
		if ( is_array( $response ) && ! is_wp_error( $response ) ) {
70
			$addons = $response['body'];
71
			if ( ! empty( $addons ) ) {
72
				$addons = json_decode( $addons, true );
73
74
				foreach ( $addons as $k => $addon ) {
75
					if ( ! isset( $addon['categories'] ) ) {
76
						continue;
77
					}
78
					$cats = array_intersect( $this->skip_categories(), $addon['categories'] );
79
					if ( ! empty( $cats ) ) {
80
						unset( $addons[ $k ] );
81
					}
82
				}
83
84
				$this->set_cached( $addons );
85
			}
86
		}
87
88
		if ( empty( $addons ) ) {
89
			return array();
90
		}
91
92
		return $addons;
93
	}
94
95
	/**
96
	 * @since 3.06
97
	 */
98
	protected function api_url() {
99
		return 'https://formidableforms.com/wp-json/s11edd/v1/updates/';
100
	}
101
102
	/**
103
	 * @since 3.06
104
	 */
105
	protected function skip_categories() {
106
		return array( 'WordPress Form Templates', 'WordPress Form Style Templates' );
107
	}
108
109
	/**
110
	 * @since 3.06
111
	 *
112
	 * @param object $license_plugin The FrmAddon object
113
	 *
114
	 * @return array
115
	 */
116
	public function get_addon_for_license( $license_plugin, $addons = array() ) {
117
		if ( empty( $addons ) ) {
118
			$addons = $this->get_api_info();
119
		}
120
		$download_id = $license_plugin->download_id;
121
		$plugin      = array();
122 View Code Duplication
		if ( empty( $download_id ) && ! empty( $addons ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
123
			foreach ( $addons as $addon ) {
124
				if ( strtolower( $license_plugin->plugin_name ) == strtolower( $addon['title'] ) ) {
125
					return $addon;
126
				}
127
			}
128
		} elseif ( isset( $addons[ $download_id ] ) ) {
129
			$plugin = $addons[ $download_id ];
130
		}
131
132
		return $plugin;
133
	}
134
135
	/**
136
	 * @since 3.06
137
	 */
138
	public function get_pro_updater() {
139
		if ( FrmAppHelper::pro_is_installed() && is_callable( 'FrmProAppHelper::get_updater' ) ) {
140
			$updater = FrmProAppHelper::get_updater();
141
			$this->set_license( $updater->license );
142
143
			return $updater;
144
		}
145
146
		return false;
147
	}
148
149
	/**
150
	 * @since 3.06
151
	 * @return array
152
	 */
153
	protected function get_cached() {
154
		$cache = get_option( $this->cache_key );
155
156 View Code Duplication
		if ( empty( $cache ) || empty( $cache['timeout'] ) || current_time( 'timestamp' ) > $cache['timeout'] ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
157
			return false; // Cache is expired
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by FrmFormApi::get_cached of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
158
		}
159
160
		$version     = FrmAppHelper::plugin_version();
161
		$for_current = isset( $cache['version'] ) && $cache['version'] == $version;
162
		if ( ! $for_current ) {
163
			// Force a new check.
164
			return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by FrmFormApi::get_cached of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
165
		}
166
167
		return json_decode( $cache['value'], true );
168
	}
169
170
	/**
171
	 * @since 3.06
172
	 */
173
	protected function set_cached( $addons ) {
174
		$data = array(
175
			'timeout' => strtotime( $this->cache_timeout, current_time( 'timestamp' ) ),
176
			'value'   => json_encode( $addons ),
177
			'version' => FrmAppHelper::plugin_version(),
178
		);
179
180
		update_option( $this->cache_key, $data, 'no' );
181
	}
182
183
	/**
184
	 * @since 3.06
185
	 */
186
	public function reset_cached() {
187
		delete_option( $this->cache_key );
188
	}
189
190
	/**
191
	 * @since 3.06
192
	 * @return array
193
	 */
194
	public function error_for_license() {
195
		$errors = array();
196
		if ( ! empty( $this->license ) ) {
197
			$errors = $this->get_error_from_response();
198
		}
199
200
		return $errors;
201
	}
202
203
	/**
204
	 * @since 3.06
205
	 * @return array
206
	 */
207
	public function get_error_from_response( $addons = array() ) {
208
		if ( empty( $addons ) ) {
209
			$addons = $this->get_api_info();
210
		}
211
		$errors = array();
212
		if ( isset( $addons['error'] ) ) {
213
			$errors[] = $addons['error']['message'];
214
			do_action( 'frm_license_error', $addons['error'] );
215
		}
216
217
		return $errors;
218
	}
219
}
220