Passed
Pull Request — master (#9)
by
unknown
01:33
created

Strings::validateIfObjectIsAString()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
nc 2
nop 1
dl 0
loc 4
c 0
b 0
f 0
cc 2
rs 10
1
<?php
2
3
namespace TraderInteractive\Filter;
4
5
use TraderInteractive\Exceptions\FilterException;
6
use TypeError;
7
8
/**
9
 * A collection of filters for strings.
10
 */
11
final class Strings
12
{
13
    /**
14
     * Filter a string.
15
     *
16
     * Verify that the passed in value  is a string.  By default, nulls are not allowed, and the length is restricted
17
     * between 1 and PHP_INT_MAX.  These parameters can be overwritten for custom behavior.
18
     *
19
     * The return value is the string, as expected by the \TraderInteractive\Filterer class.
20
     *
21
     * @param mixed $value The value to filter.
22
     * @param bool $allowNull True to allow nulls through, and false (default) if nulls should not be allowed.
23
     * @param int $minLength Minimum length to allow for $value.
24
     * @param int $maxLength Maximum length to allow for $value.
25
     * @return string|null The passed in $value.
26
     *
27
     * @throws FilterException if the value did not pass validation.
28
     * @throws \InvalidArgumentException if one of the parameters was not correctly typed.
29
     */
30
    public static function filter(
31
        $value = null,
32
        bool $allowNull = false,
33
        int $minLength = 1,
34
        int $maxLength = PHP_INT_MAX
35
    ) {
36
        self::validateMinimumLength($minLength);
37
        self::validateMaximumLength($maxLength);
38
39
        if (self::valueIsNullAndValid($allowNull, $value)) {
40
            return null;
41
        }
42
43
        $value = self::enforceValueCanBeCastAsString($value);
44
45
        self::validateStringLength($value, $minLength, $maxLength);
46
47
        return $value;
48
    }
49
50
    /**
51
     * Explodes a string into an array using the given delimiter.
52
     *
53
     * For example, given the string 'foo,bar,baz', this would return the array ['foo', 'bar', 'baz'].
54
     *
55
     * @param string $value The string to explode.
56
     * @param string $delimiter The non-empty delimiter to explode on.
57
     * @return array The exploded values.
58
     *
59
     * @throws \InvalidArgumentException if the delimiter does not pass validation.
60
     */
61
    public static function explode($value, string $delimiter = ',')
62
    {
63
        self::validateIfObjectIsAString($value);
64
65
        if (empty($delimiter)) {
66
            throw new \InvalidArgumentException(
67
                "Delimiter '" . var_export($delimiter, true) . "' is not a non-empty string"
68
            );
69
        }
70
71
        return explode($delimiter, $value);
72
    }
73
74
    /**
75
     * This filter takes the given string and translates it using the given value map.
76
     *
77
     * @param string $value    The string value to translate
78
     * @param array  $valueMap Array of key value pairs where a key will match the given $value.
79
     *
80
     * @return string
81
     */
82
    public static function translate(string $value, array $valueMap) : string
83
    {
84
        if (!array_key_exists($value, $valueMap)) {
85
            throw new FilterException("The value '{$value}' was not found in the translation map array.");
86
        }
87
88
        return $valueMap[$value];
89
    }
90
91
    /**
92
     * This filter prepends $prefix and appends $suffix to the string value.
93
     *
94
     * @param mixed  $value  The string value to which $prefix and $suffix will be added.
95
     * @param string $prefix The value to prepend to the string.
96
     * @param string $suffix The value to append to the string.
97
     *
98
     * @return string
99
     *
100
     * @throws FilterException Thrown if $value cannot be casted to a string.
101
     */
102
    public static function concat($value, string $prefix = '', string $suffix = '') : string
103
    {
104
        self::enforceValueCanBeCastAsString($value);
105
        return "{$prefix}{$value}{$suffix}";
106
    }
107
108
    /**
109
     * @param mixed          $value       The raw input to run the filter against.
110
     * @param array|callable $words       The words to filter out.
111
     * @param string         $replacement The character to replace the words with.
112
     *
113
     * @return string|null
114
     *
115
     * @throws FilterException Thrown when a bad value is encountered.
116
     */
117
    public static function redact(
118
        $value,
119
        $words,
120
        string $replacement = ''
121
    ) {
122
        if ($value === null || $value === '') {
123
            return $value;
124
        }
125
126
        $stringValue = self::filter($value);
127
        if (is_callable($words)) {
128
            $words = $words();
129
        }
130
131
        if (is_array($words) === false) {
132
            throw new FilterException("Words was not an array or a callable that returns an array");
133
        }
134
135
        return self::replaceWordsWithReplacementString($stringValue, $words, $replacement);
0 ignored issues
show
Bug introduced by
It seems like $stringValue can also be of type null; however, parameter $value of TraderInteractive\Filter...WithReplacementString() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

135
        return self::replaceWordsWithReplacementString(/** @scrutinizer ignore-type */ $stringValue, $words, $replacement);
Loading history...
136
    }
137
138
    /**
139
     * Strip HTML and PHP tags from a string. Unlike the strip_tags function this method will return null if a null
140
     * value is given. The native php function will return an empty string.
141
     *
142
     * @param string|null $value The input string
143
     *
144
     * @return string|null
145
     */
146
    public static function stripTags(string $value = null)
147
    {
148
        if ($value === null) {
149
            return null;
150
        }
151
152
        return strip_tags($value);
153
    }
154
155
    private static function validateMinimumLength(int $minLength)
156
    {
157
        if ($minLength < 0) {
158
            throw new \InvalidArgumentException('$minLength was not a positive integer value');
159
        }
160
    }
161
162
    private static function validateMaximumLength(int $maxLength)
163
    {
164
        if ($maxLength < 0) {
165
            throw new \InvalidArgumentException('$maxLength was not a positive integer value');
166
        }
167
    }
168
169
    private static function validateStringLength(string $value = null, int $minLength, int $maxLength)
170
    {
171
        $valueLength = strlen($value);
172
        if ($valueLength < $minLength || $valueLength > $maxLength) {
173
            $format = "Value '%s' with length '%d' is less than '%d' or greater than '%d'";
174
            throw new FilterException(
175
                sprintf($format, $value, $valueLength, $minLength, $maxLength)
176
            );
177
        }
178
    }
179
180
    private static function valueIsNullAndValid(bool $allowNull, $value = null) : bool
181
    {
182
        if ($allowNull === false && $value === null) {
183
            throw new FilterException('Value failed filtering, $allowNull is set to false');
184
        }
185
186
        return $allowNull === true && $value === null;
187
    }
188
189
    private static function validateIfObjectIsAString($value)
190
    {
191
        if (!is_string($value)) {
192
            throw new FilterException("Value '" . var_export($value, true) . "' is not a string");
193
        }
194
    }
195
196
    private static function enforceValueCanBeCastAsString($value)
197
    {
198
        try {
199
            $value = (
200
                function (string $str) : string {
201
                    return $str;
202
                }
203
            )($value);
204
        } catch (TypeError $te) {
205
            throw new FilterException(sprintf("Value '%s' is not a string", var_export($value, true)));
206
        }
207
208
        return $value;
209
    }
210
211
    private static function replaceWordsWithReplacementString(string $value, array $words, string $replacement) : string
212
    {
213
        $matchingWords = self::getMatchingWords($words, $value);
214
        if (count($matchingWords) === 0) {
215
            return $value;
216
        }
217
218
        $replacements = self::generateReplacementsMap($matchingWords, $replacement);
219
220
        return str_ireplace($matchingWords, $replacements, $value);
221
    }
222
223
    private static function getMatchingWords(array $words, string $value) : array
224
    {
225
        $matchingWords = [];
226
        foreach ($words as $word) {
227
            $escapedWord = preg_quote($word, '/');
228
            $caseInsensitiveWordPattern = "/\b{$escapedWord}\b/i";
229
            if (preg_match($caseInsensitiveWordPattern, $value)) {
230
                $matchingWords[] = $word;
231
            }
232
        }
233
234
        return $matchingWords;
235
    }
236
237
    private static function generateReplacementsMap(array $words, string $replacement) : array
238
    {
239
        $replacement = mb_substr($replacement, 0, 1);
240
241
        return array_map(
242
            function ($word) use ($replacement) {
243
                if ($replacement === '') {
244
                    return '';
245
                }
246
247
                return str_repeat($replacement, strlen($word));
248
            },
249
            $words
250
        );
251
    }
252
}
253