Completed
Push — master ( afb93c...2180a3 )
by Freek
24:20 queued 09:20
created

ModelsExist::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 1
1
<?php
2
3
namespace Spatie\ValidationRules\Rules;
4
5
use Illuminate\Contracts\Validation\Rule;
6
7
class ModelsExist implements Rule
8
{
9
    /** @var string */
10
    protected $modelClassName;
11
12
    /** @var string */
13
    protected $modelAttribute;
14
15
    /** @var string */
16
    protected $attribute;
17
18
    /** @var array */
19
    protected $modelIds;
20
21 18
    public function __construct(string $modelClassName, string $attribute = 'id')
22
    {
23 18
        $this->modelClassName = $modelClassName;
24
25 18
        $this->modelAttribute = $attribute;
26 18
    }
27
28 18
    public function passes($attribute, $value): bool
29
    {
30 18
        $this->attribute = $attribute;
31
32 18
        $value = array_filter($value);
33
34 18
        $this->modelIds = array_unique($value);
35
36 18
        $modelCount = $this->modelClassName::whereIn($this->modelAttribute, $this->modelIds)->count();
0 ignored issues
show
Bug introduced by
The method whereIn cannot be called on $this->modelClassName (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
37
38 18
        return count($this->modelIds) === $modelCount;
39
    }
40
41 6
    public function message(): string
42
    {
43 6
        $modelIds = implode(', ', $this->modelIds);
44
45 6
        $classBasename = class_basename($this->modelClassName);
46
47 6
        return __('validationRules::messages.model_ids', [
48 6
            'attribute' => $this->attribute,
49 6
            'model' => $classBasename,
50 6
            'modelAttribute' => $this->modelAttribute,
51 6
            'modelIds' => $modelIds,
52
        ]);
53
    }
54
}
55