1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace BestServedCold\LaravelZendSearch\Laravel; |
4
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Model; |
6
|
|
|
use Illuminate\Support\Facades\App; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Class SearchTrait |
10
|
|
|
* @package BestServedCold\LaravelZendSearch\Laravel |
11
|
|
|
*/ |
12
|
|
|
trait SearchTrait |
13
|
|
|
{ |
14
|
|
|
private static $searchFields = [ ]; |
15
|
|
|
|
16
|
15 |
|
private static function setup() |
17
|
|
|
{ |
18
|
15 |
|
if (!is_subclass_of(static::class, Model::class)) { |
|
|
|
|
19
|
1 |
|
throw new \Exception( |
20
|
1 |
|
'SearchTrait must only be used with Eloquent models, [' . get_called_class() . '] used.' |
21
|
1 |
|
); |
22
|
|
|
} |
23
|
|
|
|
24
|
15 |
|
static::searchFields(); |
25
|
15 |
|
} |
26
|
|
|
|
27
|
1 |
|
private static function searchFields() |
28
|
|
|
{ |
29
|
1 |
|
throw new \Exception("Method [searchFields] must exist and be static."); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @param array $fields |
34
|
|
|
*/ |
35
|
15 |
|
public static function setSearchFields(array $fields) |
36
|
|
|
{ |
37
|
15 |
|
self::$searchFields = $fields; |
38
|
15 |
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @return array |
42
|
|
|
*/ |
43
|
2 |
|
public static function getSearchFields() |
44
|
|
|
{ |
45
|
2 |
|
return self::$searchFields; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* @return mixed |
50
|
|
|
*/ |
51
|
2 |
|
public static function search() |
52
|
|
|
{ |
53
|
2 |
|
self::setup(); |
54
|
|
|
|
55
|
1 |
|
$search = App::make(Search::class); |
56
|
1 |
|
$search->model(new static); |
57
|
|
|
|
58
|
1 |
|
return $search; |
59
|
|
|
} |
60
|
|
|
|
61
|
15 |
|
public static function bootSearchTrait() |
62
|
|
|
{ |
63
|
15 |
|
self::setup(); |
64
|
15 |
|
$store = App::make(Store::class); |
65
|
15 |
|
self::saved(self::insertCallback($store)); |
66
|
15 |
|
self::deleting(self::deleteCallback($store)); |
67
|
15 |
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* @param Store $store |
71
|
|
|
* @return \Closure |
72
|
|
|
*/ |
73
|
15 |
|
private static function insertCallback(Store $store) |
74
|
|
|
{ |
75
|
|
|
return function (Model $model) use ($store) { |
76
|
1 |
|
$store->model($model); |
77
|
1 |
|
$store->insertModel($model); |
78
|
15 |
|
}; |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
/** |
82
|
|
|
* @param Store $store |
83
|
|
|
* @return \Closure |
84
|
|
|
*/ |
85
|
|
|
private static function deleteCallback(Store $store) |
86
|
|
|
{ |
87
|
15 |
|
return function (Model $model) use ($store) { |
88
|
1 |
|
$store->model($model); |
89
|
1 |
|
$store->deleteModel($model); |
90
|
15 |
|
}; |
91
|
|
|
} |
92
|
|
|
} |
93
|
|
|
|