Passed
Push — master ( 082614...4e2d52 )
by Donald
01:34
created

Store::keyValueContains()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 3
dl 0
loc 7
rs 9.4285
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 key's 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
     * Asserts that the key's value contains the specified string.
65
     *
66
     * @param  string                   $key   The key to check. @see self::get() for formatting options.
67
     * @param  string                   $value The value expected to be contained within the key's value.
68
     * @param  int                      $index [optional] The index of the key entry to retrieve. If not specified, the
69
     *                                         method will check the most recent value stored under the key.
70
     * @throws OutOfBoundsException     If a value has not been stored for the specified key.
71
     * @throws InvalidArgumentException if both an $index and $key are provided, but the $key contains an nth value
72
     *                                        that does not match the index.
73
     */
74
    public function assertKeyValueContains($key, $value, $index = null)
75
    {
76
        list($key, $index) = $this->parseKey($key, $index);
77
78
        $this->assertKeyExists($key, $index);
79
80
        if (!$this->keyValueContains($key, $value, $index)) {
81
            throw new RuntimeException(
82
                "Entry '{$this->buildKey($key, $index)}' does not contain '$value'"
83
            );
84
        }
85
    }
86
87
    /**
88
     * Removes all entries from the store.
89
     *
90
     * @return void
91
     */
92
    public function reset()
93
    {
94
        $this->nouns = [];
95
    }
96
97
    /**
98
     * Retrieves a value for the specified key.
99
     *
100
     * Each key is actually a collection. If you do not specify which item in the collection you want,
101
     * the method will return the most recent entry. You can specify the entry you want by either
102
     * using the plain english 1st, 2nd, 3rd etc in the $key param, or by specifying 0, 1, 2 etc in
103
     * the $index param. For example:
104
     *
105
     * Retrieve the most recent entry "Thing" collection:
106
     *   retrieve("Thing")
107
     *
108
     * Retrieve the 1st entry in the "Thing" collection:
109
     *   retrieve("1st Thing")
110
     *   retrieve("Thing", 0)
111
     *
112
     * Retrieve the 3rd entry in the "Thing" collection:
113
     *   retrieve("3rd Thing")
114
     *   retrieve("Thing", 2)
115
     *
116
     * Please note: The nth value in the string key is indexed from 1. In that "1st" is the first item stored.
117
     * The index parameter is indexed from 0. In that 0 is the first item stored.
118
     *
119
     * Please Note: If you specify both an $index param and an nth in the $key, they must both reference the same index.
120
     * If they do not, the method will throw an InvalidArgumentException.
121
     *
122
     * retrieve("1st Thing", 1);
123
     *
124
     * @param  string                   $key   The key to retrieve the value for. Can be prefixed with an nth descriptor.
125
     * @param  int                      $index [optional] The index of the key entry to retrieve. If not specified, the
126
     *                                         method will return the most recent value stored under the key.
127
     * @throws InvalidArgumentException if both an $index and $key are provided, but the $key contains an nth value
128
     *                                        that does not match the index.
129
     * @return mixed                    The value, or null if no value exists for the specified key/index combination.
130
     */
131
    public function get($key, $index = null)
132
    {
133
        list($key, $index) = $this->parseKey($key, $index);
134
135
        if (!$this->keyExists($key, $index)) {
136
            return;
137
        }
138
139
        return $index !== null ? $this->nouns[$key][$index] : end($this->nouns[$key]);
140
    }
141
142
    /**
143
     * Retrieves all values for the specified key.
144
     *
145
     * @param  string               $key The key to retrieve the values for.
146
     * @throws OutOfBoundsException if the specified $key does not exist in the store.
147
     * @return array                The values.
148
     */
149
    public function getAll($key)
150
    {
151
        if (!isset($this->nouns[$key])) {
152
            throw new OutOfBoundsException("'$key' does not exist in the store");
153
        }
154
155
        return $this->nouns[$key];
156
    }
157
158
    /**
159
     * Determines if a value has been stored for the specified key.
160
     *
161
     * @param  string                   $key   The key to check.
162
     * @param  int                      $index [optional] The index of the key entry to check. If not specified, the
163
     *                                         method will ensure that at least one item is stored for the key.
164
     * @throws InvalidArgumentException if both an $index and $key are provided, but the $key contains an nth value
165
     *                                        that does not match the index.
166
     * @return bool                     True if the a value has been stored, false if not.
167
     */
168
    public function keyExists($key, $index = null)
