aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/stephenhill/base58/src/Base58.php
blob: 75a2e0de46b2e9ccaf901323147c8962521e3947 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php

namespace StephenHill;

use InvalidArgumentException;

/**
 * @package      StephenHill\Base58
 * @author       Stephen Hill <stephen@gatekiller.co.uk>
 * @copyright    2014 Stephen Hill <stephen@gatekiller.co.uk>
 * @license      http://www.opensource.org/licenses/MIT    The MIT License
 * @link         https://github.com/stephen-hill/base58php
 * @since        Release v1.0.0
 */
class Base58
{
    /**
     * @var StephenHill\ServiceInterface;
     * @since v1.1.0
     */
    protected $service;

    /**
     * Constructor
     *
     * @param string           $alphabet optional
     * @param ServiceInterface $service  optional
     * @since v1.0.0
     * @since v1.1.0 Added the optional $service argument.
     */
    public function __construct(
        $alphabet = null,
        ServiceInterface $service = null
    ) {
        // Handle null alphabet
        if (is_null($alphabet) === true) {
            $alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
        }

        // Type validation
        if (is_string($alphabet) === false) {
            throw new InvalidArgumentException('Argument $alphabet must be a string.');
        }

        // The alphabet must contain 58 characters
        if (strlen($alphabet) !== 58) {
            throw new InvalidArgumentException('Argument $alphabet must contain 58 characters.');
        }

        // Provide a default service if one isn't injected
        if ($service === null) {
            // Check for GMP support first
            if (function_exists('\gmp_init') === true) {
                $service = new GMPService($alphabet);
            }
            else if (function_exists('\bcmul') === true) {
                $service = new BCMathService($alphabet);
            }
            else {
                throw new \Exception('Please install the BC Math or GMP extension.');
            }
        }

        $this->service = $service;
    }

    /**
     * Encode a string into base58.
     *
     * @param  string $string The string you wish to encode.
     * @since v1.0.0
     * @return string The Base58 encoded string.
     */
    public function encode($string)
    {
        return $this->service->encode($string);
    }

    /**
     * Decode base58 into a PHP string.
     *
     * @param  string $base58 The base58 encoded string.
     * @since v1.0.0
     * @return string Returns the decoded string.
     */
    public function decode($base58)
    {
        return $this->service->decode($base58);
    }
}