OpenSsl::generate()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 11
rs 9.4285
cc 2
eloc 6
nc 2
nop 1
1
<?php
2
/**
3
 * Caridea
4
 *
5
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
6
 * use this file except in compliance with the License. You may obtain a copy of
7
 * the License at
8
 *
9
 * http://www.apache.org/licenses/LICENSE-2.0
10
 *
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14
 * License for the specific language governing permissions and limitations under
15
 * the License.
16
 *
17
 * @copyright 2015-2016 LibreWorks contributors
18
 * @license   http://opensource.org/licenses/Apache-2.0 Apache 2.0 License
19
 */
20
namespace Caridea\Random;
21
22
/**
23
 * A provider of cryptographically-strong random bytes using OpenSSL.
24
 *
25
 * @copyright 2015-2016 LibreWorks contributors
26
 * @license   http://opensource.org/licenses/Apache-2.0 Apache 2.0 License
27
 */
28
class OpenSsl implements Generator
29
{
30
    public function generate($length)
31
    {
32
        $bytes = '';
33
        $length = (int)$length;
34
        
35
        if (self::isAvailable()) {
36
            $bytes = openssl_random_pseudo_bytes($length);
37
        }
38
        
39
        return str_pad($bytes, $length, chr(0));
40
    }
41
    
42
    /**
43
     * Determines whether this provider can be run (e.g. all needed PHP extensions are available).
44
     *
45
     * @return bool Whether this provider is available
46
     */
47
    public static function isAvailable()
48
    {
49
        return function_exists('openssl_random_pseudo_bytes');
50
    }
51
}
52