1<?php
2/**
3 * Copyright 2017 Facebook, Inc.
4 *
5 * You are hereby granted a non-exclusive, worldwide, royalty-free license to
6 * use, copy, modify, and distribute this software in source code or binary
7 * form for use in connection with the web services and APIs provided by
8 * Facebook.
9 *
10 * As with any software that integrates with the Facebook platform, your use
11 * of this software is subject to the Facebook Developer Principles and
12 * Policies [http://developers.facebook.com/policy/]. This copyright notice
13 * shall be included in all copies or substantial portions of the software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21 * DEALINGS IN THE SOFTWARE.
22 *
23 */
24namespace Facebook\PseudoRandomString;
25
26use Facebook\Exceptions\FacebookSDKException;
27
28class RandomBytesPseudoRandomStringGenerator implements PseudoRandomStringGeneratorInterface
29{
30    use PseudoRandomStringGeneratorTrait;
31
32    /**
33     * @const string The error message when generating the string fails.
34     */
35    const ERROR_MESSAGE = 'Unable to generate a cryptographically secure pseudo-random string from random_bytes(). ';
36
37    /**
38     * @throws FacebookSDKException
39     */
40    public function __construct()
41    {
42        if (!function_exists('random_bytes')) {
43            throw new FacebookSDKException(
44                static::ERROR_MESSAGE .
45                'The function random_bytes() does not exist.'
46            );
47        }
48    }
49
50    /**
51     * @inheritdoc
52     */
53    public function getPseudoRandomString($length)
54    {
55        $this->validateLength($length);
56
57        return $this->binToHex(random_bytes($length), $length);
58    }
59}
60