Completed
Push — master ( 8a1e80...9a8538 )
by Iman
01:46
created

Nullable::getOrAbort()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 3
dl 0
loc 8
ccs 4
cts 5
cp 0.8
crap 2.032
rs 10
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
    /**
15
     * Nullable constructor.
16
     *
17
     * @param $value
18
     * @param $predicate
19
     */
20 8
    public function __construct($value, $predicate = null)
21
    {
22 8
        $this->result = $value;
23 8
        $this->predicate = $predicate;
24 8
    }
25
26
    /**
27
     * @param $default
28
     *
29
     * @return mixed
30
     */
31 1
    public function getOr($default)
32
    {
33 1
        $p = $this->getPredicate();
34
35 1
        if (!$p($this->result)) {
36 1
            return $this->result;
37
        }
38
39 1
        if (is_callable($default)) {
40
            return call_user_func($default);
41
        }
42
43 1
        return $default;
44
    }
45
46 2
    public function getOrAbort($code, $message = '', array $headers = [])
47
    {
48 2
        if (!is_null($this->result)) {
49 1
            return $this->result;
50
        }
51
52 1
        abort($code, $message, $headers);
53
    }
54
55
    /**
56
     * @param       $callable
57
     * @param array $params
58
     *
59
     * @return mixed
60
     */
61 6
    public function getOrSend($callable, $params = [])
62
    {
63 6
        if (!is_null($this->result)) {
64 1
            return $this->result;
65
        }
66
67 5
        if (is_callable($callable)) {
68 3
            $callable = call_user_func_array($callable, $params);
69
        }
70
71 5
        if (is_a($callable, Response::class)) {
72 3
            $response = $callable;
73
        }
74
75 5
        if (isset($response)) {
76 3
            throw new HttpResponseException($response);
77
        }
78
79 2
        throw new \InvalidArgumentException('You should provide a valid http response.');
80
    }
81
82
    /**
83
     * @return callable|\Closure|null
84
     */
85 1
    private function getPredicate()
86
    {
87 1
        if (is_callable($this->predicate)) {
88 1
            $p = $this->predicate;
89
        } else {
90
            $p = function ($r) {
91 1
                return is_null($r);
92 1
            };
93
        }
94
95 1
        return $p;
96
    }
97
}
98