Completed
Branch dev (b11655)
by
unknown
03:58
created

getNumberFixed()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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