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.2 KiB

  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. if (is_object($searchable) && method_exists($searchable, 'getTable')) {
  38. $this->table = $searchable->getTable();
  39. } else {
  40. $this->table = $searchable;
  41. }
  42. return $this;
  43. }
  44. /**
  45. * @return FuzzySearchDriver
  46. */
  47. public function fields(/* $fields */)
  48. {
  49. $this->searchFields = func_get_args();
  50. return $this->makeDriver();
  51. }
  52. /**
  53. * @param $driverName
  54. *
  55. * @return $this
  56. */
  57. public function driver($driverName)
  58. {
  59. $this->driverName = $driverName;
  60. return $this;
  61. }
  62. /**
  63. * @param $table
  64. * @param $searchFields
  65. *
  66. * @return mixed
  67. */
  68. public function __call($table, $searchFields)
  69. {
  70. return call_user_func_array([$this->search($table), 'fields'], $searchFields);
  71. }
  72. /**
  73. * @return mixed
  74. */
  75. private function makeDriver()
  76. {
  77. $relevanceFieldName = $this->config->get('searchy.fieldName');
  78. // Check if default driver is being overridden, otherwise
  79. // load the default
  80. if ($this->driverName) {
  81. $driverName = $this->driverName;
  82. } else {
  83. $driverName = $this->config->get('searchy.default');
  84. }
  85. // Gets the details for the selected driver from the configuration file
  86. $driver = $this->config->get("searchy.drivers.$driverName")['class'];
  87. // Create a new instance of the selected drivers 'class' and pass
  88. // through table and fields to search
  89. $driverInstance = new $driver($this->table, $this->searchFields, $relevanceFieldName);
  90. return $driverInstance;
  91. }
  92. }