usingTemplates2.php 729 B

12345678910111213141516171819202122232425262728293031323334
  1. <?php
  2. require __DIR__ . "/../vendor/autoload.php";
  3. use BitWasp\Buffertools\Buffer;
  4. use BitWasp\Buffertools\Parser;
  5. use BitWasp\Buffertools\TemplateFactory;
  6. $structure = (object) [
  7. 'hash' => hash('sha256', 'abc'),
  8. 'message_id' => 9123,
  9. 'message' => "Hi there! What's up?"
  10. ];
  11. // Templates are read/write
  12. $template = (new TemplateFactory)
  13. ->bytestring(32)
  14. ->uint32()
  15. ->varstring()
  16. ->getTemplate();
  17. // Write the structure
  18. $binary = $template->write([
  19. Buffer::hex($structure->hash),
  20. $structure->message_id,
  21. new Buffer($structure->message)
  22. ]);
  23. echo $binary->getHex() . "\n";
  24. // Use the template to read resulting Buffer
  25. $parsed = $template->parse(new Parser($binary));
  26. print_r($parsed);