blob: 542233b9c5873d8d9bd1b56af94a257de2554373 [file] [log] [blame]
Mark Slee052bbef2010-10-11 21:45:13 +00001<?php
2/*
3 * Licensed to the Apache Software Foundation (ASF) under one
4 * or more contributor license agreements. See the NOTICE file
5 * distributed with this work for additional information
6 * regarding copyright ownership. The ASF licenses this file
7 * to you under the Apache License, Version 2.0 (the
8 * "License"); you may not use this file except in compliance
9 * with the License. You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing,
14 * software distributed under the License is distributed on an
15 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 * KIND, either express or implied. See the License for the
17 * specific language governing permissions and limitations
18 * under the License.
19 *
20 * @package thrift.protocol
21 * @author: rmarin (marin.radu@facebook.com)
22 */
23
24require_once $GLOBALS['THRIFT_ROOT'].'/transport/TMemoryBuffer.php';
25require_once $GLOBALS['THRIFT_ROOT'].'/protocol/TBinaryProtocol.php';
26
27/**
28 * Utility class for serializing and deserializing
29 * a thrift object using TBinaryProtocolAccelerated.
30 */
31class TBinarySerializer {
32
33 // NOTE(rmarin): Because thrift_protocol_write_binary
34 // adds a begin message prefix, you cannot specify
35 // a transport in which to serialize an object. It has to
36 // be a string. Otherwise we will break the compatibility with
37 // normal deserialization.
38 public static function serialize($object) {
39 $transport = new TMemoryBuffer();
40 $protocol = new TBinaryProtocolAccelerated($transport);
41 if (function_exists('thrift_protocol_write_binary')) {
42 thrift_protocol_write_binary($protocol, $object->getName(),
43 TMessageType::REPLY, $object,
44 0, $protocol->isStrictWrite());
45
46 $protocol->readMessageBegin($unused_name, $unused_type,
47 $unused_seqid);
48 } else {
49 $object->write($protocol);
50 }
Jake Farrellb5c618a2011-08-26 02:42:14 +000051 $protocol->getTransport()->flush();
Mark Slee052bbef2010-10-11 21:45:13 +000052 return $transport->getBuffer();
53 }
54
55 public static function deserialize($string_object, $class_name) {
56 $transport = new TMemoryBuffer();
57 $protocol = new TBinaryProtocolAccelerated($transport);
58 if (function_exists('thrift_protocol_read_binary')) {
59 $protocol->writeMessageBegin('', TMessageType::REPLY, 0);
60 $transport->write($string_object);
61 return thrift_protocol_read_binary($protocol, $class_name,
62 $protocol->isStrictRead());
63 } else {
64 $transport->write($string_object);
65 $object = new $class_name();
66 $object->read($protocol);
67 return $object;
68 }
69 }
70}