Completed
Pull Request — develop (#1394)
by
unknown
02:59
created

Config::config()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 47

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
nc 7
nop 0
dl 0
loc 47
rs 8.8452
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 false;
78
	}
79
80
81
	public function config() {
82
83
		// Perform validation check for all the parameters.
84
		$required_fields = array(
85
			'diagnostic',
86
			'vocabulary',
87
			'language',
88
			'country',
89
			'publisherName',
90
			'publisher',
91
			'license'
92
		);
93
94
		header('Access-Control-Allow-Origin: *');
95
96
		// validate all the fields before processing
97
		foreach ( $required_fields as $field ) {
98
			if ( ! array_key_exists( $field, $_POST ) ) {
99
				wp_send_json_error( sprintf( __( 'Field %s is required', 'wordlift' ), $field ), 422 );
100
101
				return;
102
			}
103
		}
104
105
		$key = (string) $_POST['license'];
106
107
		if ( ! $this->is_key_valid_and_not_bound_to_any_domain( $key ) ) {
108
			wp_send_json_error( __( 'Key is not valid or associated with other domain', 'wordlift' ), 403 );
109
110
			// exit if not valid.
111
			return;
112
		}
113
114
115
		// check if key is already configured, if yes then dont save settings.
116
		if ( $this->configuration_service->get_key() ) {
117
			wp_send_json_error( __( 'Key already configured.', 'wordlift' ), 403 );
118
119
			// key already configured
120
			return;
121
		}
122
123
		$this->admin_setup->save_configuration( $this->get_params() );
124
125
126
		wp_send_json_success( __( 'Configuration Saved', 'wordlift' ) );
127
	}
128
129
	/**
130
	 *
131
	 * @return array
132
	 */
133
	private function get_params() {
134
135
		$attachment_id = $this->may_be_get_attachment_id();
136
137
		$params = array(
138
			'key'              => (string) $_POST['license'],
139
			'vocabulary'       => (string) $_POST['vocabulary'],
140
			'wl-site-language' => (string) $_POST['language'],
141
			'wl-country-code'  => (string) $_POST['country'],
142
			'name'             => (string) $_POST['publisherName'],
143
			'user_type'        => (string) $_POST['publisher'],
144
			'logo'             => $attachment_id
145
		);
146
147
		if ( (bool) $_POST['diagnostic'] ) {
148
			$params['share-diagnostic'] = 'on';
149
		}
150
151
		return $params;
152
	}
153
154
	/**
155
	 * @return int | bool
156
	 */
157
	private function may_be_get_attachment_id() {
158
159
		// if image or image extension not posted then return false.
160
		if ( ! isset( $_POST['image'] ) || ! isset( $_POST['imageExtension'] ) ) {
161
			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...
162
		}
163
164
		$allowed_extensions = array( 'png', 'jpeg', 'jpg' );
165
		$image_string       = (string) $_POST['image'];
166
		$image_ext          = (string) $_POST['imageExtension'];
167
168
		if ( ! in_array( $image_ext, $allowed_extensions ) ) {
169
			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...
170
		}
171
172
		$image_decoded_string = base64_decode( $image_string );
173
174
		$upload_dir = wp_upload_dir();
175
176
		$file_path = $upload_dir['path'] . DIRECTORY_SEPARATOR . md5( $image_string ) . "." . $image_ext;
177
178
		file_put_contents( $file_path, $image_decoded_string );
179
180
		$attachment_id = wp_insert_attachment( array(
181
			'post_status'    => 'inherit',
182
			'post_mime_type' => "image/$image_ext"
183
		), $file_path );
184
185
		// Generate the metadata for the attachment, and update the database record.
186
		$attachment_data = wp_generate_attachment_metadata( $attachment_id, $file_path );
187
		// Update the attachment metadata.
188
		wp_update_attachment_metadata( $attachment_id, $attachment_data );
189
190
		return $attachment_id;
191
	}
192
193
}
194