Completed
Push — master ( 2a0008...c509f4 )
by Iman
01:36
created

Nullable::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 2
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Imanghafoori\Helpers;
4
5
use App;
6
use function foo\func;
7
use Symfony\Component\HttpFoundation\Response;
8
use Illuminate\Http\Exceptions\HttpResponseException;
9
10
class Nullable
11
{
12
    private $result;
13
14
    private $predicate = null;
15
16
    /**
17
     * Nullable constructor.
18
     *
19
     * @param $value
20
     * @param $predicate
21
     */
22 5
    public function __construct($value, $predicate = null)
23
    {
24 5
        $this->result = $value;
25 5
        $this->predicate = $predicate;
26 5
    }
27
28
    /**
29
     * @param $default
30
     *
31
     * @return mixed
32
     */
33 1
    public function getOr($default)
34
    {
35 1
        if (is_callable($this->predicate)) {
36 1
            $p = $this->predicate;
37
        } else {
38
            $p = function ($r) {
39 1
                return is_null($r);
40 1
            };
41
        }
42
43 1
        if (! $p($this->result)) {
44 1
            return $this->result;
45
        }
46
47 1
        if (is_callable($default)) {
48
            return call_user_func($default);
49
        }
50
51 1
        return $default;
52
    }
53
54
    /**
55
     * @param       $callable
56
     * @param array $params
57
     *
58
     * @return mixed
59
     */
60 5
    public function getOrSend($callable, $params = [])
61
    {
62 5
        if (! is_null($this->result)) {
63 1
            return $this->result;
64
        }
65
66 4
        if (is_callable($callable)) {
67 2
            $response = call_user_func_array($callable, $params);
68
        }
69
70 4
        if (is_a($callable, Response::class)) {
71 1
            $response = $callable;
72
        }
73
74 4
        if(isset($response)) {
75 3
            throw new HttpResponseException($response);
76
        }
77
78 1
        throw new \InvalidArgumentException('You should provide a response.');
79
    }
80
}