Passed
Branch dev (72fba1)
by Michael
05:23
created

AdminPageFramework_Utility_String   A

Complexity

Total Complexity 36

Size/Duplication

Total Lines 253
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 36
eloc 65
dl 0
loc 253
rs 9.52
c 0
b 0
f 0

15 Methods

Rating   Name   Duplication   Size   Complexity  
A getAsString() 0 13 4
A getLengthSanitized() 0 5 3
A getCSSMinified() 0 5 1
A getStringLength() 0 4 2
A sanitizeString() 0 4 2
A getSuffixRemoved() 0 4 2
A hasSlash() 0 3 1
A hasPrefix() 0 2 1
A sanitizeSlug() 0 4 2
A hasSuffix() 0 7 2
A getNumberFixed() 0 12 6
A getPrefixRemoved() 0 4 2
A getReadableBytes() 0 7 1
A fixNumber() 0 2 1
A getNumberOfReadableSize() 0 16 6
1
<?php
2
/**
3
 * Admin Page Framework
4
 *
5
 * http://admin-page-framework.michaeluno.jp/
6
 * Copyright (c) 2013-2021, Michael Uno; Licensed MIT
7
 *
8
 */
9
10
/**
11
 * Provides utility methods dealing with strings which do not use WordPress functions.
12
 *
13
 * @since       2.0.0
14
 * @package     AdminPageFramework/Utility
15
 * @internal
16
 */
