Completed
Pull Request — master (#23)
by Erin
03:28
created

DynamicObjectTrait::addProperty()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 5
rs 9.4285
cc 1
eloc 3
nc 1
nop 3
1
<?php
2
namespace Peridot\Leo;
3
4
/**
5
 * DynamicObjectTrait adds methods for dynamically defining methods, flags, and properties.
6
 * @package Peridot\Leo
7
 */
8
trait DynamicObjectTrait
9
{
10
    /**
11
     * @var array
12
     */
13
    protected $methods = [];
14
15
    /**
16
     * @var array
17
     */
18
    protected $properties = [];
19
20
    /**
21
     * @var array
22
     */
23
    protected $flags = [];
24
25
    /**
26
     * Add a method identified by the given name.
27
     *
28
     * @param string $name
29
     * @param callable $method the body of the method
30
     * @return $this
31
     */
32
    public function addMethod($name, callable $method)
33
    {
34
        $this->methods[$name] = \Closure::bind($method, $this, $this);
35
        return $this;
36
    }
37
38
    /**
39
     * Adds a lazy property identified by the given name. The property
40
     * is lazy because it is not evaluated until asked for via __get().
41
     *
42
     * @param string $name
43
     * @param callable $factory
44
     * @param bool $memoize
45
     * @return $this
46
     */
47
    public function addProperty($name, callable $factory, $memoize = false)
48
    {
49
        $this->properties[$name] = ['factory' => \Closure::bind($factory, $this, $this), 'memoize' => $memoize];
50
        return $this;
51
    }
52
53
    /**
54
     * A simple mechanism for storing arbitrary flags. Flags are useful
55
     * for tweaking behavior based on their presence.
56
     *
57
     * @return $this|mixed
58
     */
59
    public function flag()
60
    {
61
        $args = func_get_args();
62
        $num = count($args);
63
64
        if ($num > 1) {
65
            $this->flags[$args[0]] = $args[1];
66
            return $this;
67
        }
68
69
        if (array_key_exists($args[0], $this->flags)) {
70
            return $this->flags[$args[0]];
71
        }
72
    }
73
74
    /**
75
     * Reset flags. Flags are generally cleared after an Assertion is made.
76
     *
77
     * @return $this
78
     */
79
    public function clearFlags()
80
    {
81
        $this->flags = [];
82
        return $this;
83
    }
84
}
85