GPBUtil.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. <?php
  2. // Protocol Buffers - Google's data interchange format
  3. // Copyright 2008 Google Inc. All rights reserved.
  4. // https://developers.google.com/protocol-buffers/
  5. //
  6. // Redistribution and use in source and binary forms, with or without
  7. // modification, are permitted provided that the following conditions are
  8. // met:
  9. //
  10. // * Redistributions of source code must retain the above copyright
  11. // notice, this list of conditions and the following disclaimer.
  12. // * Redistributions in binary form must reproduce the above
  13. // copyright notice, this list of conditions and the following disclaimer
  14. // in the documentation and/or other materials provided with the
  15. // distribution.
  16. // * Neither the name of Google Inc. nor the names of its
  17. // contributors may be used to endorse or promote products derived from
  18. // this software without specific prior written permission.
  19. //
  20. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. namespace Google\Protobuf\Internal;
  32. use Google\Protobuf\Duration;
  33. use Google\Protobuf\FieldMask;
  34. use Google\Protobuf\Internal\GPBType;
  35. use Google\Protobuf\Internal\RepeatedField;
  36. use Google\Protobuf\Internal\MapField;
  37. function camel2underscore($input) {
  38. preg_match_all(
  39. '!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!',
  40. $input,
  41. $matches);
  42. $ret = $matches[0];
  43. foreach ($ret as &$match) {
  44. $match = $match == strtoupper($match) ? strtolower($match) : lcfirst($match);
  45. }
  46. return implode('_', $ret);
  47. }
  48. class GPBUtil
  49. {
  50. const NANOS_PER_MILLISECOND = 1000000;
  51. const NANOS_PER_MICROSECOND = 1000;
  52. const TYPE_URL_PREFIX = 'type.googleapis.com/';
  53. public static function divideInt64ToInt32($value, &$high, &$low, $trim = false)
  54. {
  55. $isNeg = (bccomp($value, 0) < 0);
  56. if ($isNeg) {
  57. $value = bcsub(0, $value);
  58. }
  59. $high = bcdiv($value, 4294967296);
  60. $low = bcmod($value, 4294967296);
  61. if (bccomp($high, 2147483647) > 0) {
  62. $high = (int) bcsub($high, 4294967296);
  63. } else {
  64. $high = (int) $high;
  65. }
  66. if (bccomp($low, 2147483647) > 0) {
  67. $low = (int) bcsub($low, 4294967296);
  68. } else {
  69. $low = (int) $low;
  70. }
  71. if ($isNeg) {
  72. $high = ~$high;
  73. $low = ~$low;
  74. $low++;
  75. if (!$low) {
  76. $high = (int)($high + 1);
  77. }
  78. }
  79. if ($trim) {
  80. $high = 0;
  81. }
  82. }
  83. public static function checkString(&$var, $check_utf8)
  84. {
  85. if (is_array($var) || is_object($var)) {
  86. throw new \InvalidArgumentException("Expect string.");
  87. }
  88. if (!is_string($var)) {
  89. $var = strval($var);
  90. }
  91. if ($check_utf8 && !preg_match('//u', $var)) {
  92. throw new \Exception("Expect utf-8 encoding.");
  93. }
  94. }
  95. public static function checkEnum(&$var)
  96. {
  97. static::checkInt32($var);
  98. }
  99. public static function checkInt32(&$var)
  100. {
  101. if (is_numeric($var)) {
  102. $var = intval($var);
  103. } else {
  104. throw new \Exception("Expect integer.");
  105. }
  106. }
  107. public static function checkUint32(&$var)
  108. {
  109. if (is_numeric($var)) {
  110. if (PHP_INT_SIZE === 8) {
  111. $var = intval($var);
  112. $var |= ((-(($var >> 31) & 0x1)) & ~0xFFFFFFFF);
  113. } else {
  114. if (bccomp($var, 0x7FFFFFFF) > 0) {
  115. $var = bcsub($var, "4294967296");
  116. }
  117. $var = (int) $var;
  118. }
  119. } else {
  120. throw new \Exception("Expect integer.");
  121. }
  122. }
  123. public static function checkInt64(&$var)
  124. {
  125. if (is_numeric($var)) {
  126. if (PHP_INT_SIZE == 8) {
  127. $var = intval($var);
  128. } else {
  129. if (is_float($var) ||
  130. is_integer($var) ||
  131. (is_string($var) &&
  132. bccomp($var, "9223372036854774784") < 0)) {
  133. $var = number_format($var, 0, ".", "");
  134. }
  135. }
  136. } else {
  137. throw new \Exception("Expect integer.");
  138. }
  139. }
  140. public static function checkUint64(&$var)
  141. {
  142. if (is_numeric($var)) {
  143. if (PHP_INT_SIZE == 8) {
  144. $var = intval($var);
  145. } else {
  146. $var = number_format($var, 0, ".", "");
  147. }
  148. } else {
  149. throw new \Exception("Expect integer.");
  150. }
  151. }
  152. public static function checkFloat(&$var)
  153. {
  154. if (is_float($var) || is_numeric($var)) {
  155. $var = floatval($var);
  156. } else {
  157. throw new \Exception("Expect float.");
  158. }
  159. }
  160. public static function checkDouble(&$var)
  161. {
  162. if (is_float($var) || is_numeric($var)) {
  163. $var = floatval($var);
  164. } else {
  165. throw new \Exception("Expect float.");
  166. }
  167. }
  168. public static function checkBool(&$var)
  169. {
  170. if (is_array($var) || is_object($var)) {
  171. throw new \Exception("Expect boolean.");
  172. }
  173. $var = boolval($var);
  174. }
  175. public static function checkMessage(&$var, $klass, $newClass = null)
  176. {
  177. if (!$var instanceof $klass && !is_null($var)) {
  178. throw new \Exception("Expect $klass.");
  179. }
  180. }
  181. public static function checkRepeatedField(&$var, $type, $klass = null)
  182. {
  183. if (!$var instanceof RepeatedField && !is_array($var)) {
  184. throw new \Exception("Expect array.");
  185. }
  186. if (is_array($var)) {
  187. $tmp = new RepeatedField($type, $klass);
  188. foreach ($var as $value) {
  189. $tmp[] = $value;
  190. }
  191. return $tmp;
  192. } else {
  193. if ($var->getType() != $type) {
  194. throw new \Exception(
  195. "Expect repeated field of different type.");
  196. }
  197. if ($var->getType() === GPBType::MESSAGE &&
  198. $var->getClass() !== $klass &&
  199. $var->getLegacyClass() !== $klass) {
  200. throw new \Exception(
  201. "Expect repeated field of " . $klass . ".");
  202. }
  203. return $var;
  204. }
  205. }
  206. public static function checkMapField(&$var, $key_type, $value_type, $klass = null)
  207. {
  208. if (!$var instanceof MapField && !is_array($var)) {
  209. throw new \Exception("Expect dict.");
  210. }
  211. if (is_array($var)) {
  212. $tmp = new MapField($key_type, $value_type, $klass);
  213. foreach ($var as $key => $value) {
  214. $tmp[$key] = $value;
  215. }
  216. return $tmp;
  217. } else {
  218. if ($var->getKeyType() != $key_type) {
  219. throw new \Exception("Expect map field of key type.");
  220. }
  221. if ($var->getValueType() != $value_type) {
  222. throw new \Exception("Expect map field of value type.");
  223. }
  224. if ($var->getValueType() === GPBType::MESSAGE &&
  225. $var->getValueClass() !== $klass &&
  226. $var->getLegacyValueClass() !== $klass) {
  227. throw new \Exception(
  228. "Expect map field of " . $klass . ".");
  229. }
  230. return $var;
  231. }
  232. }
  233. public static function Int64($value)
  234. {
  235. return new Int64($value);
  236. }
  237. public static function Uint64($value)
  238. {
  239. return new Uint64($value);
  240. }
  241. public static function getClassNamePrefix(
  242. $classname,
  243. $file_proto)
  244. {
  245. $option = $file_proto->getOptions();
  246. $prefix = is_null($option) ? "" : $option->getPhpClassPrefix();
  247. if ($prefix !== "") {
  248. return $prefix;
  249. }
  250. $reserved_words = array(
  251. "abstract"=>0, "and"=>0, "array"=>0, "as"=>0, "break"=>0,
  252. "callable"=>0, "case"=>0, "catch"=>0, "class"=>0, "clone"=>0,
  253. "const"=>0, "continue"=>0, "declare"=>0, "default"=>0, "die"=>0,
  254. "do"=>0, "echo"=>0, "else"=>0, "elseif"=>0, "empty"=>0,
  255. "enddeclare"=>0, "endfor"=>0, "endforeach"=>0, "endif"=>0,
  256. "endswitch"=>0, "endwhile"=>0, "eval"=>0, "exit"=>0, "extends"=>0,
  257. "final"=>0, "for"=>0, "foreach"=>0, "function"=>0, "global"=>0,
  258. "goto"=>0, "if"=>0, "implements"=>0, "include"=>0,
  259. "include_once"=>0, "instanceof"=>0, "insteadof"=>0, "interface"=>0,
  260. "isset"=>0, "list"=>0, "namespace"=>0, "new"=>0, "or"=>0,
  261. "print"=>0, "private"=>0, "protected"=>0, "public"=>0, "require"=>0,
  262. "require_once"=>0, "return"=>0, "static"=>0, "switch"=>0,
  263. "throw"=>0, "trait"=>0, "try"=>0, "unset"=>0, "use"=>0, "var"=>0,
  264. "while"=>0, "xor"=>0, "int"=>0, "float"=>0, "bool"=>0, "string"=>0,
  265. "true"=>0, "false"=>0, "null"=>0, "void"=>0, "iterable"=>0
  266. );
  267. if (array_key_exists(strtolower($classname), $reserved_words)) {
  268. if ($file_proto->getPackage() === "google.protobuf") {
  269. return "GPB";
  270. } else {
  271. return "PB";
  272. }
  273. }
  274. return "";
  275. }
  276. public static function getLegacyClassNameWithoutPackage(
  277. $name,
  278. $file_proto)
  279. {
  280. $classname = implode('_', explode('.', $name));
  281. return static::getClassNamePrefix($classname, $file_proto) . $classname;
  282. }
  283. public static function getClassNameWithoutPackage(
  284. $name,
  285. $file_proto)
  286. {
  287. $parts = explode('.', $name);
  288. foreach ($parts as $i => $part) {
  289. $parts[$i] = static::getClassNamePrefix($parts[$i], $file_proto) . $parts[$i];
  290. }
  291. return implode('\\', $parts);
  292. }
  293. public static function getFullClassName(
  294. $proto,
  295. $containing,
  296. $file_proto,
  297. &$message_name_without_package,
  298. &$classname,
  299. &$legacy_classname,
  300. &$fullname)
  301. {
  302. // Full name needs to start with '.'.
  303. $message_name_without_package = $proto->getName();
  304. if ($containing !== "") {
  305. $message_name_without_package =
  306. $containing . "." . $message_name_without_package;
  307. }
  308. $package = $file_proto->getPackage();
  309. if ($package === "") {
  310. $fullname = "." . $message_name_without_package;
  311. } else {
  312. $fullname = "." . $package . "." . $message_name_without_package;
  313. }
  314. $class_name_without_package =
  315. static::getClassNameWithoutPackage($message_name_without_package, $file_proto);
  316. $legacy_class_name_without_package =
  317. static::getLegacyClassNameWithoutPackage(
  318. $message_name_without_package, $file_proto);
  319. $option = $file_proto->getOptions();
  320. if (!is_null($option) && $option->hasPhpNamespace()) {
  321. $namespace = $option->getPhpNamespace();
  322. if ($namespace !== "") {
  323. $classname = $namespace . "\\" . $class_name_without_package;
  324. $legacy_classname =
  325. $namespace . "\\" . $legacy_class_name_without_package;
  326. return;
  327. } else {
  328. $classname = $class_name_without_package;
  329. $legacy_classname = $legacy_class_name_without_package;
  330. return;
  331. }
  332. }
  333. if ($package === "") {
  334. $classname = $class_name_without_package;
  335. $legacy_classname = $legacy_class_name_without_package;
  336. } else {
  337. $parts = array_map('ucwords', explode('.', $package));
  338. foreach ($parts as $i => $part) {
  339. $parts[$i] = self::getClassNamePrefix($part, $file_proto).$part;
  340. }
  341. $classname =
  342. implode('\\', $parts) .
  343. "\\".self::getClassNamePrefix($class_name_without_package,$file_proto).
  344. $class_name_without_package;
  345. $legacy_classname =
  346. implode('\\', array_map('ucwords', explode('.', $package))).
  347. "\\".$legacy_class_name_without_package;
  348. }
  349. }
  350. public static function combineInt32ToInt64($high, $low)
  351. {
  352. $isNeg = $high < 0;
  353. if ($isNeg) {
  354. $high = ~$high;
  355. $low = ~$low;
  356. $low++;
  357. if (!$low) {
  358. $high = (int) ($high + 1);
  359. }
  360. }
  361. $result = bcadd(bcmul($high, 4294967296), $low);
  362. if ($low < 0) {
  363. $result = bcadd($result, 4294967296);
  364. }
  365. if ($isNeg) {
  366. $result = bcsub(0, $result);
  367. }
  368. return $result;
  369. }
  370. public static function parseTimestamp($timestamp)
  371. {
  372. // prevent parsing timestamps containing with the non-existant year "0000"
  373. // DateTime::createFromFormat parses without failing but as a nonsensical date
  374. if (substr($timestamp, 0, 4) === "0000") {
  375. throw new \Exception("Year cannot be zero.");
  376. }
  377. // prevent parsing timestamps ending with a lowercase z
  378. if (substr($timestamp, -1, 1) === "z") {
  379. throw new \Exception("Timezone cannot be a lowercase z.");
  380. }
  381. $nanoseconds = 0;
  382. $periodIndex = strpos($timestamp, ".");
  383. if ($periodIndex !== false) {
  384. $nanosecondsLength = 0;
  385. // find the next non-numeric character in the timestamp to calculate
  386. // the length of the nanoseconds text
  387. for ($i = $periodIndex + 1, $length = strlen($timestamp); $i < $length; $i++) {
  388. if (!is_numeric($timestamp[$i])) {
  389. $nanosecondsLength = $i - ($periodIndex + 1);
  390. break;
  391. }
  392. }
  393. if ($nanosecondsLength % 3 !== 0) {
  394. throw new \Exception("Nanoseconds must be disible by 3.");
  395. }
  396. if ($nanosecondsLength > 9) {
  397. throw new \Exception("Nanoseconds must be in the range of 0 to 999,999,999 nanoseconds.");
  398. }
  399. if ($nanosecondsLength > 0) {
  400. $nanoseconds = substr($timestamp, $periodIndex + 1, $nanosecondsLength);
  401. $nanoseconds = intval($nanoseconds);
  402. // remove the nanoseconds and preceding period from the timestamp
  403. $date = substr($timestamp, 0, $periodIndex);
  404. $timezone = substr($timestamp, $periodIndex + $nanosecondsLength + 1);
  405. $timestamp = $date.$timezone;
  406. }
  407. }
  408. $date = \DateTime::createFromFormat(\DateTime::RFC3339, $timestamp, new \DateTimeZone("UTC"));
  409. if ($date === false) {
  410. throw new \Exception("Invalid RFC 3339 timestamp.");
  411. }
  412. $value = new \Google\Protobuf\Timestamp();
  413. $seconds = $date->format("U");
  414. $value->setSeconds($seconds);
  415. $value->setNanos($nanoseconds);
  416. return $value;
  417. }
  418. public static function formatTimestamp($value)
  419. {
  420. if (bccomp($value->getSeconds(), "253402300800") != -1) {
  421. throw new GPBDecodeException("Duration number too large.");
  422. }
  423. if (bccomp($value->getSeconds(), "-62135596801") != 1) {
  424. throw new GPBDecodeException("Duration number too small.");
  425. }
  426. $nanoseconds = static::getNanosecondsForTimestamp($value->getNanos());
  427. if (!empty($nanoseconds)) {
  428. $nanoseconds = ".".$nanoseconds;
  429. }
  430. $date = new \DateTime('@'.$value->getSeconds(), new \DateTimeZone("UTC"));
  431. return $date->format("Y-m-d\TH:i:s".$nanoseconds."\Z");
  432. }
  433. public static function parseDuration($value)
  434. {
  435. if (strlen($value) < 2 || substr($value, -1) !== "s") {
  436. throw new GPBDecodeException("Missing s after duration string");
  437. }
  438. $number = substr($value, 0, -1);
  439. if (bccomp($number, "315576000001") != -1) {
  440. throw new GPBDecodeException("Duration number too large.");
  441. }
  442. if (bccomp($number, "-315576000001") != 1) {
  443. throw new GPBDecodeException("Duration number too small.");
  444. }
  445. $pos = strrpos($number, ".");
  446. if ($pos !== false) {
  447. $seconds = substr($number, 0, $pos);
  448. if (bccomp($seconds, 0) < 0) {
  449. $nanos = bcmul("0" . substr($number, $pos), -1000000000);
  450. } else {
  451. $nanos = bcmul("0" . substr($number, $pos), 1000000000);
  452. }
  453. } else {
  454. $seconds = $number;
  455. $nanos = 0;
  456. }
  457. $duration = new Duration();
  458. $duration->setSeconds($seconds);
  459. $duration->setNanos($nanos);
  460. return $duration;
  461. }
  462. public static function formatDuration($value)
  463. {
  464. if (bccomp($value->getSeconds(), "315576000001") != -1) {
  465. throw new GPBDecodeException("Duration number too large.");
  466. }
  467. if (bccomp($value->getSeconds(), "-315576000001") != 1) {
  468. throw new GPBDecodeException("Duration number too small.");
  469. }
  470. return strval(bcadd($value->getSeconds(),
  471. $value->getNanos() / 1000000000.0, 9));
  472. }
  473. public static function parseFieldMask($paths_string)
  474. {
  475. $field_mask = new FieldMask();
  476. if (strlen($paths_string) === 0) {
  477. return $field_mask;
  478. }
  479. $path_strings = explode(",", $paths_string);
  480. $paths = $field_mask->getPaths();
  481. foreach($path_strings as &$path_string) {
  482. $field_strings = explode(".", $path_string);
  483. foreach($field_strings as &$field_string) {
  484. $field_string = camel2underscore($field_string);
  485. }
  486. $path_string = implode(".", $field_strings);
  487. $paths[] = $path_string;
  488. }
  489. return $field_mask;
  490. }
  491. public static function formatFieldMask($field_mask)
  492. {
  493. $converted_paths = [];
  494. foreach($field_mask->getPaths() as $path) {
  495. $fields = explode('.', $path);
  496. $converted_path = [];
  497. foreach ($fields as $field) {
  498. $segments = explode('_', $field);
  499. $start = true;
  500. $converted_segments = "";
  501. foreach($segments as $segment) {
  502. if (!$start) {
  503. $converted = ucfirst($segment);
  504. } else {
  505. $converted = $segment;
  506. $start = false;
  507. }
  508. $converted_segments .= $converted;
  509. }
  510. $converted_path []= $converted_segments;
  511. }
  512. $converted_path = implode(".", $converted_path);
  513. $converted_paths []= $converted_path;
  514. }
  515. return implode(",", $converted_paths);
  516. }
  517. public static function getNanosecondsForTimestamp($nanoseconds)
  518. {
  519. if ($nanoseconds == 0) {
  520. return '';
  521. }
  522. if ($nanoseconds % static::NANOS_PER_MILLISECOND == 0) {
  523. return sprintf('%03d', $nanoseconds / static::NANOS_PER_MILLISECOND);
  524. }
  525. if ($nanoseconds % static::NANOS_PER_MICROSECOND == 0) {
  526. return sprintf('%06d', $nanoseconds / static::NANOS_PER_MICROSECOND);
  527. }
  528. return sprintf('%09d', $nanoseconds);
  529. }
  530. public static function hasSpecialJsonMapping($msg)
  531. {
  532. return is_a($msg, 'Google\Protobuf\Any') ||
  533. is_a($msg, "Google\Protobuf\ListValue") ||
  534. is_a($msg, "Google\Protobuf\Struct") ||
  535. is_a($msg, "Google\Protobuf\Value") ||
  536. is_a($msg, "Google\Protobuf\Duration") ||
  537. is_a($msg, "Google\Protobuf\Timestamp") ||
  538. is_a($msg, "Google\Protobuf\FieldMask") ||
  539. static::hasJsonValue($msg);
  540. }
  541. public static function hasJsonValue($msg)
  542. {
  543. return is_a($msg, "Google\Protobuf\DoubleValue") ||
  544. is_a($msg, "Google\Protobuf\FloatValue") ||
  545. is_a($msg, "Google\Protobuf\Int64Value") ||
  546. is_a($msg, "Google\Protobuf\UInt64Value") ||
  547. is_a($msg, "Google\Protobuf\Int32Value") ||
  548. is_a($msg, "Google\Protobuf\UInt32Value") ||
  549. is_a($msg, "Google\Protobuf\BoolValue") ||
  550. is_a($msg, "Google\Protobuf\StringValue") ||
  551. is_a($msg, "Google\Protobuf\BytesValue");
  552. }
  553. }