Hooks.php
73 lines
| 1 | <?php |
| 2 | |
| 3 | namespace WCML\Block\Convert; |
| 4 | |
| 5 | use IWPML_DIC_Action; |
| 6 | use IWPML_Frontend_Action; |
| 7 | use WPML\Core\ISitePress; |
| 8 | use WCML\StandAlone\NullSitePress; |
| 9 | use SitePress; |
| 10 | use WCML\Rest\Frontend\Language; |
| 11 | use WPML\FP\Just; |
| 12 | use WPML\FP\Str; |
| 13 | |
| 14 | class Hooks implements IWPML_Frontend_Action, IWPML_DIC_Action { |
| 15 | |
| 16 | private $sitepress; |
| 17 | |
| 18 | private $frontendRestLang; |
| 19 | |
| 20 | public function __construct( ISitePress $sitepress, Language $frontendRestLang ) { |
| 21 | $this->sitepress = $sitepress; |
| 22 | $this->frontendRestLang = $frontendRestLang; |
| 23 | } |
| 24 | |
| 25 | public function add_hooks() { |
| 26 | add_filter( 'render_block_data', [ $this, 'filterIdsInBlock' ] ); |
| 27 | add_filter( 'render_block_woocommerce/product-search', [ $this, 'filterProductSearchForm' ] ); |
| 28 | add_action( 'parse_query', [ $this, 'addCurrentLangToQueryVars' ] ); |
| 29 | |
| 30 | if ( ! ( is_admin() || \WPML_URL_HTTP_Referer::is_post_edit_page() ) ) { |
| 31 | add_filter( 'rest_request_before_callbacks', [ $this, 'useLanguageFrontendRestLang' ], 10, 3 ); |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | public function filterIdsInBlock( array $block ) { |
| 36 | return ConverterProvider::get( $block['blockName'] )->convert( $block ); |
| 37 | } |
| 38 | |
| 39 | public function addCurrentLangToQueryVars( $query ) { |
| 40 | if ( $query instanceof \Automattic\WooCommerce\Blocks\Utils\BlocksWpQuery ) { |
| 41 | $query->query_vars['wpml_language'] = $this->sitepress->get_current_language(); |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | public function useLanguageFrontendRestLang( $response, $handler, $request ) { |
| 46 | if ( $this->isWcRestRequest( $request ) ) { |
| 47 | $lang = $this->frontendRestLang->get(); |
| 48 | |
| 49 | if ( $lang ) { |
| 50 | $this->sitepress->switch_lang( $lang ); |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | return $response; |
| 55 | } |
| 56 | |
| 57 | private function isWcRestRequest( \WP_REST_Request $request ) { |
| 58 | return strpos( $request->get_route(), '/wc/blocks/' ) === 0 |
| 59 | || strpos( $request->get_route(), '/wc/store/' ) === 0; |
| 60 | } |
| 61 | |
| 62 | public function filterProductSearchForm( $blockContent ) { |
| 63 | $replaceActionUrl = Str::pregReplace( '/(<form[^>]*action=")([^"]*)"/', '$1' . home_url( '/' ) . '"' ); |
| 64 | |
| 65 | $addLanguageHiddenField = [ $this->sitepress, 'get_search_form_filter' ]; |
| 66 | |
| 67 | return Just::of( $blockContent ) |
| 68 | ->map( $replaceActionUrl ) |
| 69 | ->map( $addLanguageHiddenField ) |
| 70 | ->get(); |
| 71 | } |
| 72 | } |
| 73 |