| 1 |
<?php |
| 2 |
/** |
| 3 |
* Replacements for GraphQL responses. |
| 4 |
* |
| 5 |
* @package FaustWP |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace WPE\FaustWP\Replacement; |
| 9 |
|
| 10 |
use function WPE\FaustWP\Settings\faustwp_get_setting; |
| 11 |
use function WPE\FaustWP\Replacement\has_file_extension; |
| 12 |
|
| 13 |
if ( ! defined( 'ABSPATH' ) ) { |
| 14 |
exit; |
| 15 |
} |
| 16 |
|
| 17 |
add_filter( 'graphql_request_results', __NAMESPACE__ . '\\url_replacement' ); |
| 18 |
/** |
| 19 |
* Callback for WP GraphQL 'graphql_request_results' filter. |
| 20 |
* |
| 21 |
* Replaces the WordPress Site URL with the replacement domain in 'url' and |
| 22 |
* 'href' fields. Response data for RootQuery.generalSettings is intentionally |
| 23 |
* left unaltered. |
| 24 |
* |
| 25 |
* @param object $response The default GraphQL query response. |
| 26 |
* |
| 27 |
* @return object The modified response with URLs replaced. |
| 28 |
*/ |
| 29 |
function url_replacement( $response ) { |
| 30 |
if ( ! domain_replacement_enabled() ) { |
| 31 |
return $response; |
| 32 |
} |
| 33 |
|
| 34 |
if ( |
| 35 |
is_object( $response ) && |
| 36 |
property_exists( $response, 'data' ) && |
| 37 |
is_array( $response->data ) |
| 38 |
) { |
| 39 |
url_replace_recursive( $response->data ); |
| 40 |
} |
| 41 |
|
| 42 |
return $response; |
| 43 |
} |
| 44 |
|
| 45 |
/** |
| 46 |
* Replaces the WordPress Site URL with the replacement domain |
| 47 |
* in 'url' and 'href' fields, skipping over values with file extensions. |
| 48 |
* |
| 49 |
* @param array $data The response data. |
| 50 |
*/ |
| 51 |
function url_replace_recursive( &$data ) { |
| 52 |
foreach ( $data as $key => &$value ) { |
| 53 |
// Exclude generalSettings from URL replacement. |
| 54 |
if ( 'generalSettings' === $key ) { |
| 55 |
continue; |
| 56 |
} |
| 57 |
|
| 58 |
if ( |
| 59 |
( 'url' === $key || 'href' === $key ) && |
| 60 |
is_string( $value ) && |
| 61 |
! has_file_extension( $value ) |
| 62 |
) { |
| 63 |
$replacement = faustwp_get_setting( 'frontend_uri', '/' ); |
| 64 |
$value = str_replace( site_url(), $replacement, $value ); |
| 65 |
} elseif ( ( 'path' === $key && is_multisite() ) && is_string( $value ) ) { |
| 66 |
$site = get_site(); |
| 67 |
$subdirectory = untrailingslashit( $site->path ); |
| 68 |
$value = str_replace( $subdirectory, '', $value ); |
| 69 |
} elseif ( is_array( $value ) ) { |
| 70 |
url_replace_recursive( $value ); |
| 71 |
} |
| 72 |
} |
| 73 |
} |
| 74 |
|