Passed
Push — master ( bc6588...b2ca63 )
by Donald
01:32
created

Store::assertKeyValueIs()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 3
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
1
<?php namespace Chekote\NounStore;
2
3
use InvalidArgumentException;
4
use OutOfBoundsException;
5
use RuntimeException;
6
7
class Store
8
{
9
    /** @var array */
10
    protected $nouns;
11
12
    const FIRST_ORDINAL = 'st';
13
    const SECOND_ORDINAL = 'nd';
14
    const THIRD_ORDINAL = 'rd';
15
    const FOURTH_THROUGH_NINTH_ORDINAL = 'th';
16
17
    /**
18
     * Asserts that a value has been stored for the specified key.
19
     *
20
     * @param  string                   $key   The key to check. @see self::get() for formatting options.
21
     * @param  int                      $index [optional] The index of the key entry to check. If not specified, the
22
     *                                         method will ensure that at least one item is stored for the key.
23
     * @throws OutOfBoundsException     if a value has not been stored for the specified key.
24
     * @throws InvalidArgumentException if both an $index and $key are provided, but the $key contains an nth value
25
     *                                        that does not match the index.
26
     * @return mixed                    The value.
27
     */
28
    public function assertKeyExists($key, $index = null)
29
    {
30
        list($key, $index) = $this->parseKey($key, $index);
31
32
        if (!$this->keyExists($key, $index)) {
33
            throw new OutOfBoundsException("Entry '{$this->buildKey($key, $index)}' was not found in the store.");
34
        }
35
36
        return $this->get($key, $index);
37
    }
38
39
    /**
40
     * Asserts that the keys value matches the specified value.
41
     *
42
     * @param  string                   $key   The key to check. @see self::get() for formatting options.
43
     * @param  mixed                    $value The expected value.
44
     * @param  int                      $index [optional] The index of the key entry to retrieve. If not specified, the
45
     *                                         method will check the most recent value stored under the key.
46
     * @throws OutOfBoundsException     If a value has not been stored for the specified key.
47
     * @throws InvalidArgumentException if both an $index and $key are provided, but the $key contains an nth value
48
     *                                        that does not match the index.
49
     */
50
    public function assertKeyValueIs($key, $value, $index = null)
51
    {
52
        list($key, $index) = $this->parseKey($key, $index);
53
54
        $this->assertKeyExists($key, $index);
55
56
        if ($this->get($key, $index) != $value) {
57
            throw new RuntimeException(
58
                "Entry '{$this->buildKey($key, $index)}' does not match '" . print_r($value, true) . "'"
59
            );
60
        }
61
    }
62
63
    /**
64
     * Removes all entries from the store.
65
     *
66
     * @return void
67
     */
68
    public function reset()
69
    {
70
        $this->nouns = [];
71
    }
72
73
    /**
74
     * Retrieves a value for the specified key.
75
     *
76
     * Each key is actually a collection. If you do not specify which item in the collection you want,
77
     * the method will return the most recent entry. You can specify the entry you want by either
78
     * using the plain english 1st, 2nd, 3rd etc in the $key param, or by specifying 0, 1, 2 etc in
79
     * the $index param. For example:
80
     *
81
     * Retrieve the most recent entry "Thing" collection:
82
     *   retrieve("Thing")
83
     *
84
     * Retrieve the 1st entry in the "Thing" collection:
85
     *   retrieve("1st Thing")
86
     *   retrieve("Thing", 0)
87
     *
88
     * Retrieve the 3rd entry in the "Thing" collection:
89
     *   retrieve("3rd Thing")
90
     *   retrieve("Thing", 2)
91
     *
92
     * Please note: The nth value in the string key is indexed from 1. In that "1st" is the first item stored.
93
     * The index parameter is indexed from 0. In that 0 is the first item stored.
94
     *
95
     * Please Note: If you specify both an $index param and an nth in the $key, they must both reference the same index.
96
     * If they do not, the method will throw an InvalidArgumentException.
97
     *
98
     * retrieve("1st Thing", 1);
99
     *
100
     * @param  string                   $key   The key to retrieve the value for. Can be prefixed with an nth descriptor.
101
     * @param  int                      $index [optional] The index of the key entry to retrieve. If not specified, the
102
     *                                         method will return the most recent value stored under the key.
103
     * @throws InvalidArgumentException if both an $index and $key are provided, but the $key contains an nth value
104
     *                                        that does not match the index.
105
     * @return mixed                    The value, or null if no value exists for the specified key/index combination.
106
     */
107
    public function get($key, $index = null)
108
    {
109
        list($key, $index) = $this->parseKey($key, $index);
110
111
        if (!$this->keyExists($key, $index)) {
112
            return;
113
        }
114
115
        return $index !== null ? $this->nouns[$key][$index] : end($this->nouns[$key]);
116
    }
117
118
    /**
119
     * Retrieves all values for the specified key.
120
     *
121
     * @param  string               $key The key to retrieve the values for.
122
     * @throws OutOfBoundsException if the specified $key does not exist in the store.
123
     * @return array                The values.
124
     */
125
    public function getAll($key)
126
    {
127
        if (!isset($this->nouns[$key])) {
128
            throw new OutOfBoundsException("'$key' does not exist in the store");
129
        }
130
131
        return $this->nouns[$key];
132
    }
133
134
    /**
135
     * Determines if a value has been stored for the specified key.
136
     *
137
     * @param  string                   $key   The key to check.
138
     * @param  int                      $index [optional] The index of the key entry to check. If not specified, the
139
     *                                         method will ensure that at least one item is stored for the key.
140
     * @throws InvalidArgumentException if both an $index and $key are provided, but the $key contains an nth value
141
     *                                        that does not match the index.
142
     * @return bool                     True if the a value has been stored, false if not.
143
     */
144
    public function keyExists($key, $index = null)
145
    {
146
        list($key, $index) = $this->parseKey($key, $index);
147
148
        return $index !== null ? isset($this->nouns[$key][$index]) : isset($this->nouns[$key]);
149
    }
150
151
    /**
152
     * Stores a value for the specified key.
153
     *
154
     * @param string $key   The key to store the value under.
155
     * @param mixed  $value The value to store.
156
     */
157
    public function set($key, $value)
158
    {
159
        $this->nouns[$key][] = $value;
160
    }
161
162
    /**
163
     * Parses a key into the separate key and index value.
164
     *
165
     * @example parseKey("Item"): ["Item", null]
166
     * @example parseKey("Item", 1): ["Item", 1]
167
     * @example parseKey("1st Item"): ["Item", 0]
168
     * @example parseKey("2nd Item"): ["Item", 1]
169
     * @example parseKey("3rd Item"): ["Item", 2]
170
     *
171
     * @param  string                   $key   the key to parse.
172
     * @param  int                      $index [optional] the index to return if the key does not contain one.
173
     * @throws InvalidArgumentException if both an $index and $key are provided, but the $key contains an nth value
174
     *                                        that does not match the index.
175
     * @return array                    a tuple, the 1st being the key with the nth removed, and the 2nd being the
176
     *                                        index.
177
     */
178
    protected function parseKey($key, $index = null)
179
    {
180
        if (preg_match('/^([1-9][0-9]*)(?:st|nd|rd|th) (.+)$/', $key, $matches)) {
181
            if ($index !== null && $index != $matches[1] - 1) {
182
                throw new InvalidArgumentException(
183
                    "$index was provided for index param when key '$key' contains an nth value, but they do not match"
184
                );
185
            }
186
187
            $index = $matches[1] - 1;
188
            $key = $matches[2];
189
        }
190
191
        return [$key, $index];
192
    }
193
194
    /**
195
     * Builds a key from it's separate key and index values.
196
     *
197
     * @example buildKey("Item", null): "Item"
198
     * @example buildKey("Item", 0): "1st Item"
199
     * @example buildKey("Item", 1): "2nd Item"
200
     * @example buildKey("Item", 2): "3rd Item"
201
     *
202
     * @param  string                   $key   The key to check.
203
     * @param  int                      $index The index (zero indexed) value for the key. If not specified, the method
204
     *                                         will not add an index notation to the key.
205
     * @throws InvalidArgumentException if $key is not a string.
206
     * @throws InvalidArgumentException if $index is not an int.
207
     * @return string                   the key with the index, or just the key if index is null.
208
     */
209
    protected function buildKey($key, $index)
210
    {
211
        if ($index === null) {
212
            return $key;
213
        }
214
215
        $nth = $index + 1;
216
217
        return $nth . $this->getOrdinal($nth) . ' ' . $key;
218
    }
219
220
    /**
221
     * Provides the ordinal notation for the specified nth number.
222
     *
223
     * @param  int    $nth the number to determine the ordinal for
224
     * @return string the ordinal
225
     */
226
    protected function getOrdinal($nth)
227
    {
228
        switch (substr($nth, -1)) {
229
            case 1:
230
                $ordinal = self::FIRST_ORDINAL;
231
                break;
232
            case 2:
233
                $ordinal = self::SECOND_ORDINAL;
234
                break;
235
            case 3:
236
                $ordinal = self::THIRD_ORDINAL;
237
                break;
238
            default:
239
                $ordinal = self::FOURTH_THROUGH_NINTH_ORDINAL;
240
                break;
241
        }
242
243
        return $ordinal;
244
    }
245
}
246