Passed
Pull Request — master (#59)
by
unknown
02:21
created

mappings.php ➔ constant()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 6
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @copyright Zicht Online <http://zicht.nl>
4
 */
5
6
namespace Zicht\Itertools\mappings;
7
8
use Zicht\Itertools\conversions;
9
10
/**
11
 * Returns a closure that strips any matching $CHARS from the left of the input string
12
 *
13
 * @param string $chars
14
 * @return \Closure
15
 */
16
function lstrip($chars = " \t\n\r\0\x0B")
17
{
18
    return function ($value) use ($chars) {
19 5
        return ltrim($value, $chars);
20 5
    };
21
}
22
23
/**
24
 * Returns a closure that strips any matching $CHARS from the right of the input string
25
 *
26
 * @param string $chars
27
 * @return \Closure
28
 */
29
function rstrip($chars = " \t\n\r\0\x0B")
30
{
31
    return function ($value) use ($chars) {
32 5
        return rtrim($value, $chars);
33 5
    };
34
}
35
36
/**
37
 * Returns a closure that strips any matching $CHARS from the left and right of the input string
38
 *
39
 * @param string $chars
40
 * @return \Closure
41
 */
42
function strip($chars = " \t\n\r\0\x0B")
43
{
44
    return function ($value) use ($chars) {
45 5
        return trim($value, $chars);
46 6
    };
47
}
48
49
/**
50
 * Returns a closure that returns the length of the input
51
 *
52
 * @return \Closure
53
 */
54
function length()
55
{
56
    return function ($value) {
57 3
        if (is_null($value)) {
58 3
            return 0;
59
        }
60
61 3
        if (is_string($value)) {
62 3
            return strlen($value);
63
        }
64
65 3
        return sizeof($value);
66 3
    };
67
}
68
69
/**
70
 * Returns a closure that returns the key
71
 *
72
 * @return \Closure
73
 */
74
function key()
75
{
76
    return function ($value, $key) {
77 5
        return $key;
78 5
    };
79
}
80
81
/**
82
 * Returns a closure that returns the string value lower cased
83
 *
84
 * @return \Closure
85
 */
86
function lower()
87
{
88
    return function ($value) {
89 1
        return strtolower($value);
90 1
    };
91
}
92
93
/**
94
 * Returns a closure that returns the string value upper cased
95
 *
96
 * @return \Closure
97
 */
98
function upper()
99
{
100
    return function ($value) {
101 1
        return strtoupper($value);
102 1
    };
103
}
104
105
/**
106
 * Returns a closure that returns the value cast to a string
107
 *
108
 * @return \Closure
109
 */
110
function string()
111
{
112
    return function ($value) {
113 1
        return (string)$value;
114 1
    };
115
}
116
117
/**
118
 * Returns a closure that returns the value as a json_encoded string
119
 *
120
 * @param int $options
121
 * @param int $depth
122
 * @return \Closure
123
 */
124
function json_encode($options = 0, $depth = 512)
125
{
126
    return function ($value) use ($options, $depth) {
127 1
        return \json_encode($value, $options, $depth);
128 1
    };
129
}
130
131
/**
132
 * Returns a closure that returns the json_encoded value as decoded value
133
 *
134
 * @param boolean $assoc
135
 * @param int $depth
136
 * @param int $options
137
 * @return \Closure
138
 */
139
function json_decode($assoc = false, $depth = 512, $options = 0)
140
{
141
    return function ($value) use ($assoc, $depth, $options) {
142 1
        return \json_decode($value, $assoc, $depth, $options);
143 1
    };
144
}
145
146
/**
147
 * Returns a closure that applies multiple $STRATEGIES to the value and returns the results
148
 *
149
 * > $compute = function ($value, $key) {
150
 * >    return 'some computation result';
151
 * > };
152
 * > $list = iter\iterable([new Data(1), new Data(2), new Data(3)]);
153
 * > $list->map(select(['data' => null, 'id' => 'Identifier', 'desc' => 'Value.DescriptionName', 'comp' => $compute]));
154
 * [
155
 *    [
156
 *       'data' => Data(1),
157
 *       'id' => Data(1)->Identifier,
158
 *       'desc' => Data(1)->Value->DescriptionName,
159
 *       'comp' => $compute(Data(1), 0),
160
 *    ],
161
 *    ...
162
 *    [
163
 *       'data' => Data(3),
164
 *       'id' => Data(3)->Identifier,
165
 *       'desc' => Data(3)->Value->DescriptionName,
166
 *       'comp' => $compute(Data(3), 2),
167
 *    ],
168
 * ]
169
 *
170
 * @param array|object $mappings
171
 * @param null|string|\Closure $strategy
172
 * @param boolean $discardNull
173
 * @param boolean $discardEmptyContainer
174
 * @return \Closure
175
 */
176
function select($mappings, $strategy = null, $discardNull = false, $discardEmptyContainer = false)
177
{
178 9
    $castToObject = is_object($mappings);
179 9
    $mappings = array_map('\Zicht\Itertools\conversions\mixed_to_value_getter', (array)$mappings);
180 9
    $strategy = conversions\mixed_to_value_getter($strategy);
181
182
    return function ($value, $key) use ($mappings, $strategy, $discardNull, $discardEmptyContainer, $castToObject) {
183 9
        $value = $strategy($value);
184 9
        $res = [];
185 9
        foreach ($mappings as $strategyKey => $strategy) {
186 7
            $res[$strategyKey] = $strategy($value, $key);
187
        }
188 9
        if ($discardNull || $discardEmptyContainer) {
189 2
            $res = array_filter(
190 2
                $res,
191
                function ($value) use ($discardNull, $discardEmptyContainer) {
192 2
                    if (null === $value) {
193 1
                        return !$discardNull;
194
                    }
195
196 2
                    if (is_array($value) && 0 === sizeof($value)) {
197 1
                        return !$discardEmptyContainer;
198
                    }
199
200 2
                    return true;
201 2
                }
202
            );
203
        }
204 9
        return $castToObject ? (object)$res : $res;
205 9
    };
206
}
207
208
/**
209
 * Returns a closure that returns random integer numbers between $MIN and $MAX
210
 *
211
 * @param int $min
212
 * @param null|int $max
213
 * @return \Closure
214
 */
215
function random($min = 0, $max = null)
216
{
217 5
    if (null === $max) {
218 1
        $max = getrandmax();
219
    }
220
221
    return function () use ($min, $max) {
222 5
        return rand($min, $max);
223 5
    };
224
}
225
226
/**
227
 * Returns a closure that returns either the class name, given an object, or otherwise the type
228
 *
229
 * @param null|string|\Closure $strategy
230
 * @return \Closure
231
 */
232
function type($strategy = null)
233
{
234 6
    $strategy = conversions\mixed_to_value_getter($strategy);
235
    return function ($value) use ($strategy) {
236 6
        $value = $strategy($value);
237 6
        return is_object($value) ? get_class($value) : gettype($value);
238 6
    };
239
}
240
241
/**
242
 * Returns a closure that calls the mapping on each element once.
243
 *
244
 * > $compute = function ($value, $key) {
245
 * >    return 'some expensive computation result';
246
 * > };
247
 * > $list = iter\iterable([['id' => 42, ...], ['id' => 43, ...], ['id' => 42, ...]]);
248
 * > $list->map(cache($compute, 'id'));
249
 * [
250
 *    $compute(['id' => 42, ...]), // <-- calls the $compute method
251
 *    $compute(['id' => 43, ...]), // <-- calls the $compute method
252
 *    $compute(['id' => 42, ...])  // <-- does not call, instead, populates with cached values
253
 * ]
254
 *
255
 * @param null|string|\Closure $mapping
256
 * @param null|string|\Closure $strategy
257
 * @return \Closure
258
 */
259
function cache($mapping, $strategy = null)
260
{
261 2
    $mapping = conversions\mixed_to_value_getter($mapping);
262 2
    $strategy = conversions\mixed_to_value_getter($strategy);
263 2
    $cache = [];
264
    return function ($value, $key = null) use ($mapping, $strategy, &$cache) {
265 2
        $cacheKey = \json_encode($strategy($value, $key));
266 2
        if (!array_key_exists($cacheKey, $cache)) {
267 2
            $cache[$cacheKey] = $mapping($value, $key);
268
        }
269 2
        return $cache[$cacheKey];
270 2
    };
271
}
272
273
/**
274
 * Returns a closure that returns the same value every time it is called.
275
 *
276
 * @param null|string|int|float|bool|object|array $value
277
 * @return \Closure
278
 */
279
function constant($value)
280
{
281
    return function () use ($value) {
282 1
        return $value;
283 1
    };
284
}
285
286
/**
287
 * Returns a mapping closure
288
 *
289
 * @param string $name
290
 * @return \Closure
291
 * @throws \InvalidArgumentException
292
 *
293
 * @deprecated please use the mapping functions directly, will be removed in version 3.0
294
 */
295
function get_mapping($name /* [argument, [arguments, ...] */)
296
{
297
    if (is_string($name)) {
298
        switch ($name) {
299
            case 'ltrim':
300
            case 'lstrip':
301
                return call_user_func_array('\Zicht\Itertools\mappings\lstrip', array_slice(func_get_args(), 1));
302
303
            case 'rtrim':
304
            case 'rstrip':
305
                return call_user_func_array('\Zicht\Itertools\mappings\rstrip', array_slice(func_get_args(), 1));
306
307
            case 'trim':
308
            case 'strip':
309
                return call_user_func_array('\Zicht\Itertools\mappings\strip', array_slice(func_get_args(), 1));
310
311
            case 'length':
312
                return length();
313
314
            case 'key':
315
                return key();
316
317
            case 'select':
318
                return call_user_func_array('\Zicht\Itertools\mappings\select', array_slice(func_get_args(), 1));
319
320
            case 'random':
321
                return call_user_func_array('\Zicht\Itertools\mappings\random', array_slice(func_get_args(), 1));
322
323
            case 'type':
324
                return call_user_func_array('\Zicht\Itertools\mappings\type', array_slice(func_get_args(), 1));
325
        }
326
    }
327
328
    throw new \InvalidArgumentException(sprintf('$NAME "%s" is not a valid mapping.', $name));
329
}
330
331
/**
332
 * @param string $name
333
 * @return \Closure
334
 * @throws \InvalidArgumentException
335
 *
336
 * @deprecated please use the mapping functions directly, will be removed in version 3.0
337
 */
338
function getMapping($name /* [argument, [arguments, ...] */) // phpcs:ignore Zicht.NamingConventions.Functions.GlobalNaming
0 ignored issues
show
Unused Code introduced by
The parameter $name is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
339
{
340
    return call_user_func_array('\Zicht\Itertools\mappings\get_mapping', func_get_args());
341
}
342