| 1 |
<?php |
| 2 |
/** |
| 3 |
* Handles search algorithms registration and storage |
| 4 |
* |
| 5 |
* @since 4.3.0 |
| 6 |
* @package elasticpress |
| 7 |
*/ |
| 8 |
|
| 9 |
namespace ElasticPress; |
| 10 |
|
| 11 |
if ( ! defined( 'ABSPATH' ) ) { |
| 12 |
exit; // Exit if accessed directly. |
| 13 |
} |
| 14 |
|
| 15 |
/** |
| 16 |
* Class for handling all SearchAlgorithm |
| 17 |
*/ |
| 18 |
class SearchAlgorithms { |
| 19 |
|
| 20 |
/** |
| 21 |
* Array of registered search algorithms |
| 22 |
* |
| 23 |
* @var array |
| 24 |
*/ |
| 25 |
private $registered_search_algorithms = []; |
| 26 |
|
| 27 |
/** |
| 28 |
* Register a search algorithm |
| 29 |
* |
| 30 |
* @param SearchAlgorithm $search_algorithm Instance of Search Algorithm. |
| 31 |
*/ |
| 32 |
public function register( SearchAlgorithm $search_algorithm ) { |
| 33 |
$this->registered_search_algorithms[ $search_algorithm->get_slug() ] = $search_algorithm; |
| 34 |
} |
| 35 |
|
| 36 |
/** |
| 37 |
* Get a search algorithm instance given a slug |
| 38 |
* |
| 39 |
* @param string $slug Search Algorithm slug |
| 40 |
* @return SearchAlgorithm |
| 41 |
*/ |
| 42 |
public function get( string $slug ) { |
| 43 |
return ( ! empty( $this->registered_search_algorithms[ $slug ] ) ) ? |
| 44 |
$this->registered_search_algorithms[ $slug ] : |
| 45 |
$this->registered_search_algorithms['default']; |
| 46 |
} |
| 47 |
|
| 48 |
/** |
| 49 |
* Unregister a search algorithm. |
| 50 |
* |
| 51 |
* A search algorithm can only be unregistered if it is not the only one left. |
| 52 |
* |
| 53 |
* @param string $slug Search Algorithm slug |
| 54 |
* @return bool Whether the search algorithm was unregistered or not. |
| 55 |
*/ |
| 56 |
public function unregister( string $slug ) { |
| 57 |
if ( isset( $this->registered_search_algorithms[ $slug ] ) && count( $this->registered_search_algorithms ) >= 2 ) { |
| 58 |
unset( $this->registered_search_algorithms[ $slug ] ); |
| 59 |
return true; |
| 60 |
} |
| 61 |
return false; |
| 62 |
} |
| 63 |
|
| 64 |
/** |
| 65 |
* Get all search algorithm instances |
| 66 |
* |
| 67 |
* @param boolean $slug_only True returns an array of only string slugs. |
| 68 |
* @return array |
| 69 |
*/ |
| 70 |
public function get_all( $slug_only = false ) { |
| 71 |
if ( $slug_only ) { |
| 72 |
return array_keys( $this->registered_search_algorithms ); |
| 73 |
} |
| 74 |
|
| 75 |
return $this->registered_search_algorithms; |
| 76 |
} |
| 77 |
|
| 78 |
/** |
| 79 |
* Return singleton instance of class |
| 80 |
* |
| 81 |
* @return object |
| 82 |
*/ |
| 83 |
public static function factory() { |
| 84 |
static $instance = false; |
| 85 |
|
| 86 |
if ( ! $instance ) { |
| 87 |
$instance = new self(); |
| 88 |
} |
| 89 |
|
| 90 |
return $instance; |
| 91 |
} |
| 92 |
} |
| 93 |
|