Method: PHP.unserialize

Defined in:
lib/php_serialize.rb

.unserialize(string, classmap = nil, assoc = false) ⇒ Object

mixed = PHP.unserialize(string serialized, [hash classmap, [bool assoc]])

Returns an object containing the reconstituted data from serialized.

If a PHP array (associative; like an ordered hash) is encountered, it scans the keys; if they’re all incrementing integers counting from 0, it’s unserialized as an Array, otherwise it’s unserialized as a Hash. Note: this will lose ordering. To avoid this, specify assoc=true, and it will be unserialized as an associative array: [[key,value],…]

If a serialized object is encountered, the hash ‘classmap’ is searched for the class name (as a symbol). Since PHP classnames are not case-preserving, this must be a .capitalize()d representation. The value is expected to be the class itself; i.e. something you could call .new on.

If it’s not found in ‘classmap’, the current constant namespace is searched, and failing that, a new Struct(classname) is generated, with the arguments for .new specified in the same order PHP provided; since PHP uses hashes to represent attributes, this should be the same order they’re specified in PHP, but this is untested.

each serialized attribute is sent to the new object using the respective attribute=() method; you’ll get a NameError if the method doesn’t exist.

Array, Hash, Fixnum, Float, True/FalseClass, NilClass and String should be returned identically (i.e. foo == PHP.unserialize(PHP.serialize(foo)) for these types); Struct should be too, provided it’s in the namespace Module.const_get within unserialize() can see, or you gave it the same name in the Struct.new(<structname>), otherwise you should provide it in classmap.

Note: StringIO is required for unserialize(); it’s loaded as needed



194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
# File 'lib/php_serialize.rb', line 194

def PHP.unserialize(string, classmap = nil, assoc = false) # {{{
  if classmap == true or classmap == false
    assoc = classmap
    classmap = {}
  end
  classmap ||= {}

  ret = nil
  original_encoding = string.encoding if string.respond_to?(:encoding)
  string = StringIOReader.new(string.respond_to?(:force_encoding) ? string.force_encoding('BINARY') : string)
  while string.string[string.pos, 32] =~ /^(\w+)\|/ # session_name|serialized_data
    ret ||= {}
    string.pos += $&.size
    ret[$1] = PHP.do_unserialize(string, classmap, assoc, original_encoding)
  end

  ret ? ret : PHP.do_unserialize(string, classmap, assoc, original_encoding)
end