Bag::has()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
/**
3
 * Veto.
4
 * PHP Microframework.
5
 *
6
 * @author Damien Walsh <[email protected]>
7
 * @copyright Damien Walsh 2013-2014
8
 * @version 0.1
9
 * @package veto
10
 */
11
namespace Veto\Collection;
12
13
/**
14
 * Bag
15
 *
16
 * @since 0.1
17
 */
18
class Bag implements \IteratorAggregate
19
{
20
    /**
21
     * @var mixed[]
22
     */
23
    protected $items;
24
25
    /**
26
     * Initialise the object
27
     *
28
     * @param array $items Initial items to create the Bag with.
29
     */
30
    public function __construct($items = array())
31
    {
32
        $this->items = $items;
33
    }
34
35
    /**
36
     * Add an item to the bag
37
     *
38
     * @param mixed $key
39
     * @param mixed $value
40
     * @return $this
41
     */
42
    public function add($key, $value)
43
    {
44
        $this->items[$key] = $value;
45
        return $this;
46
    }
47
48
    /**
49
     * Get an item from the bag by key, optionally returning a default if the key is not found.
50
     *
51
     * @param mixed $key
52
     * @param mixed $default
53
     * @return mixed|null
54
     */
55
    public function get($key, $default = null)
56
    {
57
        if (array_key_exists($key, $this->items)) {
58
            return $this->items[$key];
59
        } else {
60
            return $default;
61
        }
62
    }
63
64
    /**
65
     * Check if the bag contains a given key
66
     *
67
     * @param mixed $key
68
     * @return bool
69
     */
70
    public function has($key)
71
    {
72
        return array_key_exists($key, $this->items);
73
    }
74
75
    /**
76
     * If the bag contains the given key, return the value, then remove it from the bag.
77
     *
78
     * @param $key
79
     * @return mixed|null
80
     */
81
    public function remove($key)
82
    {
83
        if (array_key_exists($key, $this->items)) {
84
            $value = $this->items[$key];
85
            unset($this->items[$key]);
86
            return $value;
87
        } else {
88
            return null;
89
        }
90
    }
91
92
    /**
93
     * @return \ArrayIterator
94
     */
95
    public function getIterator()
96
    {
97
        return new \ArrayIterator($this->items);
98
    }
99
100
    /**
101
     * Get the underlying array of the contents of the bag.
102
     *
103
     * @return array
104
     */
105
    public function all()
106
    {
107
        return $this->items;
108
    }
109
}
110