Completed
Push — develop ( 0e3a8a...448679 )
by Naveen
27s queued 11s
created

Config::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 3
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Wordlift\Configuration;
4
5
6
class Config {
7
	/**
8
	 * @var \Wordlift_Admin_Setup
9
	 */
10
	private $admin_setup;
11
	/**
12
	 * @var \Wordlift_Key_Validation_Service
13
	 */
14
	private $key_validation_service;
15
	/**
16
	 * @var \Wordlift_Configuration_Service
17
	 */
18
	private $configuration_service;
19
20
	/**
21
	 * Config constructor.
22
	 *
23
	 * @param $admin_setup \Wordlift_Admin_Setup
24
	 * @param $key_validation_service \Wordlift_Key_Validation_Service
25
	 * @param $configuration_service \Wordlift_Configuration_Service
26
	 */
27
	public function __construct( $admin_setup, $key_validation_service, $configuration_service ) {
28
29
		$this->admin_setup            = $admin_setup;
30
		$this->key_validation_service = $key_validation_service;
31
		$this->configuration_service = $configuration_service;
32
		add_action( 'wp_ajax_nopriv_wl_config_plugin', array( $this, 'config' ) );
33
34
	}
35
36
	/**
37
	 * Check if the key is valid and also not bound to any domain.
38
	 *
39
	 * @param $key string
40
	 *
41
	 * @return bool
42
	 */
43
	private function is_key_valid_and_not_bound_to_any_domain( $key ) {
44
		$account_info = $this->key_validation_service->get_account_info( $key );
45
46
		/**
47
		 * we need to check if the key is not associated with any account
48
		 * before setting it, we should check if the url is null.
49
		 */
50
		if ( is_wp_error( $account_info )
51
		     || wp_remote_retrieve_response_code( $account_info ) !== 200 ) {
52
			return false;
53
		}
54
55
		$account_info_json = $account_info['body'];
56
57
		$account_info_data = json_decode( $account_info_json, true );
58
59
		if ( ! $account_info_data ) {
60
			// Invalid json returned by api.
61
			return false;
62
		}
63
64
		$site_url = apply_filters( 'wl_production_site_url', untrailingslashit( get_option( 'home' ) ) );
65
66
67
		if ( $account_info_data['url'] === null) {
68
			return true;
69
		}
70
71
		// Check if the key belongs to same site.
72
		if ( $site_url !== untrailingslashit( $account_info_data['url'] ) ) {
73
			// key already associated with another account.
74
			return false;
75
		}
76
77
		// Return true if the key domain and site domain are the same.
78
		return true;
79
	}
80
81
82
	public function config() {
83
84
		// Perform validation check for all the parameters.
85
		$required_fields = array(
86
			'diagnostic',
87
			'vocabulary',
88
			'language',
89
			'country',
90
			'publisherName',
91
			'publisher',
92
			'license'
93
		);
94
95
		header('Access-Control-Allow-Origin: *');
96
97
		// validate all the fields before processing
98
		foreach ( $required_fields as $field ) {
99
			if ( ! array_key_exists( $field, $_POST ) ) {
100
				wp_send_json_error( sprintf( __( 'Field %s is required', 'wordlift' ), $field ), 422 );
101
102
				return;
103
			}
104
		}
105
106
		$key = (string) $_POST['license'];
107
108
		if ( ! $this->is_key_valid_and_not_bound_to_any_domain( $key ) ) {
109
			wp_send_json_error( __( 'Key is not valid or associated with other domain', 'wordlift' ), 403 );
110
111
			// exit if not valid.
112
			return;
113
		}
114
115
116
		// check if key is already configured, if yes then dont save settings.
117
		if ( $this->configuration_service->get_key() ) {
118
			wp_send_json_error( __( 'Key already configured.', 'wordlift' ), 403 );
119
120
			// key already configured
121
			return;
122
		}
123
124
		$this->admin_setup->save_configuration( $this->get_params() );
125
126
127
		wp_send_json_success( __( 'Configuration Saved', 'wordlift' ) );
128
	}
129
130
	/**
131
	 *
132
	 * @return array
133
	 */
134
	private function get_params() {
135
136
		$attachment_id = $this->may_be_get_attachment_id();
137
138
		$params = array(
139
			'key'              => (string) $_POST['license'],
140
			'vocabulary'       => (string) $_POST['vocabulary'],
141
			'wl-site-language' => (string) $_POST['language'],
142
			'wl-country-code'  => (string) $_POST['country'],
143
			'name'             => (string) $_POST['publisherName'],
144
			'user_type'        => (string) $_POST['publisher'],
145
			'logo'             => $attachment_id
146
		);
147
148
		if ( (bool) $_POST['diagnostic'] ) {
149
			$params['share-diagnostic'] = 'on';
150
		}
151
152
		return $params;
153
	}
154
155
	/**
156
	 * @return int | bool
157
	 */
158
	private function may_be_get_attachment_id() {
159
160
		// if image or image extension not posted then return false.
161
		if ( ! isset( $_POST['image'] ) || ! isset( $_POST['imageExtension'] ) ) {
162
			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 Wordlift\Configuration\C...ay_be_get_attachment_id of type integer.

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...
163
		}
164
165
		$allowed_extensions = array( 'png', 'jpeg', 'jpg' );
166
		$image_string       = (string) $_POST['image'];
167
		$image_ext          = (string) $_POST['imageExtension'];
168
169
		if ( ! in_array( $image_ext, $allowed_extensions ) ) {
170
			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 Wordlift\Configuration\C...ay_be_get_attachment_id of type integer.

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...
171
		}
172
173
		$image_decoded_string = base64_decode( $image_string );
174
175
		$upload_dir = wp_upload_dir();
176
177
		$file_path = $upload_dir['path'] . DIRECTORY_SEPARATOR . md5( $image_string ) . "." . $image_ext;
178
179
		file_put_contents( $file_path, $image_decoded_string );
180
181
		$attachment_id = wp_insert_attachment( array(
182
			'post_status'    => 'inherit',
183
			'post_mime_type' => "image/$image_ext"
184
		), $file_path );
185
186
		// Generate the metadata for the attachment, and update the database record.
187
		$attachment_data = wp_generate_attachment_metadata( $attachment_id, $file_path );
188
		// Update the attachment metadata.
189
		wp_update_attachment_metadata( $attachment_id, $attachment_data );
190
191
		return $attachment_id;
192
	}
193
194
}
195