Completed
Push — master ( dbb9c2...da52bd )
by Scott
05:56
created

DotFunc::run()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 25
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 25
ccs 17
cts 17
cp 1
rs 8.8571
c 0
b 0
f 0
cc 3
eloc 17
nc 3
nop 1
crap 3
1
<?php
2
namespace Desmond\functions\core;
3
use Desmond\functions\DesmondFunction;
4
use Desmond\ArgumentHelper;
5
use Desmond\TypeHelper;
6
use Desmond\data_types\VectorType;
7
use Desmond\exceptions\ArgumentException;
8
use RuntimeException;
9
use ArgumentCountError;
10
11
class DotFunc extends DesmondFunction
12
{
13
    use ArgumentHelper;
14
    use TypeHelper;
15
16 314
    public function id()
17
    {
18 314
        return '.func';
19
    }
20
21 7
    public function run(array $args)
22
    {
23 7
        $this->expectArguments(
24 7
            '.func',
25 7
            [0 => ['Symbol', 'String']],
26 7
            $args
27
        );
28 6
        $function = self::getFunction($args);
29 5
        $args = self::getArgs($args);
30
31
        // This is to capture warnings when you call PHP functions without all their args.
32 5
        set_error_handler(function($errno, $errstr, $errfile, $errline) {
33 1
            throw new RuntimeException($errstr);
34 5
        });
35
36
        try {
37 5
            $value = $function(...$args);
38 2
        } catch (RuntimeException $error) {
39 1
            throw new ArgumentException("\".func\": Too few arguments passed to $function.");
40 1
        } catch (ArgumentCountError $error) {
41 1
            throw new ArgumentException("\".func\": Too few arguments passed to $function.");
42
        }
43 3
        restore_error_handler();
44 3
        return self::fromPhpType($value);
45
    }
46
47 5
    private static function getArgs($args)
48
    {
49 5
        array_shift($args);
50 5
        $argValues = [];
51 5
        foreach ($args as $arg) {
52 2
            $argValues[] = self::toPhpType($arg);
53
        }
54 5
        return $argValues;
55
    }
56
57 6
    private static function getFunction(array $args)
58
    {
59 6
        $functionName = $args[0]->value();
60 6
        if (!function_exists($functionName)) {
61 1
            throw new ArgumentException("\".func\": undefined PHP function \"$functionName\".");
62
        } else {
63 5
            return $args[0]->value();
64
        }
65
    }
66
}
67