Filters.php
42 lines
| 1 | <?php |
| 2 | |
| 3 | namespace WCML\Utilities\Suspend; |
| 4 | |
| 5 | use WPML\FP\Logic; |
| 6 | use WPML\FP\Relation; |
| 7 | use function WPML\FP\pipe; |
| 8 | use function WPML\FP\spreadArgs; |
| 9 | |
| 10 | class Filters implements Suspend { |
| 11 | |
| 12 | /** @var \WPML\Collect\Support\Collection $suspended */ |
| 13 | private $suspended; |
| 14 | |
| 15 | public function __construct( array $filtersToSuspend ) { |
| 16 | $this->suspended = wpml_collect( $filtersToSuspend )->filter( spreadArgs( 'remove_filter' ) ); |
| 17 | } |
| 18 | |
| 19 | /** |
| 20 | * @return void |
| 21 | */ |
| 22 | public function resume() { |
| 23 | $this->suspended |
| 24 | // Make sure the filter has not been already restored. |
| 25 | ->filter( pipe( spreadArgs( 'has_filter' ), Relation::equals( false ), Logic::not() ) ) |
| 26 | ->each( spreadArgs( 'add_filter' ) ); |
| 27 | } |
| 28 | |
| 29 | /** |
| 30 | * @param callable $function |
| 31 | * |
| 32 | * @return mixed |
| 33 | */ |
| 34 | public function runAndResume( callable $function ) { |
| 35 | $result = $function(); |
| 36 | |
| 37 | $this->resume(); |
| 38 | |
| 39 | return $result; |
| 40 | } |
| 41 | } |
| 42 |