Completed
Push — master ( fcfd9c...110fa8 )
by Florent
02:56
created

StringUtil   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 5
Bugs 2 Features 1
Metric Value
wmc 11
c 5
b 2
f 1
lcom 0
cbo 0
dl 0
loc 44
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A generateRandomBytes() 0 11 4
A strlen() 0 4 2
A substr() 0 4 2
A str_pad() 0 4 2
A mb_pad_str() 0 4 1
1
<?php
2
3
/*
4
 * The MIT License (MIT)
5
 *
6
 * Copyright (c) 2014-2016 Spomky-Labs
7
 *
8
 * This software may be modified and distributed under the terms
9
 * of the MIT license.  See the LICENSE file for details.
10
 */
11
12
namespace Jose\Util;
13
14
/**
15
 * Class String.
16
 */
17
final class StringUtil
18
{
19
    /**
20
     * @param int $size
21
     * 
22
     * @return string
23
     */
24
    public static function generateRandomBytes($size)
25
    {
26
        if (function_exists('random_bytes')) {
27
            return random_bytes($size);
28
        } elseif (function_exists('openssl_random_pseudo_bytes')) {
29
            return openssl_random_pseudo_bytes($size);
30
        } elseif (function_exists('mcrypt_create_iv')) {
31
            return mcrypt_create_iv($length);
0 ignored issues
show
Bug introduced by
The variable $length does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
32
        }
33
        throw new \RuntimeException('Unable to create random bytes.');
34
    }
35
    
36
    /**
37
     * @param string $string
38
     * 
39
     * @return int
40
     */
41
    public static function strlen($string)
42
    {
43
        return function_exists('mb_strlen') ? mb_strlen($string, '8bit') : strlen($string);
44
    }
45
46
    public static function substr($string, $start, $length = null)
47
    {
48
        return function_exists('mb_substr') ? mb_substr($string, $start, $length, '8bit') : substr($string, $start, $length);
49
    }
50
51
    public static function str_pad($input, $pad_length, $pad_string = null, $pad_style = null)
52
    {
53
        return function_exists('mb_strlen') ? self::mb_pad_str($input, $pad_length, $pad_string, $pad_style) : str_pad($input, $pad_length, $pad_string, $pad_style);
54
    }
55
56
    private static function mb_pad_str($input, $pad_length, $pad_string = null, $pad_style = null)
57
    {
58
        return str_pad($input, strlen($input) - mb_strlen($input, '8bit') + $pad_length, $pad_string, $pad_style);
59
    }
60
}
61