| 1 |
<?php |
| 2 |
/** |
| 3 |
* Function to read json files. |
| 4 |
* |
| 5 |
* @package gutenberg |
| 6 |
*/ |
| 7 |
|
| 8 |
if ( ! function_exists( 'wp_json_file_decode' ) ) { |
| 9 |
/** |
| 10 |
* Reads and decodes a JSON file. |
| 11 |
* |
| 12 |
* @param string $filename Path to the JSON file. |
| 13 |
* @param array $options { |
| 14 |
* Optional. Options to be used with `json_decode()`. |
| 15 |
* |
| 16 |
* @type bool associative Optional. When `true`, JSON objects will be returned as associative arrays. |
| 17 |
* When `false`, JSON objects will be returned as objects. |
| 18 |
* } |
| 19 |
* |
| 20 |
* @return mixed Returns the value encoded in JSON in appropriate PHP type. |
| 21 |
* `null` is returned if the file is not found, or its content can't be decoded. |
| 22 |
*/ |
| 23 |
function wp_json_file_decode( $filename, $options = array() ) { |
| 24 |
$result = null; |
| 25 |
$filename = wp_normalize_path( realpath( $filename ) ); |
| 26 |
if ( ! file_exists( $filename ) ) { |
| 27 |
trigger_error( |
| 28 |
sprintf( |
| 29 |
/* translators: %s: Path to the JSON file. */ |
| 30 |
__( "File %s doesn't exist!", 'gutenberg' ), |
| 31 |
$filename |
| 32 |
) |
| 33 |
); |
| 34 |
return $result; |
| 35 |
} |
| 36 |
|
| 37 |
$options = wp_parse_args( $options, array( 'associative' => false ) ); |
| 38 |
$decoded_file = json_decode( file_get_contents( $filename ), $options['associative'] ); |
| 39 |
|
| 40 |
if ( JSON_ERROR_NONE !== json_last_error() ) { |
| 41 |
trigger_error( |
| 42 |
sprintf( |
| 43 |
/* translators: 1: Path to the JSON file, 2: Error message. */ |
| 44 |
__( 'Error when decoding a JSON file at path %1$s: %2$s', 'gutenberg' ), |
| 45 |
$filename, |
| 46 |
json_last_error_msg() |
| 47 |
) |
| 48 |
); |
| 49 |
return $result; |
| 50 |
} |
| 51 |
|
| 52 |
return $decoded_file; |
| 53 |
} |
| 54 |
} |
| 55 |
|