169
    {
170
        list($key, $index) = $this->parseKey($key, $index);
171
172
        return $index !== null ? isset($this->nouns[$key][$index]) : isset($this->nouns[$key]);
173
    }
174
175
    /**
176
     * Asserts that the key's value contains the specified string.
177
     *
178
     * @param  string                   $key   The key to check. @see self::get() for formatting options.
179
     * @param  string                   $value The value expected to be contained within the key's value.
180
     * @param  int                      $index [optional] The index of the key entry to retrieve. If not specified, the
181
     *                                         method will check the most recent value stored under the key.
182
     * @throws InvalidArgumentException if both an $index and $key are provided, but the $key contains an nth value
183
     *                                        that does not match the index.
184
     * @return bool                     True if the key's value contains the specified string, false if not.
185
     */
186
    public function keyValueContains($key, $value, $index = null)
187
    {
188
        list($key, $index) = $this->parseKey($key, $index);
189
190
        $actual = $this->get($key, $index);
191
192
        return is_string($actual) && strpos($actual, $value) !== false;
193
    }
194
195
    /**
196
     * Stores a value for the specified key.
197
     *
198
     * @param string $key   The key to store the value under.
199
     * @param mixed  $value The value to store.
200
     */
201
    public function set($key, $value)
202
    {
203
        $this->nouns[$key][] = $value;
204
    }
205
206
    /**
207
     * Parses a key into the separate key and index value.
208
     *
209
     * @example parseKey("Item"): ["Item", null]
210
     * @example parseKey("Item", 1): ["Item", 1]
211
     * @example parseKey("1st Item"): ["Item", 0]
212
     * @example parseKey("2nd Item"): ["Item", 1]
213
     * @example parseKey("3rd Item"): ["Item", 2]
214
     *
215
     * @param  string                   $key   the key to parse.
216
     * @param  int                      $index [optional] the index to return if the key does not contain one.
217
     * @throws InvalidArgumentException if both an $index and $key are provided, but the $key contains an nth value
218
     *                                        that does not match the index.
219
     * @return array                    a tuple, the 1st being the key with the nth removed, and the 2nd being the
220
     *                                        index.
221
     */
222
    protected function parseKey($key, $index = null)
223
    {
224
        if (preg_match('/^([1-9][0-9]*)(?:st|nd|rd|th) (.+)$/', $key, $matches)) {
225
            if ($index !== null && $index != $matches[1] - 1) {
226
                throw new InvalidArgumentException(
227
                    "$index was provided for index param when key '$key' contains an nth value, but they do not match"
228
                );
229
            }
230
231
            $index = $matches[1] - 1;
232
            $key = $matches[2];
233
        }
234
235
        return [$key, $index];
236
    }
237
238
    /**
239
     * Builds a key from it's separate key and index values.
240
     *
241
     * @example buildKey("Item", null): "Item"
242
     * @example buildKey("Item", 0): "1st Item"
243
     * @example buildKey("Item", 1): "2nd Item"
244
     * @example buildKey("Item", 2): "3rd Item"
245
     *
246
     * @param  string                   $key   The key to check.
247
     * @param  int                      $index The index (zero indexed) value for the key. If not specified, the method
248
     *                                         will not add an index notation to the key.
249
     * @throws InvalidArgumentException if $key is not a string.
250
     * @throws InvalidArgumentException if $index is not an int.
251
     * @return string                   the key with the index, or just the key if index is null.
252
     */
253
    protected function buildKey($key, $index)
254
    {
255
        if ($index === null) {
256
            return $key;
257
        }
258
259
        $nth = $index + 1;
260
261
        return $nth . $this->getOrdinal($nth) . ' ' . $key;
262
    }
263
264
    /**
265
     * Provides the ordinal notation for the specified nth number.
266
     *
267
     * @param  int    $nth the number to determine the ordinal for
268
     * @return string the ordinal
269
     */
270
    protected function getOrdinal($nth)
271
    {
272
        switch (substr($nth, -1)) {
273
            case 1:
274
                $ordinal = self::FIRST_ORDINAL;
275
                break;
276
            case 2:
277
                $ordinal = self::SECOND_ORDINAL;
278
                break;
279
            case 3:
280
                $ordinal = self::THIRD_ORDINAL;
281
                break;
282
            default:
283
                $ordinal = self::FOURTH_THROUGH_NINTH_ORDINAL;
284
                break;
285
        }
286
287
        return $ordinal;
288
    }
289
}
290