Ethereum PHP
PHP interface to Ethereum JSON-RPC API.
EthS.php
Go to the documentation of this file.
1 <?php
2 
3 namespace Ethereum\DataType;
4 
6 
7 
13 class EthS extends EthBytes
14 {
22  public function validate($val, array $params)
23  {
24  $return = null;
25  // Decode
26  if ($this->hasHexPrefix($val)) {
27  // Hex encoded string.
28  $return = $this->hexToStr($val);
29  }
30  else {
31  $return = $val;
32  }
33 
34  // Validate.
35  if (is_string((string)$return) && $this->checkUtf8($return)) {
36  return $return;
37  }
38  else {
39  throw new \InvalidArgumentException('Can not decode value: ' . $val);
40  }
41  }
42 
43 
49  public static function cretateFromRLP($hexVal)
50  {
51  $rlpItem = Rlp::decode($hexVal);
52  return new EthS(self::ensureHexPrefix($rlpItem[0]->get()));
53  }
54 
61  public function rlpVal()
62  {
63  // @todo ???
64  return Rlp::encode($this->strToHex($this->value));
65  }
66 
70  public function hexVal()
71  {
72  return $this->ensureHexPrefix($this->strToHex($this->value));
73  }
74 
78  public function encodedHexVal()
79  {
80  return $this->rlpVal();
81  }
82 
86  public function val()
87  {
88  return $this->value;
89  }
90 
91 
102  private function checkUtf8($str)
103  {
104  if (preg_match('%^(?:
105  [\x09\x0A\x0D\x20-\x7E] # ASCII
106  | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
107  | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
108  | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
109  | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
110  | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
111  | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
112  | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
113  )*$%xs', $str)) {
114  return true;
115  }
116  return false;
117  }
118 
128  public static function strToHex($string)
129  {
130  $hex = unpack('H*', $string);
131  return array_shift($hex);
132  }
133 
147  public static function hexToStr($string)
148  {
149  return pack('H*', self::removeHexPrefix($string));
150  }
151 
152 }
static cretateFromRLP($hexVal)
Definition: EthS.php:49
static hexToStr($string)
Definition: EthS.php:147
static strToHex($string)
Definition: EthS.php:128
validate($val, array $params)
Definition: EthS.php:22
static decode(string $hexVal)
Definition: Rlp.php:100
static encode(string $val)
Definition: Rlp.php:43