Filter
uncanny-automator
automator_recipe_object_json_encoding_flags_php72
Filters JSON encoding flags for recipe objects, allowing custom flags for specific PHP 7.2+ environments.
add_filter( 'automator_recipe_object_json_encoding_flags_php72', $callback, 10, 1 );
Description
Filters the JSON encoding flags used for recipe objects, specifically for PHP 7.2+ environments. Developers can use this hook to modify the flags, enabling custom handling of invalid UTF-8 characters during JSON encoding. The `JSON_INVALID_UTF8_SUBSTITUTE` constant is available by default.
Usage
add_filter( 'automator_recipe_object_json_encoding_flags_php72', 'your_function_name', 10, 1 );
Parameters
-
$this(mixed) - This parameter allows you to modify the flags used for JSON encoding, specifically by enabling the `JSON_INVALID_UTF8_SUBSTITUTE` option for improved handling of invalid UTF-8 characters.
Return Value
The filtered value.
Examples
/**
* Example callback for the 'automator_recipe_object_json_encoding_flags_php72' filter.
*
* This function demonstrates how to modify the JSON encoding flags when
* encoding a recipe object in PHP 7.2 and above. Specifically, it adds
* the JSON_UNESCAPED_UNICODE flag to ensure that Unicode characters are
* not escaped, making the JSON output more readable.
*
* @param int $flags The current JSON encoding flags.
* @param object $recipeObject The recipe object being encoded.
* @return int The modified JSON encoding flags.
*/
add_filter( 'automator_recipe_object_json_encoding_flags_php72', function( $flags, $recipeObject ) {
// Add JSON_UNESCAPED_UNICODE to make the output more human-readable
// by not escaping Unicode characters.
// We assume JSON_INVALID_UTF8_SUBSTITUTE is already included by default
// from the context of the hook.
$flags = $flags | JSON_UNESCAPED_UNICODE;
// You could also add other flags here based on conditions related to $recipeObject
// For example:
// if ( property_exists( $recipeObject, 'is_complex' ) && true === $recipeObject->is_complex ) {
// $flags = $flags | JSON_PRETTY_PRINT;
// }
return $flags;
}, 10, 2 );
Placement
This code should be placed in the functions.php file of your active theme, a custom plugin, or using a code snippets plugin.
Source Code
src/core/services/recipe/structure.php:241
public function toJSON() {
// Pass default option by default.
$flags = apply_filters( 'automator_recipe_object_json_encoding_flags', 0, $this );
// If its a php 7.2 where constant "JSON_INVALID_UTF8_SUBSTITUTE" is available.
if ( defined( 'JSON_INVALID_UTF8_SUBSTITUTE' ) ) {
// Provide a different filter and by default, substitute invalid utf-8 characters.
$flags = apply_filters( 'automator_recipe_object_json_encoding_flags_php72', JSON_INVALID_UTF8_SUBSTITUTE, $this );
}
$decoded = wp_json_encode( $this, $flags );
if ( false === $decoded || ! is_string( $decoded ) ) {
return '';
}
return $decoded;
}