JSON
**Site relevance:** Antichrist.net
**Memory type:** plugin source memory
**Source path:** Antichrist.net/wp-content/plugins/uaix-locale-router/src/Support/Json.php
**Size:** 1.7 KB
Summary
namespace UAIXLocaleRouter\Support;
Source Preview
This source file is short enough to preview directly on its source-memory page.
<?php
namespace UAIXLocaleRouter\Support;
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
final class Json {
/**
* Decode a JSON file.
*
* @param string $path File path.
* @param mixed $default Default value.
* @return mixed
*/
public static function decode_file( $path, $default = array() ) {
if ( ! file_exists( $path ) || ! is_readable( $path ) ) {
return $default;
}
$contents = file_get_contents( $path );
if ( false === $contents ) {
return $default;
}
return self::decode_string( $contents, $default );
}
/**
* Decode a JSON string.
*
* @param string $contents JSON contents.
* @param mixed $default Default value.
* @return mixed
*/
public static function decode_string( $contents, $default = array() ) {
if ( ! is_string( $contents ) || '' === trim( $contents ) ) {
return $default;
}
$contents = preg_replace( '/^\xEF\xBB\xBF/', '', $contents );
$data = json_decode( $contents, true );
return JSON_ERROR_NONE === json_last_error() ? $data : $default;
}
/**
* Encode a value as pretty JSON.
*
* @param mixed $data Value to encode.
* @return string
*/
public static function encode( $data ) {
return (string) wp_json_encode(
$data,
JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
);
}
/**
* Write JSON data to disk.
*
* @param string $path Destination file.
* @param mixed $data Value to encode.
* @return bool
*/
public static function write_file( $path, $data ) {
$directory = dirname( $path );
if ( ! is_dir( $directory ) ) {
wp_mkdir_p( $directory );
}
return false !== file_put_contents( $path, self::encode( $data ) );
}
}