DynamicObjectTrait   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 81
Duplicated Lines 0 %

Coupling/Cohesion

Components 3
Dependencies 0

Importance

Changes 0
Metric Value
dl 0
loc 81
rs 10
c 0
b 0
f 0
wmc 6
lcom 3
cbo 0

4 Methods

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