AbstractFieldProducer::getValue()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 2
eloc 2
nc 2
nop 1
1
<?php
2
3
/*
4
 * This file is part of the CGI-Calc package.
5
 *
6
 * (c) Milos Tomic <[email protected]>
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
namespace Cgi\Calc\Field;
13
14
use Cgi\Calc\FieldProducer;
15
use Cgi\Calc\Point;
16
17
abstract class AbstractFieldProducer implements FieldProducer
18
{
19
    private $callback;
20
21
    public function __construct($valueProvider)
22
    {
23
        $this->callback = $this->getValueCallable($valueProvider);
24
    }
25
26
    /**
27
     * @param Point $point
28
     *
29
     * @return mixed|null
30
     */
31
    protected function getValue(Point $point)
32
    {
33
        return $this->callback ? call_user_func($this->callback, $point) : null;
34
    }
35
36
    /**
37
     * @param ValueProvider|callable|null $valueProvider
38
     *
39
     * @return callable|null
40
     */
41
    private function getValueCallable($valueProvider)
42
    {
43
        $callback = null;
44
        if ($valueProvider instanceof ValueProvider) {
45
            $callback = function (Point $p) use ($valueProvider) {
46
                return $valueProvider->get($p);
47
            };
48
        } elseif (is_callable($valueProvider)) {
49
            $callback = $valueProvider;
50
        } elseif ($valueProvider) {
51
            throw new \InvalidArgumentException('Value provider must be instance of ValueProvider or callable');
52
        }
53
54
        return $callback;
55
    }
56
}
57