17
abstract class AdminPageFramework_Utility_String extends AdminPageFramework_Utility_VariableType {
18
19
    /**
20
     * Get a value as a string.
21
     *
22
     * This is used when dealing with a function that returns mixed value types and wanting a string value, for example to concatenate strings.
23
     *
24
     * @param  mixed  $mValue
25
     * @return string
26
     * @since  3.9.0
27
     */
28
    static public function getAsString( $mValue ) {
29
        if ( is_string( $mValue ) ) {
30
            return $mValue;
31
        }
32
        if ( is_scalar( $mValue ) ) {
33
            return ( string ) $mValue;
34
        }
35
        // if null or false,
36
        if ( empty( $mValue ) ) {
37
            return '';
38
        }
39
        // Convert it to string
40
        return ( string ) $mValue;
41
    }
42
43
    /**
44
     * Returns the width for HTML attributes.
45
     *
46
     * When a value may be a number with a unit like, '100%', it returns the value itself.
47
     * When a value misses a unit like '60', it returns with the unit such as '60%'.
48
     *
49
     * ```
50
     * 0        -> '0px'
51
     * '0'      -> '0px'
52
     * null     -> '0px'
53
     * ''       -> '0px'
54
     * false    -> '0px'
55
     * ```
56
     *
57
     * @since       3.1.1
58
     * @since       3.8.0   Renamed from `sanitizeLength()`.
59
     * @since       3.8.4   When non-true value is passed, `0px` will be returned.
60
     * @return      string
61
     */
62
    static public function getLengthSanitized( $sLength, $sUnit='px' ) {
63
        $sLength = $sLength ? $sLength : 0;
64
        return is_numeric( $sLength )
65
            ? $sLength . $sUnit
66
            : $sLength;
67
    }
68
69
    /**
70
     * Converts non-alphabetic characters to underscore.
71
     *
72
     * @since       2.0.0
73
     * @return      string|null     The sanitized string.
74
     * @todo        Change the method name as it does not tell for what it will sanitized.
75
     * @todo        Examine why null needs to be returned.
76
     */
77
    public static function sanitizeSlug( $sSlug ) {
78
        return is_null( $sSlug )
79
            ? null
80
            : preg_replace( '/[^a-zA-Z0-9_\x7f-\xff]/', '_', trim( $sSlug ) );
81
    }
82
83
    /**
84
     * Converts non-alphabetic characters to underscore except hyphen(dash).
85
     *
86
     * @since       2.0.0
87
     * @return      string|null      The sanitized string.
88
     * @todo        Change the method name as it does not tell for what it will sanitized.
89
     * @todo        Examine why null needs to be returned.
90
     */
91
    public static function sanitizeString( $sString ) {
92
        return is_null( $sString )
93
            ? null
94
            : preg_replace( '/[^a-zA-Z0-9_\x7f-\xff\-]/', '_', $sString );
95
    }
96
97
    /**
98
     * Checks if the passed value is a number and sets it to the default if not.
99
     *
100
     * This is useful for form data validation. If it is a number and exceeds a set maximum number,
101
     * it sets it to the maximum value. If it is a number and is below the minimum number, it sets to the minimum value.
102
     * Set a blank value for no limit.
103
     *
104
     * @since       3.8.11      Renamed from `fixNumber()`.
105
     * @return      string|integer      A numeric value will be returned.
106
     */
107
    static public function getNumberFixed( $nToFix, $nDefault, $nMin='', $nMax='' ) {
108
109
        if ( ! is_numeric( trim( $nToFix ) ) ) {
110
            return $nDefault;
111
        }
112
        if ( $nMin !== '' && $nToFix < $nMin ) {
113
            return $nMin;
114
        }
115
        if ( $nMax !== '' && $nToFix > $nMax ) {
116
            return $nMax;
117
        }
118
        return $nToFix;
119
120
    }
121
        /**
122
         * An alias of `getNumberFixed()`.
123
         * @since       2.0.0
124
         * @return      string|integer      A numeric value will be returned.
125
         * @deprecated  3.8.11
126
         */
127
        static public function fixNumber( $nToFix, $nDefault, $nMin='', $nMax='' ) {
128
            return self::getNumberFixed( $nToFix, $nDefault, $nMin, $nMax );
129
        }
130
131
    /**
132
     * Compresses CSS rules.
133
     *
134
     * @since       3.0.0
135
     * @since       3.7.10      Changed the name from `minifyCSS()`.
136
     * @return      string
137
     */
138
    static public function getCSSMinified( $sCSSRules ) {
139
        return str_replace(
140
            array( "\r\n", "\r", "\n", "\t", '  ', '    ', '    '),  // remove line breaks, tab, and white sspaces.
141
            '',
142
            preg_replace( '!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $sCSSRules ) // remove comments
143
        );
144
    }
145
146
    /**
147
     * Returns the given string length.
148
     * @since       3.3.0
149
     * @return      integer|null        Null if an array is given.
150
     */
151
    static public function getStringLength( $sString ) {
152
        return function_exists( 'mb_strlen' )
153
            ? mb_strlen( $sString )
154
            : strlen( $sString );
155
    }
156
157
    /**
158
     * Returns a number from the given human readable size representation.
159
     *
160
     * For example,
161
     * ```
162
     * 20M   -> 20971520
163
     * 324k  -> 331776
164
     * ```
165
     *
166
     * Only a single character for the unit is allowed. So ~MB will not be recognized and only the first letter will be left.
167
     * ```
168
     * 20MB  -> '20M'
169
     * 42KB  -> '42K'
170
     * ```
171
     *
172
     * @since       3.4.6
173
     * @return      string|integer
174
     */
175
    static public function getNumberOfReadableSize( $nSize ) {
176
177
        $_nReturn     = substr( $nSize, 0, -1 );
178
        switch( strtoupper( substr( $nSize, -1 ) ) ) {
179
            case 'P':
180
                $_nReturn *= 1024;
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment if this fall-through is intended.
Loading history...
181
            case 'T':
182
                $_nReturn *= 1024;
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment if this fall-through is intended.
Loading history...
183
            case 'G':
184
                $_nReturn *= 1024;
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment if this fall-through is intended.
Loading history...
185
            case 'M':
186
                $_nReturn *= 1024;
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment if this fall-through is intended.
Loading history...
187
            case 'K':
188
                $_nReturn *= 1024;
189
        }
190
        return $_nReturn;
191
192
    }
193
194
    /**
195
     * Returns a human readable size from the given byte number.
196
     * @param  integer $iRoundPrecision
197
     * @param  integer|float $nBytes
198
     * @since       3.4.6
199
     * @since       3.8.26 Added the `$iRoundPrecision` parameter.
200
     * @return      string
201
     */
202
    static public function getReadableBytes( $nBytes, $iRoundPrecision=2 ) {
203
        $_aUnits = array( 0 => 'B', 1 => 'kB', 2 => 'MB', 3 => 'GB' );
204
        $_nLog   = log( $nBytes, 1024 );
205
        $_iPower = ( int ) $_nLog;
206
        $_ifSize = pow( 1024, $_nLog - $_iPower );
207
        $_ifSize = round( $_ifSize, $iRoundPrecision );
208
        return $_ifSize . $_aUnits[ $_iPower ];
209
    }
210
211
    /**
212
     * Trims a starting sub-string if exists.
213
     * @return      string
214
     * @since       3.7.2
215
     */
216
    static public function getPrefixRemoved( $sString, $sPrefix ) {
217
        return self::hasPrefix( $sPrefix, $sString )
218
            ? substr( $sString, strlen( $sPrefix ) )
219
            : $sString;
220
    }
221
    /**
222
     * Trims a trailing sub-string if exists.
223
     * @return      string
224
     * @since       3.7.2
225
     */
226
    static public function getSuffixRemoved( $sString, $sSuffix ) {
227
        return self::hasSuffix( $sSuffix, $sString )
228
            ? substr( $sString, 0, strlen( $sSuffix ) * - 1 )
229
            : $sString;
230
    }
231
232
    /**
233
     * Checks if the given string has a certain prefix.
234
     *
235
     * Used mainly in the __call() method to determine the called undefined method name has a certain prefix.
236
     *
237
     * @since       3.5.3
238
     * @return      boolean     True if it has the given prefix; otherwise, false.
239
     */
240
    static public function hasPrefix( $sNeedle, $sHaystack ) {
241
        return ( string ) $sNeedle === substr( $sHaystack, 0, strlen( ( string ) $sNeedle ) );
242
    }
243
244
    /**
245
     * Checks if the given string has a certain suffix.
246
     *
247
     * Used to check file base name etc.
248
     *
249
     * @since   3.5.4
250
     * @return  boolean
251
     */
252
    static public function hasSuffix( $sNeedle, $sHaystack ) {
253
254
        $_iLength = strlen( ( string ) $sNeedle );
255
        if ( 0 === $_iLength ) {
256
            return true;
257
        }
258
        return substr( $sHaystack, - $_iLength ) === $sNeedle;
259
260
    }
261
262
    /**
263
     * Checks if a given string has back/forward slashes.
264
     * @param string $sString
265
     * @return boolean
266
     */
267
    static public function hasSlash( $sString ) {
268
        $sString = str_replace( '\\', '/', $sString );
269
        return ( false !== strpos( $sString, '/' ) );
270
    }
271
272
}
273