Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Analyse encoding of arrays in msgpack #106

Open
fcastilloes opened this issue Mar 5, 2018 · 2 comments
Open

Analyse encoding of arrays in msgpack #106

fcastilloes opened this issue Mar 5, 2018 · 2 comments

Comments

@fcastilloes
Copy link
Contributor

Msgpack supports both maps and arrays for lists of data. When a packing is done from php, a map could be created both with string or integer keys. An msgpack array is created when the php array has only integer keys that are sequential and starting from 0.

Katana has strong types and map keys must be strings, so any integer key in a map will result in error.

Some solution is needed to prevent those errors.

The library could have some options. https://github.com/rybakit/msgpack.php#type-detection-mode

@fcastilloes fcastilloes added this to the 2.0 milestone Mar 5, 2018
@fcastilloes fcastilloes self-assigned this Mar 5, 2018
@rybakit
Copy link

rybakit commented Apr 17, 2018

@fcastilloes It's quite easy to achieve with the new msgpack.php v0.3.0:

First, create a "packable" type transformer:

class StringKeyMapTransformer implements Packable
{
    public function pack(Packer $packer, $value)
    {
        if (!$value instanceof Map) {
            return null;
        }

        $data = $packer->packMapHeader(\count($value->map));
        foreach ($value->map as $key => $val) {
            $data .= $packer->packStr($key).$packer->pack($val); // keys get packed to str
        }

        return $data;
    }
}

Then register it and wrap your assoc arrays with MessagePack\Type\Map objects:

use MessagePack\Packer;
use MessagePack\Type\Map;

$packer = new Packer();
$packer->registerTransformer(new StringKeyMapTransformer());

$packed = $packer->pack(new Map($data));

@fcastilloes
Copy link
Contributor Author

Thanks a lot @rybakit, I am busy in other projects now, but this looks great for this and a couple of other types I need to serialize. I'll definitely give it a try.

@fcastilloes fcastilloes removed their assignment Feb 27, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants