Failed Conditions
Pull Request — master (#7)
by Chad
11:01 queued 06:34
created

Strings::format()   C

Complexity

Conditions 7
Paths 4

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 6.9811
c 0
b 0
f 0
cc 7
eloc 12
nc 4
nop 2
1
<?php
2
/**
3
 * Defines \TraderInteractive\Util\Strings class.
4
 */
5
6
namespace TraderInteractive\Util;
7
8
/**
9
 * Static class with various string functions.
10
 */
11
final class Strings
12
{
13
    /**
14
     * Replaces the format items in a specified string with the string representation of n specified objects.
15
     *
16
     * @param string $format A composit format string
17
     * @param mixed  $arguments Variable number of items to format.
18
     *
19
     * @return string Returns a copy of format in which the format items have been
20
     *     replaced by the string representations of arg0, arg1,... argN.
21
     *
22
     * @throws \InvalidArgumentException Thrown if $format is not a string
23
     * @throws \InvalidArgumentException Thrown if all arguments are not castable as strings or
24
     *     if less than two arguments are given
25
     */
26
    public static function format(string $format, string ...$arguments) : string
27
    {
28
        if (!is_string($format)) {
29
            throw new \InvalidArgumentException('$format is not a string');
30
        }
31
32
        foreach ($arguments as $key => $value) {
33
            if (is_scalar($value) || (is_object($value) && method_exists($value, '__toString'))) {
34
                $format = str_replace("{{$key}}", (string)$value, $format);
35
                continue;
36
            }
37
38
            throw new \InvalidArgumentException(
39
                sprintf(
40
                    "Variable of type '%s' could not be converted to a string",
41
                    is_object($value) ? get_class($value) : gettype($value)
42
                )
43
            );
44
        }
45
46
        return $format;
47
    }
48
49
    /**
50
     * Checks if $string ends with $suffix and puts the rest of the $string in $nonSuffix.
51
     *
52
     * @param string $string The string to check
53
     * @param string $suffix The suffix to check for
54
     * @param mixed &$nonSuffix This is the part of the string that is not the suffix.
55
     *
56
     * @return bool whether the $string ended with $suffix or not.
57
     *
58
     * @throws \InvalidArgumentException if $string is not a string
59
     * @throws \InvalidArgumentException if $suffix is not a string
60
     */
61
    public static function endsWith(string $string, string $suffix, &$nonSuffix = null) : bool
62
    {
63
        if (!is_string($string)) {
64
            throw new \InvalidArgumentException('$string is not a string');
65
        }
66
67
        if (!is_string($suffix)) {
68
            throw new \InvalidArgumentException('$suffix is not a string');
69
        }
70
71
        $suffixLength = strlen($suffix);
72
73
        if ($suffixLength === 0) {
74
            $nonSuffix = $string;
75
            return true;
76
        } elseif (empty($string)) {
77
            $nonSuffix = '';
78
            return false;
79
        }
80
81
        if (substr_compare($string, $suffix, -$suffixLength, $suffixLength) !== 0) {
82
            $nonSuffix = $string;
83
            return false;
84
        }
85
86
        $nonSuffix = substr($string, 0, -$suffixLength);
87
        return true;
88
    }
89
90
    /**
91
     * Truncates the string to the given length, with an ellipsis at the end.
92
     *
93
     * @param string $string The string to shorten.
94
     * @param int $maxLength The length to truncate the string to.  The result will not be longer than this, but may be
95
     *                       shorter.
96
     * @param string $suffix The string to append when truncating.  Typically this will be an ellipsis.
97
     *
98
     * @return string The truncated string with the ellipsis included if truncation occured.
99
     *
100
     * @throws \InvalidArgumentException if $string is not a string
101
     * @throws \InvalidArgumentException if $maxLength is not an integer
102
     * @throws \InvalidArgumentException if $maxLength is negative
103
     * @throws \InvalidArgumentException if $suffix is not a string
104
     */
105
    public static function ellipsize(string $string, int $maxLength, string $suffix = '...') : string
106
    {
107
        if (!is_string($string)) {
108
            throw new \InvalidArgumentException('$string is not a string');
109
        }
110
111
        if (!is_int($maxLength)) {
112
            throw new \InvalidArgumentException('$maxLength is not an integer');
113
        }
114
115
        if ($maxLength < 0) {
116
            throw new \InvalidArgumentException('$maxLength is negative');
117
        }
118
119
        if (!is_string($suffix)) {
120
            throw new \InvalidArgumentException('$suffix is not a string');
121
        }
122
123
        if (strlen($string) <= $maxLength) {
124
            return $string;
125
        }
126
127
        $trimmedLength = $maxLength - strlen($suffix);
128
        $string = substr($string, 0, max(0, $trimmedLength));
129
130
        if ($string === '') {
131
            return substr($suffix, 0, $maxLength);
132
        }
133
134
        return $string . $suffix;
135
    }
136
137
    /**
138
     * Uppercases words using custom word delimiters.
139
     *
140
     * This is more flexible than normal php ucwords because that only treats space as a word delimiter.
141
     *
142
     * Here is an example:
143
     * <code>
144
     * <?php
145
     * $string = 'break-down o\'boy up_town you+me here now,this:place';
146
     *
147
     * echo String::ucwords($string);
148
     * // Break-Down O\'Boy Up_Town You+Me Here Now,This:Place
149
     *
150
     * echo String::ucwords($string, '- ');
151
     * // Break-Down O\'boy Up_town You+me Here Now,this:place
152
     * ?>
153
     * </code>
154
     *
155
     * @param string $string The string to titleize.
156
     * @param string $delimiters The characters to treat as word delimiters.
157
     *
158
     * @return string The titleized string.
159
     *
160
     * @throws \InvalidArgumentException if $string is not a string
161
     * @throws \InvalidArgumentException if $delimiters is not a string
162
     */
163
    public static function ucwords(string $string, string $delimiters = "-_+' \n\t\r\0\x0B:/,.") : string
164
    {
165
        if (!is_string($string)) {
166
            throw new \InvalidArgumentException('$string is not a string');
167
        }
168
169
        if (!is_string($delimiters)) {
170
            throw new \InvalidArgumentException('$delimiters is not a string');
171
        }
172
173
        if ($delimiters === '') {
174
            return $string;
175
        }
176
177
        return preg_replace_callback(
178
            '/[^' . preg_quote($delimiters, '/') . ']+/',
179
            function ($matches) {
180
                return ucfirst($matches[0]);
181
            },
182
            $string
183
        );
184
    }
185
}
186