Completed
Push — master ( 4d1f4a...3dcd94 )
by Jitendra
11s
created

With::stack()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 1
nc 2
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Ahc\With;
4
5
/**
6
 * With provides object like fluent interface for scalars and non objects.
7
 *
8
 * @author Jitendra Adhikari <[email protected]>
9
 */
10
class With
11
{
12
    private $thing;
13
14
    /**
15
     * The constructor.
16
     *
17
     * @param mixed $thing Any thing (but non-objects preferred).
18
     */
19
    public function __construct($thing)
20
    {
21
        $this->thing = $thing;
22
    }
23
24
    /**
25
     * The method call is delegated to the thing initially `with`ed.
26
     *
27
     * By default The initial thing will be first parameter to the method to be called.
28
     * You can change this behavior by suffixing underscore (_) to the method name.
29
     *
30
     * @param string $method
31
     * @param array  $things
32
     *
33
     * @return With
34
     */
35
    public function __call(string $method, array $things): With
36
    {
37
        if (\substr($method, -1) === '_') {
38
            $method   = \substr($method, 0, -1);
39
            $things[] = $this->thing;
40
        } else {
41
            \array_unshift($things, $this->thing);
42
        }
43
44
        $this->thing = $method(...$things);
45
46
        return $this;
47
    }
48
49
    /**
50
     * Call as a function to get the final value!
51
     *
52
     * @return mixed
53
     */
54
    public function __invoke()
55
    {
56
        return $this->thing;
57
    }
58
59
    /**
60
     * Pass the value via any callable and optionally extra arguments.
61
     *
62
     * @param callable $method
63
     * @param array    $things
64
     *
65
     * @return With
66
     */
67
    public function via(callable $method, array $things = []): With
68
    {
69
        \array_unshift($things, $this->thing);
70
71
        $this->thing = $method(...$things);
72
73
        return $this;
74
    }
75
}
76