Hooks.php
48 lines
| 1 | <?php |
| 2 | |
| 3 | namespace WCML\Multicurrency\Transient; |
| 4 | |
| 5 | use WCML\MultiCurrency\Settings as McSettings; |
| 6 | use WPML\FP\Fns; |
| 7 | use WPML\FP\Str; |
| 8 | use WPML\LIB\WP\Hooks as WpHooks; |
| 9 | use function WCML\functions\getClientCurrency; |
| 10 | use function WPML\FP\spreadArgs; |
| 11 | |
| 12 | class Hooks { |
| 13 | |
| 14 | public static function addHooks( $key ) { |
| 15 | $getKeyWithCurrency = Str::concat( $key . '_' ); |
| 16 | $getKeyWithClientCurrency = function() use ( $getKeyWithCurrency ) { |
| 17 | return $getKeyWithCurrency( getClientCurrency() ); |
| 18 | }; |
| 19 | |
| 20 | $getTransient = function() use ( $getKeyWithClientCurrency ) { |
| 21 | return get_transient( $getKeyWithClientCurrency() ); |
| 22 | }; |
| 23 | |
| 24 | $setTransient = function( $value ) use ( $key, $getKeyWithClientCurrency ) { |
| 25 | delete_transient( $key ); |
| 26 | return set_transient( $getKeyWithClientCurrency(), $value ); |
| 27 | }; |
| 28 | |
| 29 | $deleteTransient = function() use ( $getKeyWithCurrency ) { |
| 30 | foreach ( McSettings::getActiveCurrencyCodes() as $code ) { |
| 31 | delete_transient( $getKeyWithCurrency( $code ) ); |
| 32 | } |
| 33 | }; |
| 34 | |
| 35 | $withLock = Fns::withNamedLock( __CLASS__ . "_$key", Fns::identity() ); |
| 36 | |
| 37 | WpHooks::onFilter( 'pre_transient_' . $key ) |
| 38 | ->then( $getTransient ); |
| 39 | |
| 40 | WpHooks::onAction( 'set_transient_' . $key ) |
| 41 | ->then( spreadArgs( $withLock( $setTransient ) ) ); |
| 42 | |
| 43 | WpHooks::onAction( 'delete_transient_' . $key ) |
| 44 | ->then( $withLock( $deleteTransient ) ); |
| 45 | } |
| 46 | |
| 47 | } |
| 48 |