Completed
Pull Request — master (#118)
by thomas
03:35
created

OutputsNormalizer::normalize()   C

Complexity

Conditions 17
Paths 84

Size

Total Lines 52

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 306

Importance

Changes 0
Metric Value
cc 17
nc 84
nop 2
dl 0
loc 52
ccs 0
cts 45
cp 0
crap 306
rs 5.2166
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Blocktrail\SDK;
4
5
use BitWasp\Bitcoin\Bitcoin;
6
use BitWasp\Bitcoin\Network\Network;
7
use BitWasp\Bitcoin\Network\NetworkInterface;
8
use BitWasp\Bitcoin\Script\Opcodes;
9
use BitWasp\Bitcoin\Script\ScriptFactory;
10
use BitWasp\Buffertools\Buffer;
11
use Blocktrail\SDK\Address\AddressReaderBase;
12
use Blocktrail\SDK\Exceptions\BlocktrailSDKException;
13
14
class OutputsNormalizer
15
{
16
    /**
17
     * @var AddressReaderBase
18
     */
19
    private $reader;
20
21
    /**
22
     * OutputsNormalizer constructor.
23
     * @param AddressReaderBase $reader
24
     */
25
    public function __construct(AddressReaderBase $reader) {
26
        $this->reader = $reader;
27
    }
28
29
    /**
30
     * @param array $output
31
     * @return array
32
     * @throws BlocktrailSDKException
33
     */
34
    protected function readArrayFormat(array $output, Network $network) {
35
        if (array_key_exists("scriptPubKey", $output) && array_key_exists("value", $output)) {
36
            return [
37
                "scriptPubKey" => $output['scriptPubKey'],
38
                "value" => $output['value'],
39
            ];
40
        } else if (array_key_exists("address", $output) && array_key_exists("value", $output)) {
41
            return $this->parseAddressOutput($output['address'], $output['value'], $network);
42
        } else {
43
            $keys = array_keys($output);
44
            if (count($keys) === 2 && count($output) === 2 && $keys[0] === 0 && $keys[1] === 1) {
45
                return $this->parseAddressOutput($output[0], $output[1], $network);
46
            } else {
47
                throw new BlocktrailSDKException("Invalid transaction output for numerically indexed list");
48
            }
49
        }
50
    }
51
52
    /**
53
     * @param $address
54
     * @param $value
55
     * @return array
56
     */
57
    private function parseAddressOutput($address, $value, $network) {
58
        if ($address === "opreturn") {
59
            $data = new Buffer($value);
60
            $scriptPubKey = ScriptFactory::sequence([Opcodes::OP_RETURN, $data]);
61
            return [
62
                "value" => 0,
63
                "scriptPubKey" => $scriptPubKey,
64
            ];
65
        }
66
67
        $object = $this->reader->fromString($address, $network);
68
        return [
69
            "value" => $value,
70
            "scriptPubKey" => $object->getScriptPubKey(),
71
        ];
72
    }
73
74
    /**
75
     * @param array $outputs
76
     * @param NetworkInterface|null $network
77
     * @return array
78
     * @throws BlocktrailSDKException
79
     */
80
    public function normalize(array $outputs, NetworkInterface $network = null) {
81
        $network = $network ?: Bitcoin::getNetwork();
82
        if (empty($outputs)) {
83
            return [];
84
        }
85
86
        $keys = array_keys($outputs);
87
        $newOutputs = [];
88
        if (is_int($keys[0])) {
89
            foreach ($outputs as $i => $output) {
90
                if (!is_int($i)) {
91
                    throw new BlocktrailSDKException("Encountered invalid index while traversing numerically indexed list");
92
                }
93
                if (!is_array($output)) {
94
                    throw new BlocktrailSDKException("Encountered invalid output while traversing numerically indexed list");
95
                }
96
                $newOutputs[] = $this->readArrayFormat($output, $network);
0 ignored issues
show
Compatibility introduced by
$network of type object<BitWasp\Bitcoin\Network\NetworkInterface> is not a sub-type of object<BitWasp\Bitcoin\Network\Network>. It seems like you assume a concrete implementation of the interface BitWasp\Bitcoin\Network\NetworkInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
97
            }
98
        } else if (is_string($keys[0])) {
99
            foreach ($outputs as $address => $value) {
100
                if (!is_string($address)) {
101
                    throw new BlocktrailSDKException("Encountered invalid address while traversing address keyed list..");
102
                }
103
104
                $newOutputs[] = $this->parseAddressOutput($address, $value, $network);
105
            }
106
        }
107
108
        foreach ($newOutputs as &$newOutput) {
109
            if (fmod($newOutput['value'], 1)) {
110
                throw new BlocktrailSDKException("Value should be in Satoshis");
111
            }
112
113
            if (is_string($newOutput['scriptPubKey'])) {
114
                $newOutput['scriptPubKey'] = ScriptFactory::fromHex($newOutput['scriptPubKey']);
115
            }
116
117
            if (strlen($newOutput['scriptPubKey']->getBinary()) < 1) {
118
                throw new BlocktrailSDKException("Script cannot be empty");
119
            }
120
121
            if ($newOutput['scriptPubKey']->getBinary()[0] !== "\x6a") {
122
                if (!$newOutput['value']) {
123
                    throw new BlocktrailSDKException("Values should be non zero");
124
                } else if ($newOutput['value'] < Blocktrail::DUST) {
125
                    throw new BlocktrailSDKException("Values should be more than dust (" . Blocktrail::DUST . ")");
126
                }
127
            }
128
        }
129
130
        return $newOutputs;
131
    }
132
}
133