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.

129 lines
2.5 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 $trashed = false;
  26. /**
  27. * @var
  28. */
  29. private $config;
  30. public function __construct(Repository $config)
  31. {
  32. $this->config = $config;
  33. }
  34. /**
  35. * @param $searchable
  36. *
  37. * @return $this
  38. */
  39. public function search($searchable)
  40. {
  41. if (is_object($searchable) && method_exists($searchable, 'getTable')) {
  42. $this->table = $searchable->getTable();
  43. } else {
  44. $this->table = $searchable;
  45. }
  46. return $this;
  47. }
  48. /**
  49. * @return FuzzySearchDriver
  50. */
  51. public function fields(/* $fields */)
  52. {
  53. $this->searchFields = func_get_args();
  54. return $this->makeDriver();
  55. }
  56. /**
  57. * @param $driverName
  58. *
  59. * @return $this
  60. */
  61. public function driver($driverName)
  62. {
  63. $this->driverName = $driverName;
  64. return $this;
  65. }
  66. /**
  67. * @param $trashed
  68. *
  69. * @return $this
  70. */
  71. public function trashed()
  72. {
  73. $this->trashed = true;
  74. return $this;
  75. }
  76. /**
  77. * @param $table
  78. * @param $searchFields
  79. *
  80. * @return mixed
  81. */
  82. public function __call($table, $searchFields)
  83. {
  84. return call_user_func_array([$this->search($table), 'fields'], $searchFields);
  85. }
  86. /**
  87. * @return mixed
  88. */
  89. private function makeDriver()
  90. {
  91. $relevanceFieldName = $this->config->get('searchy.fieldName');
  92. // Check if default driver is being overridden, otherwise
  93. // load the default
  94. if ($this->driverName) {
  95. $driverName = $this->driverName;
  96. } else {
  97. $driverName = $this->config->get('searchy.default');
  98. }
  99. // Gets the details for the selected driver from the configuration file
  100. $driver = $this->config->get("searchy.drivers.$driverName")['class'];
  101. // Create a new instance of the selected drivers 'class' and pass
  102. // through table and fields to search
  103. $driverInstance = new $driver($this->table, $this->searchFields, $relevanceFieldName,['*'],$this->trashed);
  104. return $driverInstance;
  105. }
  106. }