Encodes a given message

@param  MessageInterface $message
@return string
551459
public function encode(MessageInterface $message)
    {
        $json = parent::encode($message);

        return gzcompress($json, $this->compressionLevel);
    }
1198503
protected function headersAndBody(MessageInterface $message)
    {
        $string = '';

        foreach ($message->getHeaders() as $name => $values) {
            foreach ($values as $value) {
                $string .= $name.': '.$value."\n";
            }
        }

        $string .= "\n";
        $string .= (string) $message->getBody();

        return $string;
    }
717330
public function write($key, $message)
    {
        $message = strval($message);
        return (strlen($key) && strlen($message))
            ? $this->_getCipherOb($key)->encrypt($message)
            : '';
    }
1046820
public function writeMessage(\fpoirotte\Pssht\MessageInterface $message)
    {
        $logging = \Plop\Plop::getInstance();

        // Serialize the message.
        $encoder    = new \fpoirotte\Pssht\Wire\Encoder();
        $encoder->encodeBytes(chr($message::getMessageId()));
        $message->serialize($encoder);
        $payload    = $encoder->getBuffer()->get(0);
        $logging->debug('Sending payload: %s', array(\escape($payload)));

        // Compress the payload if necessary.
        $payload    = $this->compressor->update($payload);
        $size       = strlen($payload);
        $blockSize  = max(8, $this->encryptor->getBlockSize());

        // Compute padding requirements.
        // See http://api.libssh.org/rfc/PROTOCOL
        // for more information on EtM (Encrypt-then-MAC)
        // and RFCs 5116 & 5647 for AEAD & AES-GCM.
        if ($this->outMAC instanceof \fpoirotte\Pssht\MAC\OpensshCom\EtM\EtMInterface) {
            $padSize    = $blockSize - ((1 + $size) % $blockSize);
        } elseif ($this->encryptor instanceof \fpoirotte\Pssht\AEADInterface) {
            $padSize    = $blockSize - ((1 + $size) % $blockSize);
        } else {
            $padSize    = $blockSize - ((1 + 4 + $size) % $blockSize);
        }
        if ($padSize < 4) {
            $padSize = ($padSize + $blockSize) % 256;
        }
        $padding = openssl_random_pseudo_bytes($padSize);

        // Create the packet. Every content passed to $encoder
        // will be encrypted, except possibly for the packet
        // length (see below).
        $encoder->encodeUint32(1 + $size + $padSize);
        if ($this->outMAC instanceof \fpoirotte\Pssht\MAC\OpensshCom\EtM\EtMInterface) {
            // Send the packet length in plaintext.
            $encSize = $encoder->getBuffer()->get(0);
            $this->encoder->encodeBytes($encSize);
        }
        $encoder->encodeBytes(chr($padSize));
        $encoder->encodeBytes($payload);
        $encoder->encodeBytes($padding);
        $packet     = $encoder->getBuffer()->get(0);
        $encrypted  = $this->encryptor->encrypt($this->outSeqNo, $packet);

        // Compute the MAC.
        if ($this->outMAC instanceof \fpoirotte\Pssht\MAC\OpensshCom\EtM\EtMInterface) {
            $mac = $this->outMAC->compute($this->outSeqNo, $encSize . $encrypted);
        } else {
            $mac = $this->outMAC->compute($this->outSeqNo, $packet);
        }

        // Send the packet on the wire.
        $this->encoder->encodeBytes($encrypted);
        $this->encoder->encodeBytes($mac);
        $this->outSeqNo = ++$this->outSeqNo & 0xFFFFFFFF;

        $logging->debug(
            'Sending %(type)s packet ' .
            '(size: %(size)d, payload: %(payload)d, ' .
            'block: %(block)d, padding: %(padding)d)',
            array(
                'type' => get_class($message),
                'size' => strlen($encrypted),
                'payload' => $size,
                'block' => $blockSize,
                'padding' => $padSize,
            )
        );
        return $this;
    }
757288
public static function getHeadersAsString(MessageInterface $message)
    {
        $result  = '';
        foreach ($message->getHeaders() as $name => $values) {
            $result .= "\r\n{$name}: " . implode(', ', $values);
        }

        return $result;
    }
