Passed
Push — develop ( bb8938...5fd6ef )
by Remco
06:05 queued 02:16
created

Util::format_date()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 2
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * Util
4
 *
5
 * @author    Pronamic <[email protected]>
6
 * @copyright 2005-2018 Pronamic
7
 * @license   GPL-3.0-or-later
8
 * @package   Pronamic\WordPress\Pay
9
 */
10
11
namespace Pronamic\WordPress\Pay;
12
13
use DateTime;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Pronamic\WordPress\Pay\DateTime. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
14
use SimpleXMLElement;
15
use WP_Error;
16
17
/**
18
 * Title: WordPress utility class
19
 *
20
 * @author Remco Tolsma
21
 * @version 1.0
22
 */
23
class Util {
24
	/**
25
	 * Remote get body.
26
	 *
27
	 * @see https://developer.wordpress.org/reference/functions/wp_remote_request/
28
	 *
29
	 * @param string $url                    The URL to use for the remote request.
30
	 * @param int    $required_response_code The required response code.
31
	 * @param array  $args                   The WordPress HTTP API request arguments.
32
	 *
33
	 * @return string|WP_Error
34
	 */
35
	public static function remote_get_body( $url, $required_response_code = 200, array $args = array() ) {
36
		$result = wp_remote_request( $url, $args );
37
38
		if ( ! is_array( $result ) ) {
39
			return $result;
40
		}
41
42
		$response_code = wp_remote_retrieve_response_code( $result );
43
44
		if ( $response_code === $required_response_code ) {
45
			return wp_remote_retrieve_body( $result );
46
		}
47
48
		return new WP_Error(
49
			'wrong_response_code',
50
			sprintf(
51
				__( 'The response code (<code>%1$s<code>) was incorrect, required response code <code>%2$s</code>.', 'pronamic_ideal' ),
52
				$response_code,
53
				$required_response_code
54
			)
55
		);
56
	}
57
58
	/**
59
	 * SimpleXML load string.
60
	 *
61
	 * @param string $string The XML string to convert to a SimpleXMLElement object.
62
	 *
63
	 * @return SimpleXMLElement|WP_Error
64
	 */
65
	public static function simplexml_load_string( $string ) {
66
		$result = false;
67
68
		// Suppress all XML errors.
69
		$use_errors = libxml_use_internal_errors( true );
70
71
		// Load.
72
		$xml = simplexml_load_string( $string );
73
74
		if ( false !== $xml ) {
75
			$result = $xml;
76
		} else {
77
			$error = new WP_Error( 'simplexml_load_error', __( 'Could not load the XML string.', 'pronamic_ideal' ) );
78
79
			foreach ( libxml_get_errors() as $e ) {
80
				$error->add( 'libxml_error', $e->message, $e );
81
			}
82
83
			libxml_clear_errors();
84
85
			$result = $error;
86
		}
87
88
		// Set back to previous value.
89
		libxml_use_internal_errors( $use_errors );
90
91
		return $result;
92
	}
93
94
	/**
95
	 * Amount to cents.
96
	 *
97
	 * @param float $price The amount to convert to cents.
98
	 *
99
	 * @return int
100
	 */
101
	public static function amount_to_cents( $price ) {
102
		return round( $price * 100 );
103
	}
104
105
	/**
106
	 * Cents to amount.
107
	 *
108
	 * @param int $cents The numberof cents to convert to an amount.
109
	 *
110
	 * @return float
111
	 */
112
	public static function cents_to_amount( $cents ) {
113
		return $cents / 100;
114
	}
115
116
	/**
117
	 * Convert boolean to an numceric boolean.
118
	 *
119
	 * @see https://github.com/eet-nu/buckaroo-ideal/blob/master/lib/buckaroo-ideal/request.rb#L136
120
	 *
121
	 * @param boolean $boolean The boolean to convert to 1 or 0.
122
	 *
123
	 * @return int
124
	 */
125
	public static function boolean_to_numeric( $boolean ) {
126
		return $boolean ? 1 : 0;
127
	}
128
129
	/**
130
	 * Convert boolean to an string boolean.
131
	 *
132
	 * @see https://github.com/eet-nu/buckaroo-ideal/blob/master/lib/buckaroo-ideal/request.rb#L136
133
	 *
134
	 * @param boolean $boolean The boolean to convert to the string 'true' or 'false'.
135
	 *
136
	 * @return int
137
	 */
138
	public static function boolean_to_string( $boolean ) {
139
		return $boolean ? 'true' : 'false';
140
	}
141
142
	/**
143
	 * Format price.
144
	 *
145
	 * @see https://github.com/woothemes/woocommerce/blob/v2.2.3/includes/wc-formatting-functions.php#L306-L347
146
	 * @see https://github.com/woothemes/woocommerce/blob/v2.2.3/includes/wc-core-functions.php#L299-L376
147
	 *
148
	 * @param float  $amount   The amount to format.
149
	 * @param string $currency The currency code for the currency symbol.
150
	 *
151
	 * @return string
152
	 */
153
	public static function format_price( $amount, $currency = null ) {
154
		$float = filter_var( $amount, FILTER_VALIDATE_FLOAT );
155
156
		if ( false === $float ) {
157
			return;
158
		}
159
160
		$currency = ( null === $currency ) ? 'EUR' : $currency;
161
162
		$currency_symbol = $currency;
163
164
		switch ( $currency ) {
165
			case 'EUR':
166
				$currency_symbol = '€';
167
				break;
168
			case 'USD':
169
				$currency_symbol = '$';
170
				break;
171
		}
172
173
		// @see https://en.wikipedia.org/wiki/Non-breaking_space#Keyboard_entry_methods
174
		$non_breaking_space = ' ';
175
176
		return '' . $currency_symbol . $non_breaking_space . number_format_i18n( $float, 2 );
177
	}
178
179
	/**
180
	 * Format interval.
181
	 *
182
	 * @param int    $interval The interval number.
183
	 * @param string $period   The period indicator.
184
	 *
185
	 * @return string
186
	 */
187
	public static function format_interval( $interval, $period ) {
188
		switch ( $period ) {
189
			case 'D':
190
			case 'day':
191
			case 'days':
192
				return sprintf( _n( 'Every %s day', 'Every %s days', $interval, 'pronamic_ideal' ), $interval );
193
			case 'W':
194
			case 'week':
195
			case 'weeks':
196
				return sprintf( _n( 'Every %s week', 'Every %s weeks', $interval, 'pronamic_ideal' ), $interval );
197
			case 'M':
198
			case 'month':
199
			case 'months':
200
				return sprintf( _n( 'Every %s month', 'Every %s months', $interval, 'pronamic_ideal' ), $interval );
201
			case 'Y':
202
			case 'year':
203
			case 'years':
204
				return sprintf( _n( 'Every %s year', 'Every %s years', $interval, 'pronamic_ideal' ), $interval );
205
		}
206
	}
207
208
	/**
209
	 * Convert single interval period character to full name.
210
	 *
211
	 * @param string $interval_period string Short interval period (D, W, M or Y).
212
	 *
213
	 * @return string
214
	 */
215
	public static function to_interval_name( $interval_period ) {
216
		switch ( $interval_period ) {
217
			case 'D':
218
				return 'days';
219
			case 'W':
220
				return 'weeks';
221
			case 'M':
222
				return 'months';
223
			case 'Y':
224
				return 'years';
225
		}
226
227
		return $interval_period;
228
	}
229
230
	/**
231
	 * Format frequency.
232
	 *
233
	 * @param int $frequency The number of times.
234
	 *
235
	 * @return string
236
	 */
237
	public static function format_frequency( $frequency ) {
238
		if ( empty( $frequency ) ) {
239
			return _x( 'Unlimited', 'Recurring payment', 'pronamic_ideal' );
240
		}
241
242
		return sprintf( _n( '%s time', '%s times', $frequency, 'pronamic_ideal' ), $frequency );
243
	}
244
245
	/**
246
	 * Build URL with the specified parameters
247
	 *
248
	 * @param string $url        The URL to extend with specified parameters.
249
	 * @param array  $parameters The parameters to add to the specified URL.
250
	 *
251
	 * @return string
252
	 */
253
	public static function build_url( $url, array $parameters ) {
254
		return $url . '?' . _http_build_query( $parameters, null, '&' );
255
	}
256
257
	/**
258
	 * Get hidden inputs HTML for data.
259
	 *
260
	 * @param array $data Array with name and value pairs to convert to hidden HTML input eleemnts.
261
	 *
262
	 * @return string
263
	 */
264
	public static function html_hidden_fields( $data ) {
265
		$html = '';
266
267
		foreach ( $data as $name => $value ) {
268
			$html .= sprintf( '<input type="hidden" name="%s" value="%s" />', esc_attr( $name ), esc_attr( $value ) );
269
		}
270
271
		return $html;
272
	}
273
274
	/**
275
	 * Array to HTML attributes.
276
	 *
277
	 * @param array $attributes The key and value pairs to convert to HTML attributes.
278
	 *
279
	 * @return string
280
	 */
281
	public static function array_to_html_attributes( array $attributes ) {
282
		$html = '';
283
284
		foreach ( $attributes as $key => $value ) {
285
			$html .= sprintf( '%s="%s"', $key, esc_attr( $value ) );
286
		}
287
288
		$html = trim( $html );
289
290
		return $html;
291
	}
292
293
	/**
294
	 * Select options grouped.
295
	 *
296
	 * @param array  $groups         The grouped select options.
297
	 * @param string $selected_value The selected value.
298
	 *
299
	 * @return string
300
	 */
301
	public static function select_options_grouped( $groups, $selected_value = null ) {
302
		$html = '';
303
304
		if ( is_array( $groups ) ) {
0 ignored issues
show
introduced by
The condition is_array($groups) is always true.
Loading history...
305
			foreach ( $groups as $group ) {
306
				$optgroup = isset( $group['name'] ) && ! empty( $group['name'] );
307
308
				if ( $optgroup ) {
309
					$html .= '<optgroup label="' . $group['name'] . '">';
310
				}
311
312
				foreach ( $group['options'] as $value => $label ) {
313
					$html .= '<option value="' . $value . '" ' . selected( $selected_value, $value, false ) . '>' . $label . '</option>';
314
				}
315
316
				if ( $optgroup ) {
317
					$html .= '</optgroup>';
318
				}
319
			}
320
		}
321
322
		return $html;
323
	}
324
}
325