0 follower

Final Class Yiisoft\Queue\Message\Serializer\MessageSerializer

InheritanceYiisoft\Queue\Message\Serializer\MessageSerializer
ImplementsYiisoft\Queue\Message\Serializer\MessageSerializerInterface

Serializes and unserializes queue messages, resolving the message class via a {@see MessageClassResolverInterface}.

When serializing, assembles an array with type, payload, and meta keys and passes it as a single array to {@see \Yiisoft\Queue\Message\Serializer\MessageEncoderInterface}, which encodes it to a string. When unserializing, decodes the string back to an array and resolves the message class from the type via the resolver, falling back to {@see \Yiisoft\Queue\Message\GenericMessage} if the type is not registered.

Method Details

Hide inherited methods

__construct() public method

public mixed __construct ( Yiisoft\Queue\Message\Serializer\MessageEncoderInterface $encoder, Yiisoft\Queue\Message\ClassResolver\MessageClassResolverInterface|array $classResolver = [] )
$encoder Yiisoft\Queue\Message\Serializer\MessageEncoderInterface

Encoder used to encode and decode message data.

$classResolver Yiisoft\Queue\Message\ClassResolver\MessageClassResolverInterface|array

Resolver for message classes, or a map of type to class.

                public function __construct(
    private readonly MessageEncoderInterface $encoder,
    MessageClassResolverInterface|array $classResolver = [],
) {
    $this->resolver = is_array($classResolver)
        ? new ArrayMessageClassResolver($classResolver)
        : $classResolver;
}

            
serialize() public method

public string serialize ( Yiisoft\Queue\Message\MessageInterface $message )
$message Yiisoft\Queue\Message\MessageInterface

                public function serialize(MessageInterface $message): string
{
    return $this->encoder->encode([
        'type' => $message->getType(),
        'payload' => $message->getPayload(),
        'meta' => $message->getMetadata(),
    ]);
}

            
unserialize() public method

public Yiisoft\Queue\Message\MessageInterface unserialize ( string $value )
$value string

                public function unserialize(string $value): MessageInterface
{
    $data = $this->encoder->decode($value);
    if (!is_array($data)) {
        throw new MessageSerializerException('Decoded data must be array. Got ' . get_debug_type($data) . '.');
    }
    $type = $data['type'] ?? null;
    if (!isset($type) || !is_string($type)) {
        throw new MessageSerializerException('Message type must be a string. Got ' . get_debug_type($type) . '.');
    }
    $metadata = $data['meta'] ?? [];
    if (!is_array($metadata)) {
        throw new MessageSerializerException('Metadata must be an array. Got ' . get_debug_type($metadata) . '.');
    }
    $class = $this->resolver->resolve($type) ?? GenericMessage::class;
    return $class::fromPayload($type, $data['payload'] ?? null)->withMetadata($metadata);
}