class-wpml-tp-api-request.php
2.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
<?php
class WPML_TP_API_Request {
const API_VERSION = 1.1;
/** @var string */
private $url;
/** @var array */
private $params = array( 'api_version' => self::API_VERSION );
/** @var string */
private $method = 'GET';
/** @var bool */
private $has_api_response = true;
/**
* @param string $url
*/
public function __construct( $url ) {
if ( empty( $url ) ) {
throw new InvalidArgumentException( 'Url cannot be empty' );
}
$this->url = $url;
}
/**
* @param array $params
*/
public function set_params( array $params ) {
$this->params = array_merge( $this->params, $params );
}
/**
* @param string $method
*/
public function set_method( $method ) {
if ( ! in_array( $method, array( 'GET', 'POST', 'PUT', 'DELETE', 'HEAD' ), true ) ) {
throw new InvalidArgumentException( 'HTTP request method has invalid value' );
}
$this->method = $method;
}
/**
* @param bool $has_api_response
*/
public function set_has_api_response( $has_api_response ) {
$this->has_api_response = (bool) $has_api_response;
}
/**
* @return string
*/
public function get_url() {
$url = $this->url;
if ( $this->get_params() ) {
list( $url, $params_used_in_path ) = $this->add_parameters_to_path( $url, $this->get_params() );
if ( 'GET' === $this->get_method() ) {
$url = $this->add_query_parameters( $params_used_in_path, $url );
}
}
return $url;
}
/**
* @return array
*/
public function get_params() {
return $this->params;
}
/**
* @return string
*/
public function get_method() {
return $this->method;
}
/**
* @return bool
*/
public function has_api_response() {
return $this->has_api_response;
}
private function add_parameters_to_path( $url, array $params ) {
$used_params = array();
if ( preg_match_all( '/\{.+?\}/', $url, $symbs ) ) {
foreach ( $symbs[0] as $symb ) {
$without_braces = preg_replace( '/\{|\}/', '', $symb );
if ( preg_match_all( '/\w+/', $without_braces, $indexes ) ) {
foreach ( $indexes[0] as $index ) {
if ( isset( $params[ $index ] ) ) {
$used_params[] = $index;
$value = $params[ $index ];
$url = preg_replace( preg_quote( "/$symb/" ), $value, $url );
}
}
}
}
}
return array( $url, $used_params );
}
/**
* @param $params_used_in_path
* @param $url
*
* @return string
*/
private function add_query_parameters( $params_used_in_path, $url ) {
$url .= '?' . preg_replace(
'/\%5B\d+\%5D/',
'%5B%5D',
wpml_http_build_query(
array_diff_key(
$this->get_params(),
array_fill_keys( $params_used_in_path, 1 )
)
)
);
return $url;
}
}