Safely Parse Complex Objects and Arrays in PHP

Multithreaded JavaScript has been published with O'Reilly!
<?php
/**
 * This class will safely parse complex objects or arrays with possible missing keys
 *
 * Usage: obj::query($obj, 'dot.separated.syntax');
 */
class obj {
    /**
     * Parse the provided object
     *
     * @param $object mixed The complex object you're going to parse
     * @param $path string The dot separated path you would like to query the object with
     */
    public static function query($object, $path) {
        $paths = explode('.', $path);
        return self::recurse($object, $paths);
    }

    /**
     * The function that does the real work
     *
     * @param $object mixed
     * @param $paths array
     */
    protected static function recurse($object, $paths) {
        if (!$object) {
            return null;
        }
        if (!is_array($object) && !is_object($object)) {
            return $object;
        }

        $newPath = array_shift($paths);

        if (is_array($object) && isset($object[$newPath])) {
            return self::recurse($object[$newPath], $paths);
        } else if (is_object($object) && isset($object->$newPath)) {
            return self::recurse($object->$newPath, $paths);
        } else {
            return null;
        }
    }
}

$data = '{
  "x": {
    "y": true,
    "z": null,
    "w": false,
    "l": "banana",
    "a": {
      "b": {
        "c": "d",
        "d": "e"
      }
    }
  }
}';

$complexArray = json_decode($data, true);
$complexObject = json_decode($data);
$complexMixed = array(
    array(
        'x' => json_decode('{"name": "so complex"}')
    )
);

echo "Should be banana: ";
var_dump(obj::query($complexArray, 'x.l'));

echo "Should be 'e': ";
var_dump(obj::query($complexArray, 'x.a.b.d'));

echo "Should be NULL: ";
var_dump(obj::query($complexArray, 'a.b.c.d.e.f.g'));

echo "Should be TRUE: ";
var_dump(obj::query($complexObject, 'x.y'));

echo "Should be 'so complex': ";
var_dump(obj::query($complexMixed, '0.x.name'));
Tags: #php
Thomas Hunter II Avatar

Thomas has contributed to dozens of enterprise Node.js services and has worked for a company dedicated to securing Node.js. He has spoken at several conferences on Node.js and JavaScript and is an O'Reilly published author.