-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcpfm-payload-helper.php
More file actions
104 lines (84 loc) · 2.17 KB
/
Copy pathcpfm-payload-helper.php
File metadata and controls
104 lines (84 loc) · 2.17 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
<?php
/**
* Encode/decode server_info and extra_details for migration-safe storage.
*
* Supports legacy PHP-serialized strings, JSON strings, and raw arrays from REST clients.
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! function_exists( 'cpfm_decode_payload' ) ) {
/**
* Decode a stored or incoming payload into an associative array.
*
* @param mixed $raw Value from the database, request, or REST param.
* @return array<string, mixed>
*/
function cpfm_decode_payload( $raw ) {
if ( empty( $raw ) && ! is_array( $raw ) ) {
return array();
}
if ( is_array( $raw ) ) {
return $raw;
}
if ( ! is_string( $raw ) ) {
return array();
}
$raw = wp_unslash( $raw );
if ( cpfm_payload_is_json_string( $raw ) ) {
$decoded = json_decode( $raw, true );
if ( JSON_ERROR_NONE === json_last_error() && is_array( $decoded ) ) {
return $decoded;
}
}
if ( is_serialized( $raw ) ) {
$decoded = maybe_unserialize( $raw );
return is_array( $decoded ) ? $decoded : array();
}
return array();
}
}
if ( ! function_exists( 'cpfm_encode_payload_for_storage' ) ) {
/**
* Normalize incoming payload for database storage.
*
* Arrays are stored as JSON. Legacy serialized or JSON strings are kept unchanged.
*
* @param mixed $data Value from REST or form request.
* @return string
*/
function cpfm_encode_payload_for_storage( $data ) {
if ( is_array( $data ) ) {
return wp_json_encode( $data );
}
if ( ! is_string( $data ) || '' === $data ) {
return '';
}
$data = wp_unslash( $data );
if ( is_serialized( $data ) ) {
return $data;
}
if ( cpfm_payload_is_json_string( $data ) ) {
json_decode( $data );
if ( JSON_ERROR_NONE === json_last_error() ) {
return $data;
}
}
return '';
}
}
if ( ! function_exists( 'cpfm_payload_is_json_string' ) ) {
/**
* Whether a string looks like a JSON object or array.
*
* @param string $value Raw string.
* @return bool
*/
function cpfm_payload_is_json_string( $value ) {
if ( ! is_string( $value ) || '' === $value ) {
return false;
}
$trimmed = ltrim( $value );
return '' !== $trimmed && ( '{' === $trimmed[0] || '[' === $trimmed[0] );
}
}