Completed
Push — master ( 216b73...ba0c65 )
by Florent
03:23
created

StringUtil::str_pad()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 1
Metric Value
c 1
b 1
f 1
dl 0
loc 4
rs 10
cc 2
eloc 2
nc 2
nop 4
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($size);
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 getStringLength($string)
42
    {
43
        return function_exists('mb_strlen') ? mb_strlen($string, '8bit') : strlen($string);
44
    }
45
46
    /**
47
     * @param string   $string
48
     * @param int      $start
49
     * @param null|int $length
50
     *
51
     * @return string
52
     */
53
    public static function getSubString($string, $start, $length = null)
54
    {
55
        return function_exists('mb_substr') ? mb_substr($string, $start, $length, '8bit') : substr($string, $start, $length);
56
    }
57
58
    /**
59
     * @param string      $input
60
     * @param int         $pad_length
61
     * @param null|string $pad_string
62
     * @param null|int    $pad_style
63
     *
64
     * @return string
65
     */
66
    public static function addPadding($input, $pad_length, $pad_string = null, $pad_style = null)
67
    {
68
        return function_exists('mb_strlen') ? self::addPaddingMultiBytes($input, $pad_length, $pad_string, $pad_style) : str_pad($input, $pad_length, $pad_string, $pad_style);
69
    }
70
71
    /**
72
     * @param string      $input
73
     * @param int         $pad_length
74
     * @param null|string $pad_string
75
     * @param null|int    $pad_style
76
     *
77
     * @return string
78
     */
79
    private static function addPaddingMultiBytes($input, $pad_length, $pad_string = null, $pad_style = null)
80
    {
81
        return str_pad($input, strlen($input) - mb_strlen($input, '8bit') + $pad_length, $pad_string, $pad_style);
82
    }
83
}
84