Completed
Push — master ( 031221...6cba54 )
by Marcel
02:18
created

Quantity   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
c 1
b 0
f 0
lcom 0
cbo 2
dl 0
loc 34
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B format() 0 21 6
1
<?php
2
namespace nochso\Omni\Format;
3
4
use nochso\Omni\Dot;
5
use nochso\Omni\Numeric;
6
7
/**
8
 * Quantity formats a string depending on quantity (many, one or zero).
9
 * 
10
 * The plural, singular and empty formats of the string can be defined like this:
11
 *
12
 * `(plural|singular|zero)`
13
 * 
14
 * The singular and zero formats are optional:
15
 * 
16
 * ```php
17
 * Quantity::format('day(s)', 1); // day
18
 * Quantity::format('day(s)', 0); // days
19
 * ```
20
 *
21
 * If the `zero` format is not defined, the plural form will be used instead.
22
 * Alternatively you can use an empty string:
23
 * 
24
 * ```php
25
 * Quantity::format('(many|one|)', 0); // empty string
26
 * ```
27
 * 
28
 * Example with all three formats:
29
 * 
30
 * ```php
31
 * Quantity::format('(bugs|bug|no bugs at all)', 5) // bugs
32
 * Quantity::format('(bugs|bug|no bugs at all)', 1) // bug
33
 * Quantity::format('(bugs|bug|no bugs at all)', 0) // no bugs at all
34
 * ```
35
 */
36
class Quantity
37
{
38
    /**
39
     * Format a string depending on a quantity.
40
     * 
41
     * See the class documentation for defining `$format`.
42
     * 
43
     * @param string $format
44
     * @param string $quantity
45
     *
46
     * @return mixed
47
     */
48
    public static function format($format, $quantity)
49
    {
50
        $quantity = Numeric::ensure($quantity);
51
        $callback = function ($matches) use ($quantity) {
52
            // Get available choices
53
            $choices = preg_split('/\|/', $matches[2]);
54
            // Assume plural
55
            $choice = 0;
56
            // Choose singular
57
            if ($quantity === 1.0 || $quantity === 1) {
58
                $choice = 1;
59
            }
60
            // Choose zero if it's defined, otherwise keep using plural format
61
            if (($quantity === 0 || $quantity === 0.0) && isset($choices[2])) {
62
                $choice = 2;
63
            }
64
            return Dot::get($choices, $choice, '');
65
        };
66
        $pattern = '/(?<!\\\\)(\\((.+?(?<!\\\\))\\))/';
67
        return preg_replace_callback($pattern, $callback, $format);
68
    }
69
}
70