Message.php 69 KB

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