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.

111 lines
2.4 KiB

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