Completed
Push — master ( 78d2ff...34493c )
by Arjay
01:50
created

HasAuthorizations::makeIf()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 2
1
<?php
2
3
namespace Yajra\DataTables\Html;
4
5
use Illuminate\Contracts\Auth\Access\Authorizable;
6
7
trait HasAuthorizations
8
{
9
    /**
10
     * Flag to check if user is authorized to use the button.
11
     *
12
     * @var bool
13
     */
14
    protected $authorized = true;
15
16
    /**
17
     * Make a button if condition is true.
18
     *
19
     * @param bool|callable $condition
20
     * @param string|array $options
21
     * @return static
22
     */
23
    public static function makeIf($condition, $options)
24
    {
25
        if (value($condition)) {
26
            return static::make($options);
27
        }
28
29
        return static::make([])->authorized(false);
30
    }
31
32
    /**
33
     * Make a button if condition is true.
34
     *
35
     * @param string $permission
36
     * @param string|array $options
37
     * @param Authorizable|null $user
38
     * @return static
39
     */
40
    public static function makeIfCan($permission, $options, Authorizable $user = null)
41
    {
42
        if (is_null($user)) {
43
            $user = auth()->user();
44
        }
45
46
        if ($user->can($permission)) {
47
            return static::make($options);
48
        }
49
50
        return static::make([])->authorized(false);
51
    }
52
53
    /**
54
     * Set authorization status of the button.
55
     *
56
     * @param bool|callable $bool
57
     * @return static
58
     */
59
    public function authorized($bool)
60
    {
61
        $this->authorized = value($bool);
62
63
        return $this;
64
    }
65
66
    /**
67
     * Convert the Fluent instance to an array.
68
     *
69
     * @return array
70
     */
71
    public function toArray()
72
    {
73
        if ($this->authorized) {
74
            return parent::toArray();
75
        }
76
77
        return [];
78
    }
79
}
80