613363
private static function encodeEMSAPSS(string $message, int $modulusLength, Hash $hash): string
    {
        $emLen = ($modulusLength + 1) >> 3;
        $sLen = $hash->getLength();
        $mHash = $hash->hash($message);
        if ($emLen <= $hash->getLength() + $sLen + 2) {
            throw new \RuntimeException();
        }
        $salt = \random_bytes($sLen);
        $m2 = "\0\0\0\0\0\0\0\0".$mHash.$salt;
        $h = $hash->hash($m2);
        $ps = \str_repeat(\chr(0), $emLen - $sLen - $hash->getLength() - 2);
        $db = $ps.\chr(1).$salt;
        $dbMask = self::getMGF1($h, $emLen - $hash->getLength() - 1, $hash);
        $maskedDB = $db ^ $dbMask;
        $maskedDB[0] = ~\chr(0xFF << ($modulusLength & 7)) & $maskedDB[0];
        $em = $maskedDB.$h.\chr(0xBC);

        return $em;
    }
32074
private function printMessage(\Psr\Http\Message\MessageInterface $message)
    {
        $type = '';
        $body = '';
        if (is_a($message, '\Psr\Http\Message\RequestInterface')) {
            $type = 'REQUEST';
            $body = $message->getBody();
        } elseif (is_a($message, '\Psr\Http\Message\ResponseInterface')) {
            $type = 'RESPONSE';
            $body = $message->getBody()->getContents();
        }
        $this->command->info("$type:");
        $headers = '';
        foreach ($message->getHeaders() as $name => $values) {
            $headers .= $name . ': ' . implode(', ', $values) . "\r\n";
        }
        $this->command->comment($headers);
        if ($type == 'REQUEST') {
            $this->command->comment($body);
        } elseif ($type == 'RESPONSE') {
            $this->command->comment($body);
        }
    }
227024
public function encodeMessage($message)
    {
        // Get message descriptor
        $pool = DescriptorPool::getGeneratedPool();
        $messageType = $pool->getDescriptorByClassName(get_class($message));
        try {
            return $this->encodeMessageImpl($message, $messageType);
        } catch (\Exception $e) {
            throw new ValidationException(
                "Error encoding message: " . $e->getMessage(),
                $e->getCode(),
                $e
            );
        }
    }
1263719
public function getMessageDataSchema(MessageInterface $message): \stdClass
    {
        $parts = explode('.', $message->getPurpose());

        if (empty($parts)) {
            throw new InvalidMessageDataException('The message "purpose" property should clearly define specific message schema');
        }

        if ($this->cache->has($message->getPurpose())) {
            return $this->cache->get($message->getPurpose());
        }

        $file_name = array_pop($parts) . '.schema.json';

        $purpose_dirs = '';
        if (!empty($parts)) {
            $purpose_dirs = implode(DIRECTORY_SEPARATOR, $parts);
        }

        $schema_dirs = array_filter(array_map(function($dir) use ($purpose_dirs, $message) {
            $schema_dir = $dir . DIRECTORY_SEPARATOR . $message->getVersion() . DIRECTORY_SEPARATOR . $purpose_dirs;
            if (file_exists($schema_dir)) {
                return $schema_dir;
            }
            return NULL;
        }, $this->schemaDirs));

        $file_locator = new FileLocator($schema_dirs);

        try {
            $path = $file_locator->locate($file_name);
            $schema = json_decode(file_get_contents($path));

            $this->cache->set($message->getPurpose(), $schema);

            return $schema;
        }
        catch (FileLocatorFileNotFoundException $e) {
            throw new InvalidMessageDataException('Could not find message with purpose "' . $message->getPurpose() . '"');
        }
    }
883260
public function encode(CredentialsHolderInterface $user): string
    {
        return $this->encodePassword($user->getPlainPassword(), $user->getSalt());
    }
1318351
protected function encode(array $messages)
    {
        if ($this->encode) {
            foreach ($messages as $key => $message) {
                if (($form = mb_detect_encoding($message)) != self::TARGET_ENCODING) {
                    $messages[$key] = mb_convert_encoding($message, self::TARGET_ENCODING, $form);
                }
            }
        }

        return $messages;
    }
