Failed Conditions
Push — possessive_nouns ( b5335d...fee3e3 )
by Donald
01:41
created

Key::parseNoun()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
c 0
b 0
f 0
dl 0
loc 11
rs 10
cc 4
nc 5
nop 1
1
<?php namespace Chekote\NounStore;
2
3
use InvalidArgumentException;
4
5
class Key
6
{
7
    use Singleton;
8
9
    const ORDINAL_ST = 'st';
10
    const ORDINAL_ND = 'nd';
11
    const ORDINAL_RD = 'rd';
12
    const ORDINAL_TH = 'th';
13
14
    protected static $ordinals = [
15
        0 => self::ORDINAL_TH,
16
        1 => self::ORDINAL_ST,
17
        2 => self::ORDINAL_ND,
18
        3 => self::ORDINAL_RD,
19
        4 => self::ORDINAL_TH,
20
        5 => self::ORDINAL_TH,
21
        6 => self::ORDINAL_TH,
22
        7 => self::ORDINAL_TH,
23
        8 => self::ORDINAL_TH,
24
        9 => self::ORDINAL_TH,
25
    ];
26
27
    const POSSESSION = "'s ";
28
29
    /**
30
     * Builds a key from it's separate key and index values.
31
     *
32
     * @example buildKey("Item", null): "Item"
33
     * @example buildKey("Item", 0): "1st Item"
34
     * @example buildKey("Item", 1): "2nd Item"
35
     * @example buildKey("Item", 2): "3rd Item"
36
     *
37
     * @param  string                   $key   The key to check.
38
     * @param  int|null                 $index The index (zero indexed) value for the key. If not specified, the method
39
     *                                         will not add an index notation to the key.
40
     * @throws InvalidArgumentException if $index is less than -1. Note: It should really be zero or higher, but this
41
     *                                        method does not assert that. The error is bubbling up from getOrdinal()
42
     * @return string                   the key with the index, or just the key if index is null.
43
     */
44
    public function build($key, $index)
45
    {
46
        if ($index === null) {
47
            return $key;
48
        }
49
50
        $nth = $index + 1;
51
52
        return $nth . $this->getOrdinal($nth) . ' ' . $key;
53
    }
54
55
    /**
56
     * Provides the ordinal notation for the specified nth number.
57
     *
58
     * @param  int                      $nth the number to determine the ordinal for
59
     * @throws InvalidArgumentException if $nth is not a positive number.
60
     * @return string                   the ordinal
61
     */
62
    public function getOrdinal($nth)
63
    {
64
        if ($nth < 0) {
65
            throw new InvalidArgumentException('$nth must be a positive number');
66
        }
67
68
        return $nth > 9 && $nth < 20 ? self::ORDINAL_TH : self::$ordinals[substr($nth, -1)];
69
    }
70
71
    /**
72
     * Parses a key into its individual nouns and indexes.
73
     *
74
     * @example parseNoun("Customer"): [["Customer", null]]
75
     * @example parseNoun("2nd Customer"): [["Customer", 1]]
76
     * @example parseNoun("Customer's Car"): [["Customer", null], ["Car", null]]
77
     * @example parseNoun("2nd Customer's Car"): [["Customer", 1], ["Car", null]]
78
     * @example parseNoun("2nd Customer's 3rd Car"): [["Customer", 1], ["Car", 2]]
79
     *
80
     * @param  string                   $key the key to parse.
81
     * @throws InvalidArgumentException if the key syntax is invalid.
82
     * @return array[]                  a array of tuples. With each tuple have the noun with the nth removed as the
83
     *                                      1st item, and the index that the nth translates to as the 2nd or null if no
84
     *                                      nth was specified.
85
     */
86
    public function parse($key) {
87
        return array_map([$this, 'parseNoun'], $this->splitPossessions($key));
88
    }
89
90
    /**
91
     * Parses a noun into the separate key and index value.
92
     *
93
     * @example parseNoun("Item"): ["Item", null]
94
     * @example parseNoun("1st Item"): ["Item", 0]
95
     * @example parseNoun("2nd Item"): ["Item", 1]
96
     * @example parseNoun("3rd Item"): ["Item", 2]
97
     *
98
     * @param  string                   $noun the key to parse.
99
     * @throws InvalidArgumentException if the key syntax is invalid.
100
     * @return array                    a tuple, the 1st being the key with the nth removed, and the 2nd being the
101
     *                                      index that the nth translates to, or null if no nth was specified.
102
     */
103
    public function parseNoun($noun)
104
    {
105
        if (!preg_match("/^(([1-9][0-9]*)(?:st|nd|rd|th) )?([^']+)$/", $noun, $matches)) {
106
            throw new InvalidArgumentException('Key syntax is invalid');
107
        }
108
109
        // @todo use null coalescing operator when upgrading to PHP 7
110
        $index = isset($matches[2]) && $matches[2] !== '' ? $matches[2] - 1 : null;
111
        $noun = $matches[3];
112
113
        return [$noun, $index];
114
    }
115
116
    /**
117
     * Resolves an index and parsed nth value to an index.
118
     *
119
     * Ensures that if both an index and parsed nth value are provided, that they are equivalent. If only one is
120
     * provided, then the appropriate index will be returned. e.g. if an index is provided, it is returned as-is, as
121
     * it is already an index. If an nth is provided, it will be returned decremented by 1.
122
     *
123
     * @param  int|null                 $index the index to process
124
     * @param  int|null                 $nth   the nth to process
125
     * @throws InvalidArgumentException if both an $index and $key are provided, but the $key contains an nth value
126
     *                                        that does not match the index.
127
     * @throws InvalidArgumentException if nth is not null and is less than 1
128
     * @return int                      the resolved index.
129
     */
130
    protected function resolveIndex($index, $nth)
131
    {
132
        // If we don't have an nth, there's nothing to process. We'll just return the $index, even if it's null.
133
        if ($nth === null) {
134
            return $index;
135
        }
136
137
        $decrementedNth = $nth - 1;
138
139
        // If both index and nth are provided, but they aren't equivalent, we need to error out.
140
        if ($index !== null && $index !== $decrementedNth) {
141
            throw new InvalidArgumentException("index $index was provided with nth $nth, but they are not equivalent");
142
        }
143
144
        if ($decrementedNth < 0) {
145
            throw new InvalidArgumentException('nth must be equal to or larger than 1');
146
        }
147
148
        return $decrementedNth;
149
    }
150
151
    /**
152
     * Determines if the specified key is a possessive noun.
153
     *
154
     * @param  string $key
155
     * @return bool   true if the key is possessive, false if not
156
     */
157
    protected function isPossessive($key)
158
    {
159
        return strpos($key, self::POSSESSION) !== false;
160
    }
161
162
    /**
163
     * Splits a possessive key into its separate nouns.
164
     *
165
     * @example splitPossessions("Customer's Car"): ['Customer', 'Car']
166
     * @example splitPossessions("8th Customer's Car"): ['8th Customer', 'Car']
167
     * @example splitPossessions("Customer's 2nd Car"): ['Customer', '2nd Car']
168
     * @example splitPossessions("7th Customer's 4th Car"): ['7th Customer', '4th Car']
169
     * @example splitPossessions("7th Customer's 4th Car's 2nd Wheel"): ['7th Customer', '4th Car', '2nd Wheel']
170
     *
171
     * @param  string   $key the possessive key to parse
172
     * @return string[] an array of nouns
173
     */
174
    protected function splitPossessions($key)
175
    {
176
        return preg_split('/' . self::POSSESSION . '/', $key);
0 ignored issues
show
Bug Best Practice introduced by
The expression return preg_split('/' . ...POSSESSION . '/', $key) returns the type false which is incompatible with the documented return type string[].
Loading history...
177
    }
178
}
179