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
|
9 |
|
private static function setup() |
17
|
|
|
{ |
18
|
9 |
|
if (!is_subclass_of(static::class, Model::class)) { |
|
|
|
|
19
|
|
|
throw new \Exception( |
20
|
|
|
'SearchTrait must only be used with Eloquent models, [' . get_called_class() . '] used' |
21
|
|
|
); |
22
|
|
|
} |
23
|
|
|
|
24
|
9 |
|
static::searchFields(); |
25
|
9 |
|
} |
26
|
|
|
|
27
|
|
|
private static function searchFields() |
28
|
|
|
{ |
29
|
|
|
throw new \Exception("Method [searchFields] must exist and be static"); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @param array $fields |
34
|
|
|
*/ |
35
|
9 |
|
public static function setSearchFields(array $fields) |
36
|
|
|
{ |
37
|
9 |
|
self::$searchFields = $fields; |
38
|
9 |
|
} |
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
|
1 |
|
public static function search() |
52
|
|
|
{ |
53
|
1 |
|
self::setup(); |
54
|
|
|
|
55
|
1 |
|
$search = App::make(Search::class); |
56
|
1 |
|
$search->model(new static); |
57
|
|
|
|
58
|
1 |
|
return $search; |
59
|
|
|
} |
60
|
|
|
|
61
|
9 |
|
public static function bootSearchTrait() |
62
|
|
|
{ |
63
|
9 |
|
self::setup(); |
64
|
|
|
|
65
|
9 |
|
$store = App::make(Store::class); |
66
|
|
|
|
67
|
9 |
|
self::saved( |
68
|
|
|
function(Model $model) use ($store) { |
69
|
|
|
self::insertCallback($model, $store); |
70
|
|
|
} |
71
|
9 |
|
); |
72
|
|
|
|
73
|
9 |
|
self::deleting( |
74
|
|
|
function(Model $model) use ($store) { |
75
|
|
|
self::deleteCallback($model, $store); |
76
|
|
|
} |
77
|
9 |
|
); |
78
|
9 |
|
} |
79
|
|
|
|
80
|
|
|
/** |
81
|
|
|
* @param Model $model |
82
|
|
|
* @param Store $store |
83
|
|
|
*/ |
84
|
|
|
private static function insertCallback(Model $model, Store $store) |
85
|
|
|
{ |
86
|
|
|
$store->model($model); |
87
|
|
|
$store->insertModel($model); |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
/** |
91
|
|
|
* @param Model $model |
92
|
|
|
* @param Store $store |
93
|
|
|
*/ |
94
|
|
|
private static function deleteCallback(Model $model, Store $store) |
95
|
|
|
{ |
96
|
|
|
$store->model($model); |
97
|
|
|
$store->deleteModel($model); |
98
|
|
|
} |
99
|
|
|
} |
100
|
|
|
|