Completed
Push — master ( 231e24...47baa1 )
by Iman
01:32
created

Nullable::getPredicate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 0
dl 0
loc 12
ccs 6
cts 6
cp 1
crap 2
rs 9.8666
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 6
    public function __construct($value, $predicate = null)
21
    {
22 6
        $this->result = $value;
23 6
        $this->predicate = $predicate;
24 6
    }
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
    /**
47
     * @param       $callable
48
     * @param array $params
49
     *
50
     * @return mixed
51
     */
52 6
    public function getOrSend($callable, $params = [])
53
    {
54 6
        if (!is_null($this->result)) {
55 1
            return $this->result;
56
        }
57
58 5
        if (is_callable($callable)) {
59 3
            $callable = call_user_func_array($callable, $params);
60
        }
61
62 5
        if (is_a($callable, Response::class)) {
63 3
            $response = $callable;
64
        }
65
66 5
        if (isset($response)) {
67 3
            throw new HttpResponseException($response);
68
        }
69
70 2
        throw new \InvalidArgumentException('You should provide a valid http response.');
71
    }
72
73
    /**
74
     * @return callable|\Closure|null
75
     */
76 1
    private function getPredicate()
77
    {
78 1
        if (is_callable($this->predicate)) {
79 1
            $p = $this->predicate;
80
        } else {
81
            $p = function ($r) {
82 1
                return is_null($r);
83 1
            };
84
        }
85
86 1
        return $p;
87
    }
88
}
89