Completed
Pull Request — master (#1)
by
unknown
04:03
created

Strings::valueIsNullAndValid()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 3
nc 3
nop 2
dl 0
loc 7
rs 9.2
c 0
b 0
f 0
1
<?php
2
3
namespace TraderInteractive\Filter;
4
5
use TraderInteractive\Exceptions\FilterException;
6
7
/**
8
 * A collection of filters for strings.
9
 */
10
final class Strings
11
{
12
    /**
13
     * Filter a string.
14
     *
15
     * Verify that the passed in value  is a string.  By default, nulls are not allowed, and the length is restricted
16
     * between 1 and PHP_INT_MAX.  These parameters can be overwritten for custom behavior.
17
     *
18
     * The return value is the string, as expected by the \TraderInteractive\Filterer class.
19
     *
20
     * @param mixed $value The value to filter.
21
     * @param bool $allowNull True to allow nulls through, and false (default) if nulls should not be allowed.
22
     * @param int $minLength Minimum length to allow for $value.
23
     * @param int $maxLength Maximum length to allow for $value.
24
     * @return string|null The passed in $value.
25
     *
26
     * @throws FilterException if the value did not pass validation.
27
     * @throws \InvalidArgumentException if one of the parameters was not correctly typed.
28
     */
29
    public static function filter(
30
        $value = null,
31
        bool $allowNull = false,
32
        int $minLength = 1,
33
        int $maxLength = PHP_INT_MAX
34
    ) {
35
        self::validateMinimumLength($minLength);
36
        self::validateMaximumLength($maxLength);
37
38
        if (self::valueIsNullAndValid($allowNull, $value)) {
39
            return null;
40
        }
41
42
        self::checkIfScalarAndConvert($value);
43
        self::checkIfObjectAndConvert($value);
44
        self::validateIfObjectIsAString($value);
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(string $value, string $delimiter = ',')
62
    {
63
        if (empty($delimiter)) {
64
            throw new \InvalidArgumentException(
65
                "Delimiter '" . var_export($delimiter, true) . "' is not a non-empty string"
66
            );
67
        }
68
69
        return explode($delimiter, $value);
70
    }
71
72
    private static function validateMinimumLength(int $minLength)
73
    {
74
        if ($minLength < 0) {
75
            throw new \InvalidArgumentException('$minLength was not a positive integer value');
76
        }
77
    }
78
79
    private static function validateMaximumLength(int $maxLength)
80
    {
81
        if ($maxLength < 0) {
82
            throw new \InvalidArgumentException('$maxLength was not a positive integer value');
83
        }
84
    }
85
86
    private static function validateStringLength(string $value = null, int $minLength, int $maxLength)
87
    {
88
        $valueLength = strlen($value);
89
        if ($valueLength < $minLength || $valueLength > $maxLength) {
90
            throw new FilterException(
91
                sprintf(
92
                    "Value '%s' with length '%d' is less than '%d' or greater than '%d'",
93
                    $value,
94
                    $valueLength,
95
                    $minLength,
96
                    $maxLength
97
                )
98
            );
99
        }
100
    }
101
102
    private static function valueIsNullAndValid(bool $allowNull, $value = null) : bool
103
    {
104
        if ($allowNull === false && $value === null) {
105
            throw new FilterException('Value failed filtering, $allowNull is set to false');
106
        }
107
108
        return $allowNull === true && $value === null;
109
    }
110
111
    private static function checkIfScalarAndConvert(&$value)
112
    {
113
        if (is_scalar($value)) {
114
            $value = (string)$value;
115
        }
116
    }
117
118
    private static function checkIfObjectAndConvert(&$value)
119
    {
120
        if (is_object($value) && method_exists($value, '__toString')) {
121
            $value = (string)$value;
122
        }
123
    }
124
125
    private static function validateIfObjectIsAString($value)
126
    {
127
        if (!is_string($value)) {
128
            throw new FilterException("Value '" . var_export($value, true) . "' is not a string");
129
        }
130
    }
131
}
132