Completed
Pull Request — develop (#1394)
by Naveen
03:27
created

Config::may_be_get_attachment_id()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 3
nop 0
dl 0
loc 34
rs 9.376
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
	/**
17
	 * Config constructor.
18
	 *
19
	 * @param $admin_setup \Wordlift_Admin_Setup
20
	 * @param $key_validation_service \Wordlift_Key_Validation_Service
21
	 */
22
	public function __construct( $admin_setup, $key_validation_service ) {
23
24
		$this->admin_setup            = $admin_setup;
25
		$this->key_validation_service = $key_validation_service;
26
		add_action( 'wp_ajax_nopriv_wl_config_plugin', array( $this, 'config' ) );
27
28
	}
29
30
	/**
31
	 * Check if the key is valid and also not bound to any domain.
32
	 *
33
	 * @param $key string
34
	 *
35
	 * @return bool
36
	 */
37
	private function is_key_valid_and_not_bound_to_any_domain( $key ) {
38
		$account_info = $this->key_validation_service->get_account_info( $key );
39
40
		/**
41
		 * we need to check if the key is not associated with any account
42
		 * before setting it, we should check if the url is null.
43
		 */
44
		if ( is_wp_error( $account_info )
45
		     || wp_remote_retrieve_response_code( $account_info ) !== 200 ) {
46
			return false;
47
		}
48
49
		$account_info_json = $account_info['body'];
50
51
		$account_info_data = json_decode( $account_info_json, true );
52
53
		if ( ! $account_info_data ) {
54
			// Invalid json returned by api.
55
			return false;
56
		}
57
58
		$site_url = apply_filters( 'wl_production_site_url', untrailingslashit( get_option( 'home' ) ) );
59
60
61
		if ( $account_info_data['url'] === null) {
62
			return true;
63
		}
64
65
		// Check if the key belongs to same site.
66
		if ( $site_url !== untrailingslashit( $account_info_data['url'] ) ) {
67
			// key already associated with another account.
68
			return false;
69
		}
70
71
		return false;
72
	}
73
74
75
	public function config() {
76
77
		// Perform validation check for all the parameters.
78
		$required_fields = array(
79
			'diagnostic',
80
			'vocabulary',
81
			'language',
82
			'country',
83
			'publisherName',
84
			'publisher',
85
			'license'
86
		);
87
88
		// validate all the fields before processing
89
		foreach ( $required_fields as $field ) {
90
			if ( ! array_key_exists( $field, $_POST ) ) {
91
				wp_send_json_error( sprintf( __( 'Field %s is required', 'wordlift' ), $field ), 422 );
92
93
				return;
94
			}
95
		}
96
97
		$key = (string) $_POST['license'];
98
99
		if ( ! $this->is_key_valid_and_not_bound_to_any_domain( $key ) ) {
100
			wp_send_json_error( __( 'Key is not valid or associated with other domain', 'wordlift' ), 403 );
101
102
			// exit if not valid.
103
			return;
104
		}
105
106
		$this->admin_setup->save_configuration( $this->get_params() );
107
108
109
		wp_send_json_success( __( 'Configuration Saved', 'wordlift' ) );
110
	}
111
112
	/**
113
	 *
114
	 * @return array
115
	 */
116
	private function get_params() {
117
118
		$attachment_id = $this->may_be_get_attachment_id();
119
120
		$params = array(
121
			'key'              => (string) $_POST['license'],
122
			'vocabulary'       => (string) $_POST['vocabulary'],
123
			'wl-site-language' => (string) $_POST['language'],
124
			'wl-country-code'  => (string) $_POST['country'],
125
			'name'             => (string) $_POST['publisherName'],
126
			'user_type'        => (string) $_POST['publisher'],
127
			'logo'             => $attachment_id
128
		);
129
130
		if ( (bool) $_POST['diagnostic'] ) {
131
			$params['share-diagnostic'] = 'on';
132
		}
133
134
		return $params;
135
	}
136
137
	/**
138
	 * @return int | bool
139
	 */
140
	private function may_be_get_attachment_id() {
141
		// if image or image extension not posted then return false.
142
		if ( ! isset( $_POST['image'] ) || ! isset( $_POST['imageExtension'] ) ) {
143
			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...
144
		}
145
146
		$allowed_extensions = array( 'png', 'jpeg', 'jpg' );
147
		$image_string       = (string) $_POST['image'];
148
		$image_ext          = (string) $_POST['imageExtension'];
149
150
		if ( ! in_array( $image_ext, $allowed_extensions ) ) {
151
			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...
152
		}
153
154
		$image_decoded_string = base64_decode( $image_string );
155
156
		$upload_dir = wp_upload_dir();
157
158
		$file_path = $upload_dir['path'] . DIRECTORY_SEPARATOR . md5( $image_string ) . "." . $image_ext;
159
160
		file_put_contents( $file_path, $image_decoded_string );
161
162
		$attachment_id = wp_insert_attachment( array(
163
			'post_status'    => 'inherit',
164
			'post_mime_type' => "image/$image_ext"
165
		), $file_path );
166
167
		// Generate the metadata for the attachment, and update the database record.
168
		$attachment_data = wp_generate_attachment_metadata( $attachment_id, $file_path );
169
		// Update the attachment metadata.
170
		wp_update_attachment_metadata( $attachment_id, $attachment_data );
171
172
		return $attachment_id;
173
	}
174
175
}