Completed
Push — master ( ddcd57...befb63 )
by Adam
12:31
created

SearchTrait::insertCallback()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 1
crap 1
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)) {
1 ignored issue
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of might return inconsistent results on some PHP versions if \Illuminate\Database\Eloquent\Model::class can be an interface. If so, you could instead use ReflectionClass::implementsInterface.
Loading history...
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