Message.php 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022
  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. /**
  32. * Defines Message, the parent class extended by all protocol message classes.
  33. */
  34. namespace Google\Protobuf\Internal;
  35. use Google\Protobuf\Internal\CodedInputStream;
  36. use Google\Protobuf\Internal\CodedOutputStream;
  37. use Google\Protobuf\Internal\DescriptorPool;
  38. use Google\Protobuf\Internal\GPBLabel;
  39. use Google\Protobuf\Internal\GPBType;
  40. use Google\Protobuf\Internal\GPBWire;
  41. use Google\Protobuf\Internal\MapEntry;
  42. use Google\Protobuf\Internal\RepeatedField;
  43. use Google\Protobuf\ListValue;
  44. use Google\Protobuf\Value;
  45. use Google\Protobuf\Struct;
  46. use Google\Protobuf\NullValue;
  47. /**
  48. * Parent class of all proto messages. Users should not instantiate this class
  49. * or extend this class or its child classes by their own. See the comment of
  50. * specific functions for more details.
  51. */
  52. class Message
  53. {
  54. /**
  55. * @ignore
  56. */
  57. private $desc;
  58. private $unknown = "";
  59. /**
  60. * @ignore
  61. */
  62. public function __construct($data = NULL)
  63. {
  64. // MapEntry message is shared by all types of map fields, whose
  65. // descriptors are different from each other. Thus, we cannot find a
  66. // specific descriptor from the descriptor pool.
  67. if ($this instanceof MapEntry) {
  68. $this->initWithDescriptor($data);
  69. } else {
  70. $this->initWithGeneratedPool();
  71. if (is_array($data)) {
  72. $this->mergeFromArray($data);
  73. } else if (!empty($data)) {
  74. throw new \InvalidArgumentException(
  75. 'Message constructor must be an array or null.'
  76. );
  77. }
  78. }
  79. }
  80. /**
  81. * @ignore
  82. */
  83. private function initWithGeneratedPool()
  84. {
  85. $pool = DescriptorPool::getGeneratedPool();
  86. $this->desc = $pool->getDescriptorByClassName(get_class($this));
  87. if (is_null($this->desc)) {
  88. user_error(get_class($this) . " is not found in descriptor pool.");
  89. return;
  90. }
  91. foreach ($this->desc->getField() as $field) {
  92. $setter = $field->getSetter();
  93. if ($field->isMap()) {
  94. $message_type = $field->getMessageType();
  95. $key_field = $message_type->getFieldByNumber(1);
  96. $value_field = $message_type->getFieldByNumber(2);
  97. switch ($value_field->getType()) {
  98. case GPBType::MESSAGE:
  99. case GPBType::GROUP:
  100. $map_field = new MapField(
  101. $key_field->getType(),
  102. $value_field->getType(),
  103. $value_field->getMessageType()->getClass());
  104. $this->$setter($map_field);
  105. break;
  106. case GPBType::ENUM:
  107. $map_field = new MapField(
  108. $key_field->getType(),
  109. $value_field->getType(),
  110. $value_field->getEnumType()->getClass());
  111. $this->$setter($map_field);
  112. break;
  113. default:
  114. $map_field = new MapField(
  115. $key_field->getType(),
  116. $value_field->getType());
  117. $this->$setter($map_field);
  118. break;
  119. }
  120. } else if ($field->getLabel() === GPBLabel::REPEATED) {
  121. switch ($field->getType()) {
  122. case GPBType::MESSAGE:
  123. case GPBType::GROUP:
  124. $repeated_field = new RepeatedField(
  125. $field->getType(),
  126. $field->getMessageType()->getClass());
  127. $this->$setter($repeated_field);
  128. break;
  129. case GPBType::ENUM:
  130. $repeated_field = new RepeatedField(
  131. $field->getType(),
  132. $field->getEnumType()->getClass());
  133. $this->$setter($repeated_field);
  134. break;
  135. default:
  136. $repeated_field = new RepeatedField($field->getType());
  137. $this->$setter($repeated_field);
  138. break;
  139. }
  140. } else if ($field->getOneofIndex() !== -1) {
  141. $oneof = $this->desc->getOneofDecl()[$field->getOneofIndex()];
  142. $oneof_name = $oneof->getName();
  143. $this->$oneof_name = new OneofField($oneof);
  144. } else if ($field->getLabel() === GPBLabel::OPTIONAL &&
  145. PHP_INT_SIZE == 4) {
  146. switch ($field->getType()) {
  147. case GPBType::INT64:
  148. case GPBType::UINT64:
  149. case GPBType::FIXED64:
  150. case GPBType::SFIXED64:
  151. case GPBType::SINT64:
  152. $this->$setter("0");
  153. }
  154. }
  155. }
  156. }
  157. /**
  158. * @ignore
  159. */
  160. private function initWithDescriptor(Descriptor $desc)
  161. {
  162. $this->desc = $desc;
  163. foreach ($desc->getField() as $field) {
  164. $setter = $field->getSetter();
  165. $defaultValue = $this->defaultValue($field);
  166. $this->$setter($defaultValue);
  167. }
  168. }
  169. protected function readWrapperValue($member)
  170. {
  171. $field = $this->desc->getFieldByName($member);
  172. $oneof_index = $field->getOneofIndex();
  173. if ($oneof_index === -1) {
  174. $wrapper = $this->$member;
  175. } else {
  176. $wrapper = $this->readOneof($field->getNumber());
  177. }
  178. if (is_null($wrapper)) {
  179. return NULL;
  180. } else {
  181. return $wrapper->getValue();
  182. }
  183. }
  184. protected function writeWrapperValue($member, $value)
  185. {
  186. $field = $this->desc->getFieldByName($member);
  187. $wrapped_value = $value;
  188. if (!is_null($value)) {
  189. $desc = $field->getMessageType();
  190. $klass = $desc->getClass();
  191. $wrapped_value = new $klass;
  192. $wrapped_value->setValue($value);
  193. }
  194. $oneof_index = $field->getOneofIndex();
  195. if ($oneof_index === -1) {
  196. $this->$member = $wrapped_value;
  197. } else {
  198. $this->writeOneof($field->getNumber(), $wrapped_value);
  199. }
  200. }
  201. protected function readOneof($number)
  202. {
  203. $field = $this->desc->getFieldByNumber($number);
  204. $oneof = $this->desc->getOneofDecl()[$field->getOneofIndex()];
  205. $oneof_name = $oneof->getName();
  206. $oneof_field = $this->$oneof_name;
  207. if ($number === $oneof_field->getNumber()) {
  208. return $oneof_field->getValue();
  209. } else {
  210. return $this->defaultValue($field);
  211. }
  212. }
  213. protected function hasOneof($number)
  214. {
  215. $field = $this->desc->getFieldByNumber($number);
  216. $oneof = $this->desc->getOneofDecl()[$field->getOneofIndex()];
  217. $oneof_name = $oneof->getName();
  218. $oneof_field = $this->$oneof_name;
  219. return $number === $oneof_field->getNumber();
  220. }
  221. protected function writeOneof($number, $value)
  222. {
  223. $field = $this->desc->getFieldByNumber($number);
  224. $oneof = $this->desc->getOneofDecl()[$field->getOneofIndex()];
  225. $oneof_name = $oneof->getName();
  226. $oneof_field = $this->$oneof_name;
  227. $oneof_field->setValue($value);
  228. $oneof_field->setFieldName($field->getName());
  229. $oneof_field->setNumber($number);
  230. }
  231. protected function whichOneof($oneof_name)
  232. {
  233. $oneof_field = $this->$oneof_name;
  234. $number = $oneof_field->getNumber();
  235. if ($number == 0) {
  236. return "";
  237. }
  238. $field = $this->desc->getFieldByNumber($number);
  239. return $field->getName();
  240. }
  241. /**
  242. * @ignore
  243. */
  244. private function defaultValue($field)
  245. {
  246. $value = null;
  247. switch ($field->getType()) {
  248. case GPBType::DOUBLE:
  249. case GPBType::FLOAT:
  250. return 0.0;
  251. case GPBType::UINT32:
  252. case GPBType::INT32:
  253. case GPBType::FIXED32:
  254. case GPBType::SFIXED32:
  255. case GPBType::SINT32:
  256. case GPBType::ENUM:
  257. return 0;
  258. case GPBType::INT64:
  259. case GPBType::UINT64:
  260. case GPBType::FIXED64:
  261. case GPBType::SFIXED64:
  262. case GPBType::SINT64:
  263. if (PHP_INT_SIZE === 4) {
  264. return '0';
  265. } else {
  266. return 0;
  267. }
  268. case GPBType::BOOL:
  269. return false;
  270. case GPBType::STRING:
  271. case GPBType::BYTES:
  272. return "";
  273. case GPBType::GROUP:
  274. case GPBType::MESSAGE:
  275. return null;
  276. default:
  277. user_error("Unsupported type.");
  278. return false;
  279. }
  280. }
  281. /**
  282. * @ignore
  283. */
  284. private function skipField($input, $tag)
  285. {
  286. $number = GPBWire::getTagFieldNumber($tag);
  287. if ($number === 0) {
  288. throw new GPBDecodeException("Illegal field number zero.");
  289. }
  290. $start = $input->current();
  291. switch (GPBWire::getTagWireType($tag)) {
  292. case GPBWireType::VARINT:
  293. $uint64 = 0;
  294. if (!$input->readVarint64($uint64)) {
  295. throw new GPBDecodeException(
  296. "Unexpected EOF inside varint.");
  297. }
  298. break;
  299. case GPBWireType::FIXED64:
  300. $uint64 = 0;
  301. if (!$input->readLittleEndian64($uint64)) {
  302. throw new GPBDecodeException(
  303. "Unexpected EOF inside fixed64.");
  304. }
  305. break;
  306. case GPBWireType::FIXED32:
  307. $uint32 = 0;
  308. if (!$input->readLittleEndian32($uint32)) {
  309. throw new GPBDecodeException(
  310. "Unexpected EOF inside fixed32.");
  311. }
  312. break;
  313. case GPBWireType::LENGTH_DELIMITED:
  314. $length = 0;
  315. if (!$input->readVarint32($length)) {
  316. throw new GPBDecodeException(
  317. "Unexpected EOF inside length.");
  318. }
  319. $data = NULL;
  320. if (!$input->readRaw($length, $data)) {
  321. throw new GPBDecodeException(
  322. "Unexpected EOF inside length delimited data.");
  323. }
  324. break;
  325. case GPBWireType::START_GROUP:
  326. case GPBWireType::END_GROUP:
  327. throw new GPBDecodeException("Unexpected wire type.");
  328. default:
  329. throw new GPBDecodeException("Unexpected wire type.");
  330. }
  331. $end = $input->current();
  332. $bytes = str_repeat(chr(0), CodedOutputStream::MAX_VARINT64_BYTES);
  333. $size = CodedOutputStream::writeVarintToArray($tag, $bytes, true);
  334. $this->unknown .= substr($bytes, 0, $size) . $input->substr($start, $end);
  335. }
  336. /**
  337. * @ignore
  338. */
  339. private static function parseFieldFromStreamNoTag($input, $field, &$value)
  340. {
  341. switch ($field->getType()) {
  342. case GPBType::DOUBLE:
  343. if (!GPBWire::readDouble($input, $value)) {
  344. throw new GPBDecodeException(
  345. "Unexpected EOF inside double field.");
  346. }
  347. break;
  348. case GPBType::FLOAT:
  349. if (!GPBWire::readFloat($input, $value)) {
  350. throw new GPBDecodeException(
  351. "Unexpected EOF inside float field.");
  352. }
  353. break;
  354. case GPBType::INT64:
  355. if (!GPBWire::readInt64($input, $value)) {
  356. throw new GPBDecodeException(
  357. "Unexpected EOF inside int64 field.");
  358. }
  359. break;
  360. case GPBType::UINT64:
  361. if (!GPBWire::readUint64($input, $value)) {
  362. throw new GPBDecodeException(
  363. "Unexpected EOF inside uint64 field.");
  364. }
  365. break;
  366. case GPBType::INT32:
  367. if (!GPBWire::readInt32($input, $value)) {
  368. throw new GPBDecodeException(
  369. "Unexpected EOF inside int32 field.");
  370. }
  371. break;
  372. case GPBType::FIXED64:
  373. if (!GPBWire::readFixed64($input, $value)) {
  374. throw new GPBDecodeException(
  375. "Unexpected EOF inside fixed64 field.");
  376. }
  377. break;
  378. case GPBType::FIXED32:
  379. if (!GPBWire::readFixed32($input, $value)) {
  380. throw new GPBDecodeException(
  381. "Unexpected EOF inside fixed32 field.");
  382. }
  383. break;
  384. case GPBType::BOOL:
  385. if (!GPBWire::readBool($input, $value)) {
  386. throw new GPBDecodeException(
  387. "Unexpected EOF inside bool field.");
  388. }
  389. break;
  390. case GPBType::STRING:
  391. // TODO(teboring): Add utf-8 check.
  392. if (!GPBWire::readString($input, $value)) {
  393. throw new GPBDecodeException(
  394. "Unexpected EOF inside string field.");
  395. }
  396. break;
  397. case GPBType::GROUP:
  398. trigger_error("Not implemented.", E_ERROR);
  399. break;
  400. case GPBType::MESSAGE:
  401. if ($field->isMap()) {
  402. $value = new MapEntry($field->getMessageType());
  403. } else {
  404. $klass = $field->getMessageType()->getClass();
  405. $value = new $klass;
  406. }
  407. if (!GPBWire::readMessage($input, $value)) {
  408. throw new GPBDecodeException(
  409. "Unexpected EOF inside message.");
  410. }
  411. break;
  412. case GPBType::BYTES:
  413. if (!GPBWire::readString($input, $value)) {
  414. throw new GPBDecodeException(
  415. "Unexpected EOF inside bytes field.");
  416. }
  417. break;
  418. case GPBType::UINT32:
  419. if (!GPBWire::readUint32($input, $value)) {
  420. throw new GPBDecodeException(
  421. "Unexpected EOF inside uint32 field.");
  422. }
  423. break;
  424. case GPBType::ENUM:
  425. // TODO(teboring): Check unknown enum value.
  426. if (!GPBWire::readInt32($input, $value)) {
  427. throw new GPBDecodeException(
  428. "Unexpected EOF inside enum field.");
  429. }
  430. break;
  431. case GPBType::SFIXED32:
  432. if (!GPBWire::readSfixed32($input, $value)) {
  433. throw new GPBDecodeException(
  434. "Unexpected EOF inside sfixed32 field.");
  435. }
  436. break;
  437. case GPBType::SFIXED64:
  438. if (!GPBWire::readSfixed64($input, $value)) {
  439. throw new GPBDecodeException(
  440. "Unexpected EOF inside sfixed64 field.");
  441. }
  442. break;
  443. case GPBType::SINT32:
  444. if (!GPBWire::readSint32($input, $value)) {
  445. throw new GPBDecodeException(
  446. "Unexpected EOF inside sint32 field.");
  447. }
  448. break;
  449. case GPBType::SINT64:
  450. if (!GPBWire::readSint64($input, $value)) {
  451. throw new GPBDecodeException(
  452. "Unexpected EOF inside sint64 field.");
  453. }
  454. break;
  455. default:
  456. user_error("Unsupported type.");
  457. return false;
  458. }
  459. return true;
  460. }
  461. /**
  462. * @ignore
  463. */
  464. private function parseFieldFromStream($tag, $input, $field)
  465. {
  466. $value = null;
  467. if (is_null($field)) {
  468. $value_format = GPBWire::UNKNOWN;
  469. } elseif (GPBWire::getTagWireType($tag) ===
  470. GPBWire::getWireType($field->getType())) {
  471. $value_format = GPBWire::NORMAL_FORMAT;
  472. } elseif ($field->isPackable() &&
  473. GPBWire::getTagWireType($tag) ===
  474. GPBWire::WIRETYPE_LENGTH_DELIMITED) {
  475. $value_format = GPBWire::PACKED_FORMAT;
  476. } else {
  477. // the wire type doesn't match. Put it in our unknown field set.
  478. $value_format = GPBWire::UNKNOWN;
  479. }
  480. if ($value_format === GPBWire::UNKNOWN) {
  481. $this->skipField($input, $tag);
  482. return;
  483. } elseif ($value_format === GPBWire::NORMAL_FORMAT) {
  484. self::parseFieldFromStreamNoTag($input, $field, $value);
  485. } elseif ($value_format === GPBWire::PACKED_FORMAT) {
  486. $length = 0;
  487. if (!GPBWire::readInt32($input, $length)) {
  488. throw new GPBDecodeException(
  489. "Unexpected EOF inside packed length.");
  490. }
  491. $limit = $input->pushLimit($length);
  492. $getter = $field->getGetter();
  493. while ($input->bytesUntilLimit() > 0) {
  494. self::parseFieldFromStreamNoTag($input, $field, $value);
  495. $this->appendHelper($field, $value);
  496. }
  497. $input->popLimit($limit);
  498. return;
  499. } else {
  500. return;
  501. }
  502. if ($field->isMap()) {
  503. $this->kvUpdateHelper($field, $value->getKey(), $value->getValue());
  504. } else if ($field->isRepeated()) {
  505. $this->appendHelper($field, $value);
  506. } else {
  507. $setter = $field->getSetter();
  508. $this->$setter($value);
  509. }
  510. }
  511. /**
  512. * Clear all containing fields.
  513. * @return null.
  514. */
  515. public function clear()
  516. {
  517. $this->unknown = "";
  518. foreach ($this->desc->getField() as $field) {
  519. $setter = $field->getSetter();
  520. if ($field->isMap()) {
  521. $message_type = $field->getMessageType();
  522. $key_field = $message_type->getFieldByNumber(1);
  523. $value_field = $message_type->getFieldByNumber(2);
  524. switch ($value_field->getType()) {
  525. case GPBType::MESSAGE:
  526. case GPBType::GROUP:
  527. $map_field = new MapField(
  528. $key_field->getType(),
  529. $value_field->getType(),
  530. $value_field->getMessageType()->getClass());
  531. $this->$setter($map_field);
  532. break;
  533. case GPBType::ENUM:
  534. $map_field = new MapField(
  535. $key_field->getType(),
  536. $value_field->getType(),
  537. $value_field->getEnumType()->getClass());
  538. $this->$setter($map_field);
  539. break;
  540. default:
  541. $map_field = new MapField(
  542. $key_field->getType(),
  543. $value_field->getType());
  544. $this->$setter($map_field);
  545. break;
  546. }
  547. } else if ($field->getLabel() === GPBLabel::REPEATED) {
  548. switch ($field->getType()) {
  549. case GPBType::MESSAGE:
  550. case GPBType::GROUP:
  551. $repeated_field = new RepeatedField(
  552. $field->getType(),
  553. $field->getMessageType()->getClass());
  554. $this->$setter($repeated_field);
  555. break;
  556. case GPBType::ENUM:
  557. $repeated_field = new RepeatedField(
  558. $field->getType(),
  559. $field->getEnumType()->getClass());
  560. $this->$setter($repeated_field);
  561. break;
  562. default:
  563. $repeated_field = new RepeatedField($field->getType());
  564. $this->$setter($repeated_field);
  565. break;
  566. }
  567. } else if ($field->getOneofIndex() !== -1) {
  568. $oneof = $this->desc->getOneofDecl()[$field->getOneofIndex()];
  569. $oneof_name = $oneof->getName();
  570. $this->$oneof_name = new OneofField($oneof);
  571. } else if ($field->getLabel() === GPBLabel::OPTIONAL) {
  572. switch ($field->getType()) {
  573. case GPBType::DOUBLE :
  574. case GPBType::FLOAT :
  575. $this->$setter(0.0);
  576. break;
  577. case GPBType::INT32 :
  578. case GPBType::FIXED32 :
  579. case GPBType::UINT32 :
  580. case GPBType::SFIXED32 :
  581. case GPBType::SINT32 :
  582. case GPBType::ENUM :
  583. $this->$setter(0);
  584. break;
  585. case GPBType::BOOL :
  586. $this->$setter(false);
  587. break;
  588. case GPBType::STRING :
  589. case GPBType::BYTES :
  590. $this->$setter("");
  591. break;
  592. case GPBType::GROUP :
  593. case GPBType::MESSAGE :
  594. $null = null;
  595. $this->$setter($null);
  596. break;
  597. }
  598. if (PHP_INT_SIZE == 4) {
  599. switch ($field->getType()) {
  600. case GPBType::INT64:
  601. case GPBType::UINT64:
  602. case GPBType::FIXED64:
  603. case GPBType::SFIXED64:
  604. case GPBType::SINT64:
  605. $this->$setter("0");
  606. }
  607. } else {
  608. switch ($field->getType()) {
  609. case GPBType::INT64:
  610. case GPBType::UINT64:
  611. case GPBType::FIXED64:
  612. case GPBType::SFIXED64:
  613. case GPBType::SINT64:
  614. $this->$setter(0);
  615. }
  616. }
  617. }
  618. }
  619. }
  620. /**
  621. * Clear all unknown fields previously parsed.
  622. * @return null.
  623. */
  624. public function discardUnknownFields()
  625. {
  626. $this->unknown = "";
  627. foreach ($this->desc->getField() as $field) {
  628. if ($field->getType() != GPBType::MESSAGE) {
  629. continue;
  630. }
  631. if ($field->isMap()) {
  632. $value_field = $field->getMessageType()->getFieldByNumber(2);
  633. if ($value_field->getType() != GPBType::MESSAGE) {
  634. continue;
  635. }
  636. $getter = $field->getGetter();
  637. $map = $this->$getter();
  638. foreach ($map as $key => $value) {
  639. $value->discardUnknownFields();
  640. }
  641. } else if ($field->getLabel() === GPBLabel::REPEATED) {
  642. $getter = $field->getGetter();
  643. $arr = $this->$getter();
  644. foreach ($arr as $sub) {
  645. $sub->discardUnknownFields();
  646. }
  647. } else if ($field->getLabel() === GPBLabel::OPTIONAL) {
  648. $getter = $field->getGetter();
  649. $sub = $this->$getter();
  650. if (!is_null($sub)) {
  651. $sub->discardUnknownFields();
  652. }
  653. }
  654. }
  655. }
  656. /**
  657. * Merges the contents of the specified message into current message.
  658. *
  659. * This method merges the contents of the specified message into the
  660. * current message. Singular fields that are set in the specified message
  661. * overwrite the corresponding fields in the current message. Repeated
  662. * fields are appended. Map fields key-value pairs are overwritten.
  663. * Singular/Oneof sub-messages are recursively merged. All overwritten
  664. * sub-messages are deep-copied.
  665. *
  666. * @param object $msg Protobuf message to be merged from.
  667. * @return null.
  668. */
  669. public function mergeFrom($msg)
  670. {
  671. if (get_class($this) !== get_class($msg)) {
  672. user_error("Cannot merge messages with different class.");
  673. return;
  674. }
  675. foreach ($this->desc->getField() as $field) {
  676. $setter = $field->getSetter();
  677. $getter = $field->getGetter();
  678. if ($field->isMap()) {
  679. if (count($msg->$getter()) != 0) {
  680. $value_field = $field->getMessageType()->getFieldByNumber(2);
  681. foreach ($msg->$getter() as $key => $value) {
  682. if ($value_field->getType() == GPBType::MESSAGE) {
  683. $klass = $value_field->getMessageType()->getClass();
  684. $copy = new $klass;
  685. $copy->mergeFrom($value);
  686. $this->kvUpdateHelper($field, $key, $copy);
  687. } else {
  688. $this->kvUpdateHelper($field, $key, $value);
  689. }
  690. }
  691. }
  692. } else if ($field->getLabel() === GPBLabel::REPEATED) {
  693. if (count($msg->$getter()) != 0) {
  694. foreach ($msg->$getter() as $tmp) {
  695. if ($field->getType() == GPBType::MESSAGE) {
  696. $klass = $field->getMessageType()->getClass();
  697. $copy = new $klass;
  698. $copy->mergeFrom($tmp);
  699. $this->appendHelper($field, $copy);
  700. } else {
  701. $this->appendHelper($field, $tmp);
  702. }
  703. }
  704. }
  705. } else if ($field->getLabel() === GPBLabel::OPTIONAL) {
  706. if($msg->$getter() !== $this->defaultValue($field)) {
  707. $tmp = $msg->$getter();
  708. if ($field->getType() == GPBType::MESSAGE) {
  709. if (is_null($this->$getter())) {
  710. $klass = $field->getMessageType()->getClass();
  711. $new_msg = new $klass;
  712. $this->$setter($new_msg);
  713. }
  714. $this->$getter()->mergeFrom($tmp);
  715. } else {
  716. $this->$setter($tmp);
  717. }
  718. }
  719. }
  720. }
  721. }
  722. /**
  723. * Parses a protocol buffer contained in a string.
  724. *
  725. * This function takes a string in the (non-human-readable) binary wire
  726. * format, matching the encoding output by serializeToString().
  727. * See mergeFrom() for merging behavior, if the field is already set in the
  728. * specified message.
  729. *
  730. * @param string $data Binary protobuf data.
  731. * @return null.
  732. * @throws \Exception Invalid data.
  733. */
  734. public function mergeFromString($data)
  735. {
  736. $input = new CodedInputStream($data);
  737. $this->parseFromStream($input);
  738. }
  739. /**
  740. * Parses a json string to protobuf message.
  741. *
  742. * This function takes a string in the json wire format, matching the
  743. * encoding output by serializeToJsonString().
  744. * See mergeFrom() for merging behavior, if the field is already set in the
  745. * specified message.
  746. *
  747. * @param string $data Json protobuf data.
  748. * @return null.
  749. * @throws \Exception Invalid data.
  750. */
  751. public function mergeFromJsonString($data, $ignore_unknown = false)
  752. {
  753. $input = new RawInputStream($data);
  754. $this->parseFromJsonStream($input, $ignore_unknown);
  755. }
  756. /**
  757. * @ignore
  758. */
  759. public function parseFromStream($input)
  760. {
  761. while (true) {
  762. $tag = $input->readTag();
  763. // End of input. This is a valid place to end, so return true.
  764. if ($tag === 0) {
  765. return true;
  766. }
  767. $number = GPBWire::getTagFieldNumber($tag);
  768. $field = $this->desc->getFieldByNumber($number);
  769. $this->parseFieldFromStream($tag, $input, $field);
  770. }
  771. }
  772. private function convertJsonValueToProtoValue(
  773. $value,
  774. $field,
  775. $ignore_unknown,
  776. $is_map_key = false)
  777. {
  778. switch ($field->getType()) {
  779. case GPBType::MESSAGE:
  780. $klass = $field->getMessageType()->getClass();
  781. $submsg = new $klass;
  782. if (is_a($submsg, "Google\Protobuf\Duration")) {
  783. if (is_null($value)) {
  784. return $this->defaultValue($field);
  785. } else if (!is_string($value)) {
  786. throw new GPBDecodeException("Expect string.");
  787. }
  788. return GPBUtil::parseDuration($value);
  789. } else if ($field->isTimestamp()) {
  790. if (is_null($value)) {
  791. return $this->defaultValue($field);
  792. } else if (!is_string($value)) {
  793. throw new GPBDecodeException("Expect string.");
  794. }
  795. try {
  796. $timestamp = GPBUtil::parseTimestamp($value);
  797. } catch (\Exception $e) {
  798. throw new GPBDecodeException(
  799. "Invalid RFC 3339 timestamp: ".$e->getMessage());
  800. }
  801. $submsg->setSeconds($timestamp->getSeconds());
  802. $submsg->setNanos($timestamp->getNanos());
  803. } else if (is_a($submsg, "Google\Protobuf\FieldMask")) {
  804. if (is_null($value)) {
  805. return $this->defaultValue($field);
  806. }
  807. try {
  808. return GPBUtil::parseFieldMask($value);
  809. } catch (\Exception $e) {
  810. throw new GPBDecodeException(
  811. "Invalid FieldMask: ".$e->getMessage());
  812. }
  813. } else {
  814. if (is_null($value) &&
  815. !is_a($submsg, "Google\Protobuf\Value")) {
  816. return $this->defaultValue($field);
  817. }
  818. if (GPBUtil::hasSpecialJsonMapping($submsg)) {
  819. } elseif (!is_object($value) && !is_array($value)) {
  820. throw new GPBDecodeException("Expect message.");
  821. }
  822. $submsg->mergeFromJsonArray($value, $ignore_unknown);
  823. }
  824. return $submsg;
  825. case GPBType::ENUM:
  826. if (is_null($value)) {
  827. return $this->defaultValue($field);
  828. }
  829. if (is_integer($value)) {
  830. return $value;
  831. }
  832. $enum_value = $field->getEnumType()->getValueByName($value);
  833. if (!is_null($enum_value)) {
  834. return $enum_value->getNumber();
  835. } else if ($ignore_unknown) {
  836. return $this->defaultValue($field);
  837. } else {
  838. throw new GPBDecodeException(
  839. "Enum field only accepts integer or enum value name");
  840. }
  841. case GPBType::STRING:
  842. if (is_null($value)) {
  843. return $this->defaultValue($field);
  844. }
  845. if (is_numeric($value)) {
  846. return strval($value);
  847. }
  848. if (!is_string($value)) {
  849. throw new GPBDecodeException(
  850. "String field only accepts string value");
  851. }
  852. return $value;
  853. case GPBType::BYTES:
  854. if (is_null($value)) {
  855. return $this->defaultValue($field);
  856. }
  857. if (!is_string($value)) {
  858. throw new GPBDecodeException(
  859. "Byte field only accepts string value");
  860. }
  861. $proto_value = base64_decode($value, true);
  862. if ($proto_value === false) {
  863. throw new GPBDecodeException("Invalid base64 characters");
  864. }
  865. return $proto_value;
  866. case GPBType::BOOL:
  867. if (is_null($value)) {
  868. return $this->defaultValue($field);
  869. }
  870. if ($is_map_key) {
  871. if ($value === "true") {
  872. return true;
  873. }
  874. if ($value === "false") {
  875. return false;
  876. }
  877. throw new GPBDecodeException(
  878. "Bool field only accepts bool value");
  879. }
  880. if (!is_bool($value)) {
  881. throw new GPBDecodeException(
  882. "Bool field only accepts bool value");
  883. }
  884. return $value;
  885. case GPBType::FLOAT:
  886. case GPBType::DOUBLE:
  887. if (is_null($value)) {
  888. return $this->defaultValue($field);
  889. }
  890. if ($value === "Infinity") {
  891. return INF;
  892. }
  893. if ($value === "-Infinity") {
  894. return -INF;
  895. }
  896. if ($value === "NaN") {
  897. return NAN;
  898. }
  899. return $value;
  900. case GPBType::INT32:
  901. case GPBType::SINT32:
  902. case GPBType::SFIXED32:
  903. if (is_null($value)) {
  904. return $this->defaultValue($field);
  905. }
  906. if (!is_numeric($value)) {
  907. throw new GPBDecodeException(
  908. "Invalid data type for int32 field");
  909. }
  910. if (is_string($value) && trim($value) !== $value) {
  911. throw new GPBDecodeException(
  912. "Invalid data type for int32 field");
  913. }
  914. if (bccomp($value, "2147483647") > 0) {
  915. throw new GPBDecodeException(
  916. "Int32 too large");
  917. }
  918. if (bccomp($value, "-2147483648") < 0) {
  919. throw new GPBDecodeException(
  920. "Int32 too small");
  921. }
  922. return $value;
  923. case GPBType::UINT32:
  924. case GPBType::FIXED32:
  925. if (is_null($value)) {
  926. return $this->defaultValue($field);
  927. }
  928. if (!is_numeric($value)) {
  929. throw new GPBDecodeException(
  930. "Invalid data type for uint32 field");
  931. }
  932. if (is_string($value) && trim($value) !== $value) {
  933. throw new GPBDecodeException(
  934. "Invalid data type for int32 field");
  935. }
  936. if (bccomp($value, 4294967295) > 0) {
  937. throw new GPBDecodeException(
  938. "Uint32 too large");
  939. }
  940. return $value;
  941. case GPBType::INT64:
  942. case GPBType::SINT64:
  943. case GPBType::SFIXED64:
  944. if (is_null($value)) {
  945. return $this->defaultValue($field);
  946. }
  947. if (!is_numeric($value)) {
  948. throw new GPBDecodeException(
  949. "Invalid data type for int64 field");
  950. }
  951. if (is_string($value) && trim($value) !== $value) {
  952. throw new GPBDecodeException(
  953. "Invalid data type for int64 field");
  954. }
  955. if (bccomp($value, "9223372036854775807") > 0) {
  956. throw new GPBDecodeException(
  957. "Int64 too large");
  958. }
  959. if (bccomp($value, "-9223372036854775808") < 0) {
  960. throw new GPBDecodeException(
  961. "Int64 too small");
  962. }
  963. return $value;
  964. case GPBType::UINT64:
  965. case GPBType::FIXED64:
  966. if (is_null($value)) {
  967. return $this->defaultValue($field);
  968. }
  969. if (!is_numeric($value)) {
  970. throw new GPBDecodeException(
  971. "Invalid data type for int64 field");
  972. }
  973. if (is_string($value) && trim($value) !== $value) {
  974. throw new GPBDecodeException(
  975. "Invalid data type for int64 field");
  976. }
  977. if (bccomp($value, "18446744073709551615") > 0) {
  978. throw new GPBDecodeException(
  979. "Uint64 too large");
  980. }
  981. if (bccomp($value, "9223372036854775807") > 0) {
  982. $value = bcsub($value, "18446744073709551616");
  983. }
  984. return $value;
  985. default:
  986. return $value;
  987. }
  988. }
  989. /**
  990. * Populates the message from a user-supplied PHP array. Array keys
  991. * correspond to Message properties and nested message properties.
  992. *
  993. * Example:
  994. * ```
  995. * $message->mergeFromArray([
  996. * 'name' => 'This is a message name',
  997. * 'interval' => [
  998. * 'startTime' => time() - 60,
  999. * 'endTime' => time(),
  1000. * ]
  1001. * ]);
  1002. * ```
  1003. *
  1004. * This method will trigger an error if it is passed data that cannot
  1005. * be converted to the correct type. For example, a StringValue field
  1006. * must receive data that is either a string or a StringValue object.
  1007. *
  1008. * @param array $array An array containing message properties and values.
  1009. * @return null.
  1010. */
  1011. protected function mergeFromArray(array $array)
  1012. {
  1013. // Just call the setters for the field names
  1014. foreach ($array as $key => $value) {
  1015. $field = $this->desc->getFieldByName($key);
  1016. if (is_null($field)) {
  1017. throw new \UnexpectedValueException(
  1018. 'Invalid message property: ' . $key);
  1019. }
  1020. $setter = $field->getSetter();
  1021. if ($field->isMap()) {
  1022. $valueField = $field->getMessageType()->getFieldByName('value');
  1023. if (!is_null($valueField) && $valueField->isWrapperType()) {
  1024. self::normalizeArrayElementsToMessageType($value, $valueField->getMessageType()->getClass());
  1025. }
  1026. } elseif ($field->isWrapperType()) {
  1027. $class = $field->getMessageType()->getClass();
  1028. if ($field->isRepeated()) {
  1029. self::normalizeArrayElementsToMessageType($value, $class);
  1030. } else {
  1031. self::normalizeToMessageType($value, $class);
  1032. }
  1033. }
  1034. $this->$setter($value);
  1035. }
  1036. }
  1037. /**
  1038. * Tries to normalize the elements in $value into a provided protobuf
  1039. * wrapper type $class. If $value is any type other than array, we do
  1040. * not do any conversion, and instead rely on the existing protobuf
  1041. * type checking. If $value is an array, we process each element and
  1042. * try to convert it to an instance of $class.
  1043. *
  1044. * @param mixed $value The array of values to normalize.
  1045. * @param string $class The expected wrapper class name
  1046. */
  1047. private static function normalizeArrayElementsToMessageType(&$value, $class)
  1048. {
  1049. if (!is_array($value)) {
  1050. // In the case that $value is not an array, we do not want to
  1051. // attempt any conversion. Note that this includes the cases
  1052. // when $value is a RepeatedField of MapField. In those cases,
  1053. // we do not need to convert the elements, as they should
  1054. // already be the correct types.
  1055. return;
  1056. } else {
  1057. // Normalize each element in the array.
  1058. foreach ($value as $key => &$elementValue) {
  1059. self::normalizeToMessageType($elementValue, $class);
  1060. }
  1061. }
  1062. }
  1063. /**
  1064. * Tries to normalize $value into a provided protobuf wrapper type $class.
  1065. * If $value is any type other than an object, we attempt to construct an
  1066. * instance of $class and assign $value to it using the setValue method
  1067. * shared by all wrapper types.
  1068. *
  1069. * This method will raise an error if it receives a type that cannot be
  1070. * assigned to the wrapper type via setValue.
  1071. *
  1072. * @param mixed $value The value to normalize.
  1073. * @param string $class The expected wrapper class name
  1074. */
  1075. private static function normalizeToMessageType(&$value, $class)
  1076. {
  1077. if (is_null($value) || is_object($value)) {
  1078. // This handles the case that $value is an instance of $class. We
  1079. // choose not to do any more strict checking here, relying on the
  1080. // existing type checking done by GPBUtil.
  1081. return;
  1082. } else {
  1083. // Try to instantiate $class and set the value
  1084. try {
  1085. $msg = new $class;
  1086. $msg->setValue($value);
  1087. $value = $msg;
  1088. return;
  1089. } catch (\Exception $exception) {
  1090. trigger_error(
  1091. "Error normalizing value to type '$class': " . $exception->getMessage(),
  1092. E_USER_ERROR
  1093. );
  1094. }
  1095. }
  1096. }
  1097. protected function mergeFromJsonArray($array, $ignore_unknown)
  1098. {
  1099. if (is_a($this, "Google\Protobuf\Any")) {
  1100. $this->clear();
  1101. $this->setTypeUrl($array["@type"]);
  1102. $msg = $this->unpack();
  1103. if (GPBUtil::hasSpecialJsonMapping($msg)) {
  1104. $msg->mergeFromJsonArray($array["value"], $ignore_unknown);
  1105. } else {
  1106. unset($array["@type"]);
  1107. $msg->mergeFromJsonArray($array, $ignore_unknown);
  1108. }
  1109. $this->setValue($msg->serializeToString());
  1110. return;
  1111. }
  1112. if (is_a($this, "Google\Protobuf\DoubleValue") ||
  1113. is_a($this, "Google\Protobuf\FloatValue") ||
  1114. is_a($this, "Google\Protobuf\Int64Value") ||
  1115. is_a($this, "Google\Protobuf\UInt64Value") ||
  1116. is_a($this, "Google\Protobuf\Int32Value") ||
  1117. is_a($this, "Google\Protobuf\UInt32Value") ||
  1118. is_a($this, "Google\Protobuf\BoolValue") ||
  1119. is_a($this, "Google\Protobuf\StringValue")) {
  1120. $this->setValue($array);
  1121. return;
  1122. }
  1123. if (is_a($this, "Google\Protobuf\BytesValue")) {
  1124. $this->setValue(base64_decode($array));
  1125. return;
  1126. }
  1127. if (is_a($this, "Google\Protobuf\Duration")) {
  1128. $this->mergeFrom(GPBUtil::parseDuration($array));
  1129. return;
  1130. }
  1131. if (is_a($this, "Google\Protobuf\FieldMask")) {
  1132. $this->mergeFrom(GPBUtil::parseFieldMask($array));
  1133. return;
  1134. }
  1135. if (is_a($this, "Google\Protobuf\Timestamp")) {
  1136. $this->mergeFrom(GPBUtil::parseTimestamp($array));
  1137. return;
  1138. }
  1139. if (is_a($this, "Google\Protobuf\Struct")) {
  1140. $fields = $this->getFields();
  1141. foreach($array as $key => $value) {
  1142. $v = new Value();
  1143. $v->mergeFromJsonArray($value, $ignore_unknown);
  1144. $fields[$key] = $v;
  1145. }
  1146. }
  1147. if (is_a($this, "Google\Protobuf\Value")) {
  1148. if (is_bool($array)) {
  1149. $this->setBoolValue($array);
  1150. } elseif (is_string($array)) {
  1151. $this->setStringValue($array);
  1152. } elseif (is_null($array)) {
  1153. $this->setNullValue(0);
  1154. } elseif (is_double($array) || is_integer($array)) {
  1155. $this->setNumberValue($array);
  1156. } elseif (is_array($array)) {
  1157. if (array_values($array) !== $array) {
  1158. // Associative array
  1159. $struct_value = $this->getStructValue();
  1160. if (is_null($struct_value)) {
  1161. $struct_value = new Struct();
  1162. $this->setStructValue($struct_value);
  1163. }
  1164. foreach ($array as $key => $v) {
  1165. $value = new Value();
  1166. $value->mergeFromJsonArray($v, $ignore_unknown);
  1167. $values = $struct_value->getFields();
  1168. $values[$key]= $value;
  1169. }
  1170. } else {
  1171. // Array
  1172. $list_value = $this->getListValue();
  1173. if (is_null($list_value)) {
  1174. $list_value = new ListValue();
  1175. $this->setListValue($list_value);
  1176. }
  1177. foreach ($array as $v) {
  1178. $value = new Value();
  1179. $value->mergeFromJsonArray($v, $ignore_unknown);
  1180. $values = $list_value->getValues();
  1181. $values[]= $value;
  1182. }
  1183. }
  1184. } else {
  1185. throw new GPBDecodeException("Invalid type for Value.");
  1186. }
  1187. return;
  1188. }
  1189. $this->mergeFromArrayJsonImpl($array, $ignore_unknown);
  1190. }
  1191. private function mergeFromArrayJsonImpl($array, $ignore_unknown)
  1192. {
  1193. foreach ($array as $key => $value) {
  1194. $field = $this->desc->getFieldByJsonName($key);
  1195. if (is_null($field)) {
  1196. $field = $this->desc->getFieldByName($key);
  1197. if (is_null($field)) {
  1198. continue;
  1199. }
  1200. }
  1201. if ($field->isMap()) {
  1202. if (is_null($value)) {
  1203. continue;
  1204. }
  1205. $key_field = $field->getMessageType()->getFieldByNumber(1);
  1206. $value_field = $field->getMessageType()->getFieldByNumber(2);
  1207. foreach ($value as $tmp_key => $tmp_value) {
  1208. if (is_null($tmp_value)) {
  1209. throw new \Exception(
  1210. "Map value field element cannot be null.");
  1211. }
  1212. $proto_key = $this->convertJsonValueToProtoValue(
  1213. $tmp_key,
  1214. $key_field,
  1215. $ignore_unknown,
  1216. true);
  1217. $proto_value = $this->convertJsonValueToProtoValue(
  1218. $tmp_value,
  1219. $value_field,
  1220. $ignore_unknown);
  1221. self::kvUpdateHelper($field, $proto_key, $proto_value);
  1222. }
  1223. } else if ($field->isRepeated()) {
  1224. if (is_null($value)) {
  1225. continue;
  1226. }
  1227. foreach ($value as $tmp) {
  1228. if (is_null($tmp)) {
  1229. throw new \Exception(
  1230. "Repeated field elements cannot be null.");
  1231. }
  1232. $proto_value = $this->convertJsonValueToProtoValue(
  1233. $tmp,
  1234. $field,
  1235. $ignore_unknown);
  1236. self::appendHelper($field, $proto_value);
  1237. }
  1238. } else {
  1239. $setter = $field->getSetter();
  1240. $proto_value = $this->convertJsonValueToProtoValue(
  1241. $value,
  1242. $field,
  1243. $ignore_unknown);
  1244. if ($field->getType() === GPBType::MESSAGE) {
  1245. if (is_null($proto_value)) {
  1246. continue;
  1247. }
  1248. $getter = $field->getGetter();
  1249. $submsg = $this->$getter();
  1250. if (!is_null($submsg)) {
  1251. $submsg->mergeFrom($proto_value);
  1252. continue;
  1253. }
  1254. }
  1255. $this->$setter($proto_value);
  1256. }
  1257. }
  1258. }
  1259. /**
  1260. * @ignore
  1261. */
  1262. public function parseFromJsonStream($input, $ignore_unknown)
  1263. {
  1264. $array = json_decode($input->getData(), true, 512, JSON_BIGINT_AS_STRING);
  1265. if ($this instanceof \Google\Protobuf\ListValue) {
  1266. $array = ["values"=>$array];
  1267. }
  1268. if (is_null($array)) {
  1269. if ($this instanceof \Google\Protobuf\Value) {
  1270. $this->setNullValue(\Google\Protobuf\NullValue::NULL_VALUE);
  1271. return;
  1272. } else {
  1273. throw new GPBDecodeException(
  1274. "Cannot decode json string: " . $input->getData());
  1275. }
  1276. }
  1277. try {
  1278. $this->mergeFromJsonArray($array, $ignore_unknown);
  1279. } catch (\Exception $e) {
  1280. throw new GPBDecodeException($e->getMessage());
  1281. }
  1282. }
  1283. /**
  1284. * @ignore
  1285. */
  1286. private function serializeSingularFieldToStream($field, &$output)
  1287. {
  1288. if (!$this->existField($field)) {
  1289. return true;
  1290. }
  1291. $getter = $field->getGetter();
  1292. $value = $this->$getter();
  1293. if (!GPBWire::serializeFieldToStream($value, $field, true, $output)) {
  1294. return false;
  1295. }
  1296. return true;
  1297. }
  1298. /**
  1299. * @ignore
  1300. */
  1301. private function serializeRepeatedFieldToStream($field, &$output)
  1302. {
  1303. $getter = $field->getGetter();
  1304. $values = $this->$getter();
  1305. $count = count($values);
  1306. if ($count === 0) {
  1307. return true;
  1308. }
  1309. $packed = $field->getPacked();
  1310. if ($packed) {
  1311. if (!GPBWire::writeTag(
  1312. $output,
  1313. GPBWire::makeTag($field->getNumber(), GPBType::STRING))) {
  1314. return false;
  1315. }
  1316. $size = 0;
  1317. foreach ($values as $value) {
  1318. $size += $this->fieldDataOnlyByteSize($field, $value);
  1319. }
  1320. if (!$output->writeVarint32($size, true)) {
  1321. return false;
  1322. }
  1323. }
  1324. foreach ($values as $value) {
  1325. if (!GPBWire::serializeFieldToStream(
  1326. $value,
  1327. $field,
  1328. !$packed,
  1329. $output)) {
  1330. return false;
  1331. }
  1332. }
  1333. return true;
  1334. }
  1335. /**
  1336. * @ignore
  1337. */
  1338. private function serializeMapFieldToStream($field, $output)
  1339. {
  1340. $getter = $field->getGetter();
  1341. $values = $this->$getter();
  1342. $count = count($values);
  1343. if ($count === 0) {
  1344. return true;
  1345. }
  1346. foreach ($values as $key => $value) {
  1347. $map_entry = new MapEntry($field->getMessageType());
  1348. $map_entry->setKey($key);
  1349. $map_entry->setValue($value);
  1350. if (!GPBWire::serializeFieldToStream(
  1351. $map_entry,
  1352. $field,
  1353. true,
  1354. $output)) {
  1355. return false;
  1356. }
  1357. }
  1358. return true;
  1359. }
  1360. /**
  1361. * @ignore
  1362. */
  1363. private function serializeFieldToStream(&$output, $field)
  1364. {
  1365. if ($field->isMap()) {
  1366. return $this->serializeMapFieldToStream($field, $output);
  1367. } elseif ($field->isRepeated()) {
  1368. return $this->serializeRepeatedFieldToStream($field, $output);
  1369. } else {
  1370. return $this->serializeSingularFieldToStream($field, $output);
  1371. }
  1372. }
  1373. /**
  1374. * @ignore
  1375. */
  1376. private function serializeFieldToJsonStream(&$output, $field)
  1377. {
  1378. $getter = $field->getGetter();
  1379. $values = $this->$getter();
  1380. return GPBJsonWire::serializeFieldToStream(
  1381. $values, $field, $output, !GPBUtil::hasSpecialJsonMapping($this));
  1382. }
  1383. /**
  1384. * @ignore
  1385. */
  1386. public function serializeToStream(&$output)
  1387. {
  1388. $fields = $this->desc->getField();
  1389. foreach ($fields as $field) {
  1390. if (!$this->serializeFieldToStream($output, $field)) {
  1391. return false;
  1392. }
  1393. }
  1394. $output->writeRaw($this->unknown, strlen($this->unknown));
  1395. return true;
  1396. }
  1397. /**
  1398. * @ignore
  1399. */
  1400. public function serializeToJsonStream(&$output)
  1401. {
  1402. if (is_a($this, 'Google\Protobuf\Any')) {
  1403. $output->writeRaw("{", 1);
  1404. $type_field = $this->desc->getFieldByNumber(1);
  1405. $value_msg = $this->unpack();
  1406. // Serialize type url.
  1407. $output->writeRaw("\"@type\":", 8);
  1408. $output->writeRaw("\"", 1);
  1409. $output->writeRaw($this->getTypeUrl(), strlen($this->getTypeUrl()));
  1410. $output->writeRaw("\"", 1);
  1411. // Serialize value
  1412. if (GPBUtil::hasSpecialJsonMapping($value_msg)) {
  1413. $output->writeRaw(",\"value\":", 9);
  1414. $value_msg->serializeToJsonStream($output);
  1415. } else {
  1416. $value_fields = $value_msg->desc->getField();
  1417. foreach ($value_fields as $field) {
  1418. if ($value_msg->existField($field)) {
  1419. $output->writeRaw(",", 1);
  1420. if (!$value_msg->serializeFieldToJsonStream($output, $field)) {
  1421. return false;
  1422. }
  1423. }
  1424. }
  1425. }
  1426. $output->writeRaw("}", 1);
  1427. } elseif (is_a($this, 'Google\Protobuf\FieldMask')) {
  1428. $field_mask = GPBUtil::formatFieldMask($this);
  1429. $output->writeRaw("\"", 1);
  1430. $output->writeRaw($field_mask, strlen($field_mask));
  1431. $output->writeRaw("\"", 1);
  1432. } elseif (is_a($this, 'Google\Protobuf\Duration')) {
  1433. $duration = GPBUtil::formatDuration($this) . "s";
  1434. $output->writeRaw("\"", 1);
  1435. $output->writeRaw($duration, strlen($duration));
  1436. $output->writeRaw("\"", 1);
  1437. } elseif (get_class($this) === 'Google\Protobuf\Timestamp') {
  1438. $timestamp = GPBUtil::formatTimestamp($this);
  1439. $timestamp = json_encode($timestamp);
  1440. $output->writeRaw($timestamp, strlen($timestamp));
  1441. } elseif (get_class($this) === 'Google\Protobuf\ListValue') {
  1442. $field = $this->desc->getField()[1];
  1443. if (!$this->existField($field)) {
  1444. $output->writeRaw("[]", 2);
  1445. } else {
  1446. if (!$this->serializeFieldToJsonStream($output, $field)) {
  1447. return false;
  1448. }
  1449. }
  1450. } elseif (get_class($this) === 'Google\Protobuf\Struct') {
  1451. $field = $this->desc->getField()[1];
  1452. if (!$this->existField($field)) {
  1453. $output->writeRaw("{}", 2);
  1454. } else {
  1455. if (!$this->serializeFieldToJsonStream($output, $field)) {
  1456. return false;
  1457. }
  1458. }
  1459. } else {
  1460. if (!GPBUtil::hasSpecialJsonMapping($this)) {
  1461. $output->writeRaw("{", 1);
  1462. }
  1463. $fields = $this->desc->getField();
  1464. $first = true;
  1465. foreach ($fields as $field) {
  1466. if ($this->existField($field) ||
  1467. GPBUtil::hasJsonValue($this)) {
  1468. if ($first) {
  1469. $first = false;
  1470. } else {
  1471. $output->writeRaw(",", 1);
  1472. }
  1473. if (!$this->serializeFieldToJsonStream($output, $field)) {
  1474. return false;
  1475. }
  1476. }
  1477. }
  1478. if (!GPBUtil::hasSpecialJsonMapping($this)) {
  1479. $output->writeRaw("}", 1);
  1480. }
  1481. }
  1482. return true;
  1483. }
  1484. /**
  1485. * Serialize the message to string.
  1486. * @return string Serialized binary protobuf data.
  1487. */
  1488. public function serializeToString()
  1489. {
  1490. $output = new CodedOutputStream($this->byteSize());
  1491. $this->serializeToStream($output);
  1492. return $output->getData();
  1493. }
  1494. /**
  1495. * Serialize the message to json string.
  1496. * @return string Serialized json protobuf data.
  1497. */
  1498. public function serializeToJsonString()
  1499. {
  1500. $output = new CodedOutputStream($this->jsonByteSize());
  1501. $this->serializeToJsonStream($output);
  1502. return $output->getData();
  1503. }
  1504. /**
  1505. * @ignore
  1506. */
  1507. private function existField($field)
  1508. {
  1509. $getter = $field->getGetter();
  1510. $hazzer = "has" . substr($getter, 3);
  1511. if (method_exists($this, $hazzer)) {
  1512. return $this->$hazzer();
  1513. } else if ($field->getOneofIndex() !== -1) {
  1514. // For old generated code, which does not have hazzers for oneof
  1515. // fields.
  1516. $oneof = $this->desc->getOneofDecl()[$field->getOneofIndex()];
  1517. $oneof_name = $oneof->getName();
  1518. return $this->$oneof_name->getNumber() === $field->getNumber();
  1519. }
  1520. $values = $this->$getter();
  1521. if ($field->isMap()) {
  1522. return count($values) !== 0;
  1523. } elseif ($field->isRepeated()) {
  1524. return count($values) !== 0;
  1525. } else {
  1526. return $values !== $this->defaultValue($field);
  1527. }
  1528. }
  1529. /**
  1530. * @ignore
  1531. */
  1532. private function repeatedFieldDataOnlyByteSize($field)
  1533. {
  1534. $size = 0;
  1535. $getter = $field->getGetter();
  1536. $values = $this->$getter();
  1537. $count = count($values);
  1538. if ($count !== 0) {
  1539. $size += $count * GPBWire::tagSize($field);
  1540. foreach ($values as $value) {
  1541. $size += $this->singularFieldDataOnlyByteSize($field);
  1542. }
  1543. }
  1544. }
  1545. /**
  1546. * @ignore
  1547. */
  1548. private function fieldDataOnlyByteSize($field, $value)
  1549. {
  1550. $size = 0;
  1551. switch ($field->getType()) {
  1552. case GPBType::BOOL:
  1553. $size += 1;
  1554. break;
  1555. case GPBType::FLOAT:
  1556. case GPBType::FIXED32:
  1557. case GPBType::SFIXED32:
  1558. $size += 4;
  1559. break;
  1560. case GPBType::DOUBLE:
  1561. case GPBType::FIXED64:
  1562. case GPBType::SFIXED64:
  1563. $size += 8;
  1564. break;
  1565. case GPBType::INT32:
  1566. case GPBType::ENUM:
  1567. $size += GPBWire::varint32Size($value, true);
  1568. break;
  1569. case GPBType::UINT32:
  1570. $size += GPBWire::varint32Size($value);
  1571. break;
  1572. case GPBType::UINT64:
  1573. case GPBType::INT64:
  1574. $size += GPBWire::varint64Size($value);
  1575. break;
  1576. case GPBType::SINT32:
  1577. $size += GPBWire::sint32Size($value);
  1578. break;
  1579. case GPBType::SINT64:
  1580. $size += GPBWire::sint64Size($value);
  1581. break;
  1582. case GPBType::STRING:
  1583. case GPBType::BYTES:
  1584. $size += strlen($value);
  1585. $size += GPBWire::varint32Size($size);
  1586. break;
  1587. case GPBType::MESSAGE:
  1588. $size += $value->byteSize();
  1589. $size += GPBWire::varint32Size($size);
  1590. break;
  1591. case GPBType::GROUP:
  1592. // TODO(teboring): Add support.
  1593. user_error("Unsupported type.");
  1594. break;
  1595. default:
  1596. user_error("Unsupported type.");
  1597. return 0;
  1598. }
  1599. return $size;
  1600. }
  1601. /**
  1602. * @ignore
  1603. */
  1604. private function fieldDataOnlyJsonByteSize($field, $value)
  1605. {
  1606. $size = 0;
  1607. switch ($field->getType()) {
  1608. case GPBType::SFIXED32:
  1609. case GPBType::SINT32:
  1610. case GPBType::INT32:
  1611. $size += strlen(strval($value));
  1612. break;
  1613. case GPBType::FIXED32:
  1614. case GPBType::UINT32:
  1615. if ($value < 0) {
  1616. $value = bcadd($value, "4294967296");
  1617. }
  1618. $size += strlen(strval($value));
  1619. break;
  1620. case GPBType::FIXED64:
  1621. case GPBType::UINT64:
  1622. if ($value < 0) {
  1623. $value = bcadd($value, "18446744073709551616");
  1624. }
  1625. // Intentional fall through.
  1626. case GPBType::SFIXED64:
  1627. case GPBType::INT64:
  1628. case GPBType::SINT64:
  1629. $size += 2; // size for ""
  1630. $size += strlen(strval($value));
  1631. break;
  1632. case GPBType::FLOAT:
  1633. if (is_nan($value)) {
  1634. $size += strlen("NaN") + 2;
  1635. } elseif ($value === INF) {
  1636. $size += strlen("Infinity") + 2;
  1637. } elseif ($value === -INF) {
  1638. $size += strlen("-Infinity") + 2;
  1639. } else {
  1640. $size += strlen(sprintf("%.8g", $value));
  1641. }
  1642. break;
  1643. case GPBType::DOUBLE:
  1644. if (is_nan($value)) {
  1645. $size += strlen("NaN") + 2;
  1646. } elseif ($value === INF) {
  1647. $size += strlen("Infinity") + 2;
  1648. } elseif ($value === -INF) {
  1649. $size += strlen("-Infinity") + 2;
  1650. } else {
  1651. $size += strlen(sprintf("%.17g", $value));
  1652. }
  1653. break;
  1654. case GPBType::ENUM:
  1655. $enum_desc = $field->getEnumType();
  1656. if ($enum_desc->getClass() === "Google\Protobuf\NullValue") {
  1657. $size += 4;
  1658. break;
  1659. }
  1660. $enum_value_desc = $enum_desc->getValueByNumber($value);
  1661. if (!is_null($enum_value_desc)) {
  1662. $size += 2; // size for ""
  1663. $size += strlen($enum_value_desc->getName());
  1664. } else {
  1665. $str_value = strval($value);
  1666. $size += strlen($str_value);
  1667. }
  1668. break;
  1669. case GPBType::BOOL:
  1670. if ($value) {
  1671. $size += 4;
  1672. } else {
  1673. $size += 5;
  1674. }
  1675. break;
  1676. case GPBType::STRING:
  1677. $value = json_encode($value, JSON_UNESCAPED_UNICODE);
  1678. $size += strlen($value);
  1679. break;
  1680. case GPBType::BYTES:
  1681. # if (is_a($this, "Google\Protobuf\BytesValue")) {
  1682. # $size += strlen(json_encode($value));
  1683. # } else {
  1684. # $size += strlen(base64_encode($value));
  1685. # $size += 2; // size for \"\"
  1686. # }
  1687. $size += strlen(base64_encode($value));
  1688. $size += 2; // size for \"\"
  1689. break;
  1690. case GPBType::MESSAGE:
  1691. $size += $value->jsonByteSize();
  1692. break;
  1693. # case GPBType::GROUP:
  1694. # // TODO(teboring): Add support.
  1695. # user_error("Unsupported type.");
  1696. # break;
  1697. default:
  1698. user_error("Unsupported type " . $field->getType());
  1699. return 0;
  1700. }
  1701. return $size;
  1702. }
  1703. /**
  1704. * @ignore
  1705. */
  1706. private function fieldByteSize($field)
  1707. {
  1708. $size = 0;
  1709. if ($field->isMap()) {
  1710. $getter = $field->getGetter();
  1711. $values = $this->$getter();
  1712. $count = count($values);
  1713. if ($count !== 0) {
  1714. $size += $count * GPBWire::tagSize($field);
  1715. $message_type = $field->getMessageType();
  1716. $key_field = $message_type->getFieldByNumber(1);
  1717. $value_field = $message_type->getFieldByNumber(2);
  1718. foreach ($values as $key => $value) {
  1719. $data_size = 0;
  1720. if ($key != $this->defaultValue($key_field)) {
  1721. $data_size += $this->fieldDataOnlyByteSize(
  1722. $key_field,
  1723. $key);
  1724. $data_size += GPBWire::tagSize($key_field);
  1725. }
  1726. if ($value != $this->defaultValue($value_field)) {
  1727. $data_size += $this->fieldDataOnlyByteSize(
  1728. $value_field,
  1729. $value);
  1730. $data_size += GPBWire::tagSize($value_field);
  1731. }
  1732. $size += GPBWire::varint32Size($data_size) + $data_size;
  1733. }
  1734. }
  1735. } elseif ($field->isRepeated()) {
  1736. $getter = $field->getGetter();
  1737. $values = $this->$getter();
  1738. $count = count($values);
  1739. if ($count !== 0) {
  1740. if ($field->getPacked()) {
  1741. $data_size = 0;
  1742. foreach ($values as $value) {
  1743. $data_size += $this->fieldDataOnlyByteSize($field, $value);
  1744. }
  1745. $size += GPBWire::tagSize($field);
  1746. $size += GPBWire::varint32Size($data_size);
  1747. $size += $data_size;
  1748. } else {
  1749. $size += $count * GPBWire::tagSize($field);
  1750. foreach ($values as $value) {
  1751. $size += $this->fieldDataOnlyByteSize($field, $value);
  1752. }
  1753. }
  1754. }
  1755. } elseif ($this->existField($field)) {
  1756. $size += GPBWire::tagSize($field);
  1757. $getter = $field->getGetter();
  1758. $value = $this->$getter();
  1759. $size += $this->fieldDataOnlyByteSize($field, $value);
  1760. }
  1761. return $size;
  1762. }
  1763. /**
  1764. * @ignore
  1765. */
  1766. private function fieldJsonByteSize($field)
  1767. {
  1768. $size = 0;
  1769. if ($field->isMap()) {
  1770. $getter = $field->getGetter();
  1771. $values = $this->$getter();
  1772. $count = count($values);
  1773. if ($count !== 0) {
  1774. if (!GPBUtil::hasSpecialJsonMapping($this)) {
  1775. $size += 3; // size for "\"\":".
  1776. $size += strlen($field->getJsonName()); // size for field name
  1777. }
  1778. $size += 2; // size for "{}".
  1779. $size += $count - 1; // size for commas
  1780. $getter = $field->getGetter();
  1781. $map_entry = $field->getMessageType();
  1782. $key_field = $map_entry->getFieldByNumber(1);
  1783. $value_field = $map_entry->getFieldByNumber(2);
  1784. switch ($key_field->getType()) {
  1785. case GPBType::STRING:
  1786. case GPBType::SFIXED64:
  1787. case GPBType::INT64:
  1788. case GPBType::SINT64:
  1789. case GPBType::FIXED64:
  1790. case GPBType::UINT64:
  1791. $additional_quote = false;
  1792. break;
  1793. default:
  1794. $additional_quote = true;
  1795. }
  1796. foreach ($values as $key => $value) {
  1797. if ($additional_quote) {
  1798. $size += 2; // size for ""
  1799. }
  1800. $size += $this->fieldDataOnlyJsonByteSize($key_field, $key);
  1801. $size += $this->fieldDataOnlyJsonByteSize($value_field, $value);
  1802. $size += 1; // size for :
  1803. }
  1804. }
  1805. } elseif ($field->isRepeated()) {
  1806. $getter = $field->getGetter();
  1807. $values = $this->$getter();
  1808. $count = count($values);
  1809. if ($count !== 0) {
  1810. if (!GPBUtil::hasSpecialJsonMapping($this)) {
  1811. $size += 3; // size for "\"\":".
  1812. $size += strlen($field->getJsonName()); // size for field name
  1813. }
  1814. $size += 2; // size for "[]".
  1815. $size += $count - 1; // size for commas
  1816. $getter = $field->getGetter();
  1817. foreach ($values as $value) {
  1818. $size += $this->fieldDataOnlyJsonByteSize($field, $value);
  1819. }
  1820. }
  1821. } elseif ($this->existField($field) || GPBUtil::hasJsonValue($this)) {
  1822. if (!GPBUtil::hasSpecialJsonMapping($this)) {
  1823. $size += 3; // size for "\"\":".
  1824. $size += strlen($field->getJsonName()); // size for field name
  1825. }
  1826. $getter = $field->getGetter();
  1827. $value = $this->$getter();
  1828. $size += $this->fieldDataOnlyJsonByteSize($field, $value);
  1829. }
  1830. return $size;
  1831. }
  1832. /**
  1833. * @ignore
  1834. */
  1835. public function byteSize()
  1836. {
  1837. $size = 0;
  1838. $fields = $this->desc->getField();
  1839. foreach ($fields as $field) {
  1840. $size += $this->fieldByteSize($field);
  1841. }
  1842. $size += strlen($this->unknown);
  1843. return $size;
  1844. }
  1845. private function appendHelper($field, $append_value)
  1846. {
  1847. $getter = $field->getGetter();
  1848. $setter = $field->getSetter();
  1849. $field_arr_value = $this->$getter();
  1850. $field_arr_value[] = $append_value;
  1851. if (!is_object($field_arr_value)) {
  1852. $this->$setter($field_arr_value);
  1853. }
  1854. }
  1855. private function kvUpdateHelper($field, $update_key, $update_value)
  1856. {
  1857. $getter = $field->getGetter();
  1858. $setter = $field->getSetter();
  1859. $field_arr_value = $this->$getter();
  1860. $field_arr_value[$update_key] = $update_value;
  1861. if (!is_object($field_arr_value)) {
  1862. $this->$setter($field_arr_value);
  1863. }
  1864. }
  1865. /**
  1866. * @ignore
  1867. */
  1868. public function jsonByteSize()
  1869. {
  1870. $size = 0;
  1871. if (is_a($this, 'Google\Protobuf\Any')) {
  1872. // Size for "{}".
  1873. $size += 2;
  1874. // Size for "\"@type\":".
  1875. $size += 8;
  1876. // Size for url. +2 for "" /.
  1877. $size += strlen($this->getTypeUrl()) + 2;
  1878. $value_msg = $this->unpack();
  1879. if (GPBUtil::hasSpecialJsonMapping($value_msg)) {
  1880. // Size for "\",value\":".
  1881. $size += 9;
  1882. $size += $value_msg->jsonByteSize();
  1883. } else {
  1884. // Size for value. +1 for comma, -2 for "{}".
  1885. $size += $value_msg->jsonByteSize() -1;
  1886. }
  1887. } elseif (get_class($this) === 'Google\Protobuf\FieldMask') {
  1888. $field_mask = GPBUtil::formatFieldMask($this);
  1889. $size += strlen($field_mask) + 2; // 2 for ""
  1890. } elseif (get_class($this) === 'Google\Protobuf\Duration') {
  1891. $duration = GPBUtil::formatDuration($this) . "s";
  1892. $size += strlen($duration) + 2; // 2 for ""
  1893. } elseif (get_class($this) === 'Google\Protobuf\Timestamp') {
  1894. $timestamp = GPBUtil::formatTimestamp($this);
  1895. $timestamp = json_encode($timestamp);
  1896. $size += strlen($timestamp);
  1897. } elseif (get_class($this) === 'Google\Protobuf\ListValue') {
  1898. $field = $this->desc->getField()[1];
  1899. if ($this->existField($field)) {
  1900. $field_size = $this->fieldJsonByteSize($field);
  1901. $size += $field_size;
  1902. } else {
  1903. // Size for "[]".
  1904. $size += 2;
  1905. }
  1906. } elseif (get_class($this) === 'Google\Protobuf\Struct') {
  1907. $field = $this->desc->getField()[1];
  1908. if ($this->existField($field)) {
  1909. $field_size = $this->fieldJsonByteSize($field);
  1910. $size += $field_size;
  1911. } else {
  1912. // Size for "{}".
  1913. $size += 2;
  1914. }
  1915. } else {
  1916. if (!GPBUtil::hasSpecialJsonMapping($this)) {
  1917. // Size for "{}".
  1918. $size += 2;
  1919. }
  1920. $fields = $this->desc->getField();
  1921. $count = 0;
  1922. foreach ($fields as $field) {
  1923. $field_size = $this->fieldJsonByteSize($field);
  1924. $size += $field_size;
  1925. if ($field_size != 0) {
  1926. $count++;
  1927. }
  1928. }
  1929. // size for comma
  1930. $size += $count > 0 ? ($count - 1) : 0;
  1931. }
  1932. return $size;
  1933. }
  1934. }