Completed
Push — master ( afd55f...63b885 )
by Iman
01:23
created

Nullable::getPredicate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 0
dl 0
loc 10
ccs 5
cts 5
cp 1
crap 2
rs 9.9332
c 0
b 0
f 0
1
<?php
2
3
namespace Imanghafoori\Helpers;
4
5
use Illuminate\Http\Exceptions\HttpResponseException;
6
use Symfony\Component\HttpFoundation\Response;
7
8
class Nullable
9
{
10
    private $result;
11
12
    private $predicate = null;
13
14
    private $message = [];
15
16
    /**
17
     * Nullable constructor.
18
     *
19
     * @param mixed $value
20
     * @param array $message
21
     * @param callable $predicate
22
     */
23 13
    public function __construct($value = null, array $message = [], $predicate = null)
24
    {
25 13
        $this->result = $value;
26 13
        $this->message = $message;
27 13
        $this->predicate = $predicate;
28 13
    }
29
30 1
    public function getOr($default)
31
    {
32 1
        $p = $this->getPredicate();
33
34 1
        if (!$p($this->result)) {
35 1
            return $this->result;
36
        }
37
38 1
        if (is_callable($default)) {
39 1
            return call_user_func_array($default, $this->message);
40
        }
41
42 1
        return $default;
43
    }
44
45 2
    public function getOrAbort($code, $message = '', array $headers = [])
46
    {
47 2
        if (!is_null($this->result)) {
48 1
            return $this->result;
49
        }
50
51 1
        abort($code, $message, $headers);
52
    }
53
54 6
    public function getOrSend($callable)
55
    {
56 6
        if (!is_null($this->result)) {
57 1
            return $this->result;
58
        }
59
60 5
        if (is_callable($callable)) {
61 3
            $callable = call_user_func_array($callable, $this->message);
62
        }
63
64 5
        if (is_a($callable, Response::class)) {
65 3
            $response = $callable;
66
        }
67
68 5
        if (isset($response)) {
69 3
            throw new HttpResponseException($response);
70
        }
71
72 2
        throw new \InvalidArgumentException('You must provide a valid http response or a callable.');
73
    }
74
75 3
    public function getOrThrow($exception, ...$parameters)
76
    {
77 3
        if (!is_null($this->result)) {
78 1
            return $this->result;
79
        }
80
81 2
        throw_if(true, $exception, ...$parameters);
82
    }
83
84 2
    public function onValue(callable $callable)
85
    {
86 2
        if (! is_null($this->result)) {
87 1
            return call_user_func_array($callable, [$this->result]);
88
        }
89 1
    }
90
91 1
    private function getPredicate()
92
    {
93 1
        if (is_callable($this->predicate)) {
94 1
            return $this->predicate;
95
        }
96
97
        return function ($value) {
98 1
            return is_null($value);
99 1
        };
100
    }
101
}
102