1124856
protected function decodeMessageBody(MessageInterface $msg)
    {
        // do we accept this type? (nb: this is an optional property)
        $type = $msg->getContentType();
        if ($type == '' && $this->assumedContentType != '') {
            $type = $this->assumedContentType;
        }
        if ($type == '' || !in_array($type, $this->acceptedContentTypes)) {
            throw new \RuntimeException("Can not decode message with content type: '$type'");
        }

        // then decode it
        switch ($type) {
            case 'application/json':
                $data = json_decode($msg->getBody(), true);
                if ($error = json_last_error()) {
                    throw new \UnexpectedValueException("Error decoding json payload: " . $error);
                }
                return $data;
            case 'application/x-httpd-php-source':
                /// @todo should we wrap this in try/catch, ob_start and set_error_handler, or just make sure it is never used?
                return eval ('return ' . $msg->body . ';');
            case 'vnd.php.serialized':
                return unserialize($msg->body);
            case 'text/plain':
            case 'application/octet-stream':
                return $msg->body;
            default:
                throw new \UnexpectedValueException("Serialization format unsupported: " . $type);
        }
    }
891881
public function modify(MessageInterface $message) : MessageInterface
    {
        /** @var MessageModifierInterface $modifier */
        foreach ($this->collection as $modifier) {
            $message = $modifier->modify($message);
        }

        return $message;
    }
320430
public static function getStartLine(MessageInterface $message)
    {
        if ($message instanceof RequestInterface) {
            return trim($message->getMethod() . ' '
                . $message->getResource())
                . ' HTTP/' . $message->getProtocolVersion();
        } elseif ($message instanceof ResponseInterface) {
            return 'HTTP/' . $message->getProtocolVersion() . ' '
                . $message->getStatusCode() . ' '
                . $message->getReasonPhrase();
        } else {
            throw new \InvalidArgumentException('Unknown message type');
        }
    }
1243968
public function wrapAndSerialize($message)
    {
        $envelope = $this->envelopeFactory->wrapMessageInEnvelope($message);

        $serializedMessage = $this->objectSerializer->serialize($message);

        return $this->objectSerializer->serialize($envelope->withSerializedMessage($serializedMessage));
    }
304469
private function getFromCache($key, MessageInterface $message)
    {
        if ($this->cache) {
            $item = $this->cache->getItem($key);

            if ($item->isHit()) {
                list($headers, $body) = $item->get();

                foreach ($headers as $name => $header) {
                    $message = $message->withHeader($name, $header);
                }

                $message->getBody()->write($body);

                return $message;
            }
        }

        return false;
    }
1002258
public function encodeMessage(Message $message, $level = 0)
    {
        $reflect    = new ReflectionClass($message);
        $properties = $reflect->getProperties(ReflectionProperty::IS_PROTECTED);
        $indent     = str_repeat('  ', $level);
        $stream     = Stream::create();

        foreach ($properties as $property) {

            $property->setAccessible(true);

            $name  = $property->getName();
            $value = $property->getValue($message);

            if ($value === null) {
                continue;
            }

            if ( ! is_array($value) && ! ($value instanceof Traversable)) {

                if ( ! $value instanceof Message) {
                    $item   = $this->encodeValue($value);
                    $buffer = $indent . $name . ': ' . $item . PHP_EOL;

                    $stream->write($buffer, strlen($buffer));

                    continue;
                }

                $innerStream  = $this->encodeMessage($value, $level + 1);
                $beginMessage = $indent . $name . ' {' . PHP_EOL;
                $endMessage   = $indent . '}' . PHP_EOL;

                $stream->write($beginMessage, strlen($beginMessage));
                $stream->writeStream($innerStream, $innerStream->getSize());
                $stream->write($endMessage, strlen($endMessage));

                continue;
            }

            foreach ($value as $val) {
                // Skip nullified repeated values
                if ($val == null) {
                    continue;
                }

                if ( ! $val instanceof Message) {
                    $item   = $this->encodeValue($val);
                    $buffer = $indent . $name . ': ' . $item . PHP_EOL;

                    $stream->write($buffer, strlen($buffer));

                    continue;
                }

                $innerStream  = $this->encodeMessage($val, $level + 1);
                $beginMessage = $indent . $name . ' {' . PHP_EOL;
                $endMessage   = $indent . '}' . PHP_EOL;

                $stream->write($beginMessage, strlen($beginMessage));
                $stream->writeStream($innerStream, $innerStream->getSize());
                $stream->write($endMessage, strlen($endMessage));
            }
        }

        $stream->seek(0);

        return $stream;
    }