Example #1
0
 /**
  * Decode a Message from raw network data
  *
  * @param string $data The data string to decode
  * @return \LibDNS\Messages\Message
  * @throws \UnexpectedValueException When the packet data is invalid
  * @throws \InvalidArgumentException When a type subtype is unknown
  */
 public function decode($data)
 {
     $packet = $this->packetFactory->create($data);
     $decodingContext = $this->decodingContextFactory->create($packet);
     $message = $this->messageFactory->create();
     $this->decodeHeader($decodingContext, $message);
     $questionRecords = $message->getQuestionRecords();
     $expected = $decodingContext->getExpectedQuestionRecords();
     for ($i = 0; $i < $expected; $i++) {
         $questionRecords->add($this->decodeQuestionRecord($decodingContext));
     }
     $answerRecords = $message->getAnswerRecords();
     $expected = $decodingContext->getExpectedAnswerRecords();
     for ($i = 0; $i < $expected; $i++) {
         $answerRecords->add($this->decodeResourceRecord($decodingContext));
     }
     $authorityRecords = $message->getAuthorityRecords();
     $expected = $decodingContext->getExpectedAuthorityRecords();
     for ($i = 0; $i < $expected; $i++) {
         $authorityRecords->add($this->decodeResourceRecord($decodingContext));
     }
     $additionalRecords = $message->getAdditionalRecords();
     $expected = $decodingContext->getExpectedAdditionalRecords();
     for ($i = 0; $i < $expected; $i++) {
         $additionalRecords->add($this->decodeResourceRecord($decodingContext));
     }
     if ($packet->getBytesRemaining() !== 0) {
         throw new \UnexpectedValueException('Decode error: Unexpected data at end of packet');
     }
     return $message;
 }
Example #2
0
 /**
  * Encode a Message to raw network data
  *
  * @param \LibDNS\Messages\Message $message  The Message to encode
  * @param bool $compress Enable message compression
  * @return string
  */
 public function encode(Message $message, $compress = true)
 {
     $packet = $this->packetFactory->create();
     $encodingContext = $this->encodingContextFactory->create($packet, $compress);
     foreach ($message->getQuestionRecords() as $record) {
         /** @var \LibDNS\Records\Question $record */
         $this->encodeQuestionRecord($encodingContext, $record);
     }
     foreach ($message->getAnswerRecords() as $record) {
         /** @var \LibDNS\Records\Resource $record */
         $this->encodeResourceRecord($encodingContext, $record);
     }
     foreach ($message->getAuthorityRecords() as $record) {
         /** @var \LibDNS\Records\Resource $record */
         $this->encodeResourceRecord($encodingContext, $record);
     }
     foreach ($message->getAdditionalRecords() as $record) {
         /** @var \LibDNS\Records\Resource $record */
         $this->encodeResourceRecord($encodingContext, $record);
     }
     return $this->encodeHeader($encodingContext, $message) . $packet->read($packet->getLength());
 }