You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

110 lines
2.3 KiB

8 years ago
8 years ago
8 years ago
  1. <?php
  2. namespace TomLingham\Searchy;
  3. use TomLingham\Searchy\SearchDrivers\FuzzySearchDriver;
  4. /**
  5. * @property mixed driverName
  6. */
  7. class SearchBuilder
  8. {
  9. /**
  10. * @var
  11. */
  12. private $table;
  13. /**
  14. * @var
  15. */
  16. private $searchFields;
  17. /**
  18. * @var
  19. */
  20. private $driverName;
  21. /**
  22. * @var
  23. */
  24. private $config;
  25. public function __construct($config)
  26. {
  27. $this->config = $config;
  28. }
  29. /**
  30. * @param $searchable
  31. *
  32. * @return $this
  33. */
  34. public function search($searchable)
  35. {
  36. // Check if table name or Eloquent
  37. $isEloquent = is_object($searchable) && method_exists($searchable, 'getTable');
  38. $this->table = $isEloquent ? $searchable->getTable() : $searchable;
  39. return $this;
  40. }
  41. /**
  42. * @return FuzzySearchDriver
  43. */
  44. public function fields(/* $fields */)
  45. {
  46. $args = func_get_args();
  47. $this->searchFields = is_array( $args[0] ) ? $args[0] : $args;
  48. return $this->makeDriver();
  49. }
  50. /**
  51. * @param $driverName
  52. *
  53. * @return $this
  54. */
  55. public function driver($driverName)
  56. {
  57. $this->driverName = $driverName;
  58. return $this;
  59. }
  60. /**
  61. * @param $table
  62. * @param $searchFields
  63. *
  64. * @return mixed
  65. */
  66. public function __call($table, $searchFields)
  67. {
  68. return call_user_func_array([$this->search($table), 'fields'], $searchFields);
  69. }
  70. /**
  71. * @return mixed
  72. */
  73. private function makeDriver()
  74. {
  75. $relevanceFieldName = $this->config->get('searchy.fieldName');
  76. // Check if default driver is being overridden, otherwise
  77. // load the default
  78. $driverName = $this->driverName ? $this->driverName : $this->config->get('searchy.default');
  79. // Gets the details for the selected driver from the configuration file
  80. $driver = $this->config->get("searchy.drivers.$driverName")['class'];
  81. // Create a new instance of the selected drivers 'class' and pass
  82. // through table and fields to search
  83. $driverInstance = new $driver( $this->table,
  84. $this->searchFields,
  85. $relevanceFieldName,
  86. ['*']);
  87. return $driverInstance;
  88. }
  89. }