Completed
Push — master ( 3fcb18...671da7 )
by
unknown
06:12 queued 03:04
created

ThisLikeThatCriteria::apply()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
rs 9.4285
cc 2
eloc 6
nc 2
nop 2
1
<?php
2
3
namespace App\Ship\Criterias\Eloquent;
4
5
use App\Ship\Parents\Criterias\Criteria;
6
use Illuminate\Database\Query\Builder;
7
use Prettus\Repository\Contracts\RepositoryInterface as PrettusRepositoryInterface;
8
9
/**
10
 * Class ThisLikeThatCriteria
11
 * 
12
 * @author Fabian Widmann <[email protected]>
13
 *
14
 * Retrieves all entities where $field contains one or more of the given items in $valueString.
15
 */
16
class ThisLikeThatCriteria extends Criteria
17
{
18
19
    /**
20
     * @var string name of the column
21
     */
22
    private $field;
23
24
    /**
25
     * @var string contains values separated by $separator
26
     */
27
    private $valueString;
28
29
    /**
30
     * @var string separates separate items in the given $values string. Default is csv.
31
     */
32
    private $separator;
33
34
    /**
35
     * @var string this character is replaced with '%'. Default is *.
36
     */
37
    private $wildcard;
38
39
40
    public function __construct($field, $valueString, $separator = ',', $wildcard = '*')
41
    {
42
        $this->field = $field;
43
        $this->valueString = $valueString;
44
        $this->separator =$separator;
45
        $this->wildcard =$wildcard;
46
    }
47
48
    /**
49
     * Applies the criteria - if more than one value is separated by the configured separator we will "OR" all the params.
50
     * 
51
     * @param  $model
52
     * @param  $repository
53
     * 
54
     * @return  mixed
55
     */
56
    public function apply($model, $repository)
57
    {
58
        $values = explode(config($this->separator), $this->valueString);
59
        $model = $model->where($this->field, 'LIKE', str_replace($this->wildcard, '%', array_shift($values)));
60
        foreach ($values as $value)
61
            $model = $model->orWhere($this->field, 'LIKE', str_replace($this->wildcard, '%', $value));
62
        return $model;
63
    }
64
65
}
66