With::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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