Completed
Push — master ( 936afc...005576 )
by Emmanuel
01:16
created

TicketReferenceRule::passes()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 8.8333
c 0
b 0
f 0
cc 7
nc 5
nop 2
1
<?php
2
3
4
namespace RexlManu\LaravelTickets\Rule;
5
6
7
use Illuminate\Contracts\Validation\Rule;
8
use Illuminate\Database\Eloquent\Relations\Relation;
9
use RexlManu\LaravelTickets\Interfaces\TicketReference;
10
11
class TicketReferenceRule implements Rule
12
{
13
14
    /**
15
     * Determine if the ticket reference is valid
16
     * Checks
17
     * if value contains type and id
18
     * if the model exists
19
     * if the model is a instance of @param string $attribute
20
     *
21
     * @param mixed $value
22
     *
23
     * @return bool if the value is valid
24
     * @link TicketReference
25
     * if the user has rights to the model
26
     *
27
     */
28
    public function passes($attribute, $value)
29
    {
30
        if (! str_contains($value, ',')) return false;
31
32
        $values = explode(',', $value);
33
        if (count($values) !== 2) return false;
34
35
        $type = $values[ 0 ];
36
        if (! class_exists($type)) return false;
37
        $model = resolve($type)->find($values[ 1 ]);
38
        if (empty($model)
39
            || ! $model instanceof TicketReference
40
            || ! $model->hasReferenceAccess()) {
41
            return false;
42
        }
43
        return true;
44
    }
45
46
    /**
47
     * Get the validation error message.
48
     *
49
     * @return string
50
     */
51
    public function message()
52
    {
53
        return trans('The reference is not valid');
54
    }
55
}
56