Completed
Push — master ( c7240b...3ac908 )
by Chris
03:04 queued 51s
created

utils::get_value_multiple_sources()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 3
nop 3
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 52 and the first side effect is on line 13.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/*
3
Plugin Name: Vendi Shared Utility Class
4
Description: Helper class shared across all Vendi-controlled properties.
5
Version: 3.0.4
6
Author: Vendi
7
*/
8
9
namespace Vendi\Shared;
10
11
if( class_exists( '\Vendi\Shared\utils' ) )
12
{
13
    return;
14
}
15
16
/**
17
 * Utility class generally for HTTP.
18
 *
19
 * NOTE: Do not modify any methods in this class ever. You
20
 * can add new methods as needed but there is a lot of code
21
 * the depends on this functioning in a specific fashion and
22
 * since this is a shared class you are not guarenteed to have
23
 * this specific class actually loaded.
24
 *
25
 * To clarify the above, this class is intended to be used by
26
 * multiple plugins and there is no guarantee of load order.
27
 * If you add a new method to this class you should grep the
28
 * server for other installs and add code to those, too, since
29
 * you don't know if your code will load first.
30
 *
31
 * Any additional methods to this class MUST work without fail
32
 * and can have zero dependencies upon other code.
33
 *
34
 * History:
35
 *
36
 * 3.0.4 - Only trim() if the value is a string.
37
 *
38
 * 2.1.0 - Allow setting custom POST/GET/COOKIE/SERVER on
39
 *         static fields of class. If set they will be used
40
 *         in place of the global $_ XYZ values. Also added
41
 *         reset_all_custom_arrays() to erase these values.
42
 *
43
 *         These changes should be 100% backwards compatible.
44
 *
45
 * 2.0.1 - Added unparse_url()
46
 *
47
 * 2.0.0 - Rewrite of previous code into this namesapce
48
 *
49
 * @version  2.1.0
50
 */
