Passed
Branch master (12d765)
by Scott
02:39
created

DotProperty::getProperty()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
cc 3
eloc 6
nc 3
nop 2
1
<?php
2
namespace Desmond\functions\core;
3
use Desmond\functions\DesmondFunction;
4
use Desmond\ArgumentHelper;
5
use Desmond\TypeHelper;
6
use Desmond\exceptions\ArgumentException;
7
8
class DotProperty implements DesmondFunction
9
{
10
    use ArgumentHelper;
11
    use TypeHelper;
12
13
    public function id()
14
    {
15
        return '.property';
16
    }
17
18
    public function run(array $args)
19
    {
20
        $this->checkArgs($args);
21
        $object = $args[0]->value();
22
        $property = $args[1]->value();
23
24
        if (isset($args[2])) {
25
            $this->setProperty($object, $property, $args[2]);
26
        }
27
28
        return $this->getProperty($object, $property);
29
    }
30
31
    private function checkArgs($args)
32
    {
33
        $this->expectArguments(
34
            '.property',
35
            [
36
                0 => ['Object', 'String', 'Symbol'],
37
                1 => ['Symbol', 'String']
38
            ],
39
            $args
40
        );
41
    }
42
43
    private function getProperty($object, $property)
44
    {
45
        if (!property_exists($object, $property)) {
46
            return $this->newReturnType('Nil');
47
        }
48
        return is_string($object)
49
            ? TypeHelper::fromPhpType($object::$$property)
50
            : TypeHelper::fromPhpType($object->$property);
51
    }
52
53
    private function getStaticProperty($object, $property)
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
54
    {
55
56
        // Isn't this the cutest thing...
57
        return TypeHelper::fromPhpType($object::$$property);
58
    }
59
60
    private function getInstanceProperty($object, $property)
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
61
    {
62
        if (!property_exists($object, $property)) {
63
            return $this->newReturnType('Nil');
64
        }
65
        return TypeHelper::fromPhpType($object->$property);
66
    }
67
68
    private function setProperty($object, $property, $value)
69
    {
70
        if (is_string($object)) {
71
            throw new ArgumentException('.property: Static properties cannot be set from an external context.');
72
        }
73
        $object->$property = $value->value();
74
        return $this->newReturnType('Void');
75
    }
76
}
77