Mariph

Mariph is a collection of a few classes that can read a subset of Ruby’s Marshal format. I wrote it back when I worked with RPG Maker XP, and wanted to convert the marshalled data from that program into something I could read. In order to do it in Ruby, I would have had to recreate most of the module and class structure defined in RPG Maker, so I instead opted to write a reader in the language most familiar to me – PHP.

It does not support every feature built in to the marshal format, only the ones that I required at the time. This includes: nil, true, false, int, float, string, symbol, regexp (string), array, hash, object, and user. Hash types are returned as a Mariph_Hash, which is a simple representation of a hash table with arbitrary data for keys. Objects are returned as stdClass, with the property __mariphName set to the name of its Ruby counterpart class. User types look for a PHP class defined with the same name as the Ruby class, with any double colon replaced by a double underscore. It then statically calls the class’s rubyLoad() method, which should accept the raw data string as its only parameter, and return an instance of the class. See the Table class in the file for an example.

The simplest way to parse in the data is by calling the mariph_load() shortcut function, which saves you the trouble of initializing both the tokenizer and interpreter classes. Each top-level element in the marshalled string becomes an element of the returned array.

$data = mariph_load($marshalString);

The Mariph_Hash class has your standard get() and set() methods, along with a few convenience methods such as iterate(), count() (implementing Countable), each(), and reset().

$hash = new Mariph_Hash(array('initial' => 'data'));
$hash->set(1, 'one');
$hash->set(2.5, 'two point five');
$hash->set('str', 'string');
$hash->set(array(1, 2, 3), 'one two three');

echo $hash->get(2.5); // "two point five"

// should work in PHP 5.3
$hash->iterate(function($value, $key) {
    echo 'Key: ';
    var_dump($key);
    echo 'Value: ';
    var_dump($value);
});

// Alternatively iterate with each()
while (list($key, $value) = $hash->each()) {
    // do whatever
}

// reset iteration position after using each()
$hash->reset();

I’m sure there’s much better ways for designing a custom hash class than what I wrote, but for me it gets the job done. Hopefully this small library can prove useful to some people. :)

This entry was posted in PHP and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>