ModelsExist   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 3
lcom 1
cbo 0
dl 0
loc 48
ccs 18
cts 18
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A passes() 0 12 1
A message() 0 13 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