51
52
class utils
53
{
54
    public static $CUSTOM_POST = null;
55
56
    public static $CUSTOM_GET = null;
57
58
    public static $CUSTOM_COOKIE = null;
59
60
    public static $CUSTOM_SERVER = null;
61
62
    public static function reset_all_custom_arrays()
63
    {
64
        self::$CUSTOM_POST = null;
65
        self::$CUSTOM_GET = null;
66
        self::$CUSTOM_COOKIE = null;
67
        self::$CUSTOM_SERVER = null;
68
    }
69
70
    /**
71
     * Get the value from the HTTP POST return the $default_value.
72
     * @param  string        $key           The form field's name to search in the $_POST array for.
73
     * @param  mixed         $default_value Optional. If the $key cannot be found the value to return. Default null.
74
     * @return mixed                        The value of the HTTP POST for the given $key or the $default.
75
     */
76
    public static function get_post_value( $key, $default_value = '' )
77
    {
78
        return self::get_request_value( 'POST', $key, $default_value );
79
    }
80
81
    /**
82
     * Get the value from the HTTP GET return the $default_value.
83
     * @param  string        $key           The form field's name to search in the $_GET array for.
84
     * @param  mixed         $default_value Optional. If the $key cannot be found the value to return. Default null.
85
     * @return mixed                        The value of the HTTP GET for the given $key or the $default.
86
     */
87
    public static function get_get_value( $key, $default_value = '' )
88
    {
89
        return self::get_request_value( 'GET', $key, $default_value );
90
    }
91
92
    /**
93
     * Get the value from the HTTP COOKIE return the $default_value.
94
     * @param  string        $key           The form field's name to search in the $_COOKIE array for.
95
     * @param  mixed         $default_value Optional. If the $key cannot be found the value to return. Default null.
96
     * @return mixed                        The value of the HTTP COOKIE for the given $key or the $default.
97
     */
98
    public static function get_cookie_value( $key, $default_value = '' )
99
    {
100
        return self::get_request_value( 'COOKIE', $key, $default_value );
101
    }
102
103
    /**
104
     * Get the value from the HTTP SERVER return the $default_value.
105
     * @param  string        $key           The form field's name to search in the $_SERVER array for.
106
     * @param  mixed         $default_value Optional. If the $key cannot be found the value to return. Default null.
107
     * @return mixed                        The value of the HTTP SERVER for the given $key or the $default.
108
     */
109
    public static function get_server_value( $key, $default_value = '' )
110
    {
111
        return self::get_request_value( 'SERVER', $key, $default_value );
112
    }
113
114
    /**
115
     * Get the first non-null value from the supplied list of sources.
116
     *
117
     * @param  string        $key           The form field's name to search in the each source array for.
118
     * @param  array         $sources       Array of sources (GET, POST, SERVER, or COOKIE) in the order to check.
119
     * @param  mixed         $default_value Optional. If the $key cannot be found the value to return. Default null.
120
     * @return mixed                        The value of the source for the given $key or the $default.
121
     */
122
    public static function get_value_multiple_sources( $key, array $sources, $default_value = null )
123
    {
124
        foreach( $sources as $source )
125
        {
126
            $value = self::get_request_value( $source, $key, null );
127
            if( null !== $value )
128
            {
129
                return $value;
130
            }
131
        }
132
133
        return $default_value;
134
    }
135
136
    /**
137
     * Get the value from the HTTP POST as an integer or return the $default_value.
138
     * @param  string        $key           The form field's name to search in the $_POST array for.
139
     * @param  integer|mixed $default_value Optional. If the $key cannot be found the value to return. Default null.
140
     * @return integer|mixed                The value of the HTTP POST for the given $key or the $default.
141
     */
142
    public static function get_post_value_int( $key, $default_value = null )
143
    {
144
        return self::get_request_value_int( 'POST', $key, $default_value );
145
    }
146
147
    /**
148
     * Get the value from the HTTP GET as an integer or return the $default_value.
149
     * @param  string        $key           The form field's name to search in the $_GET array for.
150
     * @param  integer|mixed $default_value Optional. If the $key cannot be found the value to return. Default null.
151
     * @return integer|mixed                The value of the HTTP GET for the given $key or the $default.
152
     */
153
    public static function get_get_value_int( $key, $default_value = null )
154
    {
155
        return self::get_request_value_int( 'GET', $key, $default_value );
156
    }
157
158
    /**
159
     * Get the value from the HTTP COOKIE as an integer or return the $default_value.
160
     * @param  string        $key           The form field's name to search in the $_COOKIE array for.
161
     * @param  integer|mixed $default_value Optional. If the $key cannot be found the value to return. Default null.
162
     * @return integer|mixed                The value of the HTTP COOKIE for the given $key or the $default.
163
     */
164
    public static function get_cookie_value_int( $key, $default_value = null )
165
    {
166
        return self::get_request_value_int( 'COOKIE', $key, $default_value );
167
    }
168
169
    /**
170
     * Get the value from the HTTP SERVER as an integer or return the $default_value.
171
     * @param  string        $key           The form field's name to search in the $_SERVER array for.
172
     * @param  integer|mixed $default_value Optional. If the $key cannot be found the value to return. Default null.
173
     * @return integer|mixed                The value of the HTTP SERVER for the given $key or the $default.
174
     */
175
    public static function get_server_value_int( $key, $default_value = null )
176
    {
177
        return self::get_request_value_int( 'SERVER', $key, $default_value );
178
    }
179
180
    public static function get_request_value_int( $request_method, $key, $default_value = null )
181
    {
182
        $value = self::get_request_value( $request_method, $key, null );
183
        if( self::is_integer_like( $value ) )
184
        {
185
            return (int)$value;
186
        }
187
188
        return $default_value;
189
    }
190
191
    public static function get_request_value( $request_method, $key, $default_value = null )
192
    {
193
        $request_obj = self::get_request_object( $request_method );
194
195
        if( null === $request_obj || ! is_array( $request_obj ) || ! array_key_exists( $key, $request_obj ) )
196
        {
197
            return $default_value;
198
        }
199
200
        $ret = $request_obj[ $key ];
201
202
        if( is_string( $ret ) )
203
        {
204
            $ret = trim( $ret );
205
        }
206
207
        return $ret;
208
    }
209
210
    public static function get_request_object( $request_method )
0 ignored issues
show
Coding Style introduced by
get_request_object uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
get_request_object uses the super-global variable $_POST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
get_request_object uses the super-global variable $_COOKIE which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
get_request_object uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
211
    {
212
        $obj = null;
0 ignored issues
show
Unused Code introduced by
$obj is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
213
        switch( $request_method )
214
        {
215
            case 'GET':
216
                if( is_array( self::$CUSTOM_GET ) )
217
                {
218
                    return self::$CUSTOM_GET;
219
                }
220
                return ( isset( $_GET ) && is_array( $_GET ) && count( $_GET ) > 0 ? $_GET : null );
221
222
            case 'POST':
223
                if( is_array( self::$CUSTOM_POST ) )
224
                {
225
                    return self::$CUSTOM_POST;
226
                }
227
                return ( isset( $_POST ) && is_array( $_POST ) && count( $_POST ) > 0 ? $_POST : null );
228
229
            case 'COOKIE':
230
                if( is_array( self::$CUSTOM_COOKIE ) )
231
                {
232
                    return self::$CUSTOM_COOKIE;
233
                }
234
                return ( isset( $_COOKIE ) && is_array( $_COOKIE ) && count( $_COOKIE ) > 0 ? $_COOKIE : null );
235
236
            case 'SERVER':
237
                if( is_array( self::$CUSTOM_SERVER ) )
238
                {
239
                    return self::$CUSTOM_SERVER;
240
                }
241
                return ( isset( $_SERVER ) && is_array( $_SERVER ) && count( $_SERVER ) > 0 ? $_SERVER : null );
242
243
            default:
244
                return null;
245
        }
246
    }
247
248
    /**
249
     * Test if we're in a certain type of HTTP request.
250
     *
251
     * @param  string  $method The server method to test for. Generally one of GET, POST, HEAD, PUT, DELETE.
252
     * @return boolean         Returns true if the REQUEST_METHOD server variable is set to the supplied $method, otherwise false.
253
     */
254
    public static function is_request_method( $method )
255
    {
256
        return $method === self::get_server_value( 'REQUEST_METHOD' );
257
    }
258
259
    /**
260
     * Check to see if we're in a post.
261
     *
262
     * Unit tests were failing because REQUEST_METHOD wasn't always being set. This should be used
263
     * for all POST checks.
264
     *
265
     * \Vendi\Forms\utils::is_post()
266
     *
267
     * @return boolean Returns true if the REQUEST_METHOD server variable is set to POST, otherwise false.
268
     */
269
    public static function is_post( )
270
    {
271
        return self::is_request_method( 'POST' );
272
    }
273
274
    /**
275
     * Test if the given $input can be converted to an int excluding booleans.
276
     *
277
     * \Vendi\Forms\utils::is_integer_like( value )
278
     *
279
     * @param  mixed  $input The value to test.
280
     * @return boolean       True if $input is an integer or a string that contains only digits possibly starting with a dash.
281
     */
282
    public static function is_integer_like( $input )
283
    {
284
        return
285
                is_int( $input )
286
                ||
287
                (
288
                    is_string( $input )
289
                    &&
290
                    preg_match( '/^-?([0-9])+$/', $input )
291
                );
292
    }
293
294
    public static function get_all_headers()
0 ignored issues
show
Coding Style introduced by
get_all_headers uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
295
    {
296
        $headers = array();
297
        foreach( array( '_SERVER', '_GET', '_POST', '_COOKIE', '_ENV' ) as $key )
298
        {
299
            if( array_key_exists( $key, $GLOBALS ) )
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
300
            {
301
302
            }
303
            $headers[ $key ] = $GLOBALS[ $key ];
304
        }
305
        return $headers;
306
    }
307
308
    /**
309
     * Convert the result of urlpieces back to a URL.
310
     *
311
     * @see  http://php.net/manual/en/function.parse-url.php#106731
312
     *
313
     * @param  array $parsed_url An array created by urlpieces.
314
     * @return string            A URL string.
315
     */
316
    public static function unparse_url( $parsed_url ) {
317
        //I don't know what you gave me so you can just have it back
318
        if( ! is_array( $parsed_url ) ) {
319
            return $parsed_url;
320
        }
321
        $scheme   = isset( $parsed_url['scheme'])    ?       $parsed_url['scheme'] . '://' : '';
322
        $host     = isset( $parsed_url['host'] )     ?       $parsed_url['host']           : '';
323
        $port     = isset( $parsed_url['port'] )     ? ':' . $parsed_url['port']           : '';
324
        $path     = isset( $parsed_url['path'] )     ?       $parsed_url['path']           : '';
325
        $query    = isset( $parsed_url['query'] )    ? '?' . $parsed_url['query']          : '';
326
        $fragment = isset( $parsed_url['fragment'] ) ? '#' . $parsed_url['fragment']       : '';
327
328
        //NOTE: user and pass were explicitly removed.
329
330
        return "$scheme$host$port$path$query$fragment";
331
    }
332
333
}
334