public static function expand($template, $variables, array $options = array())
{
    if (is_object($variables)) {
        $variables = get_object_vars($variables);
    } elseif (!is_array($variables)) {
        throw new UriTemplateException('$variables must be an array or object');
    }

    $result = $template;
    $errors = array();
    $expressions = self::getExpressions($template, $options);
    $i = count($expressions);
    while ($i-- > 0) {
        try {
            $expression = $expressions[$i];
            if (!$expression['valid']) {
                throw new UriTemplateException('Malformed expression: "%s" at offset %d', array($expression['complete'], $expression['offset']));
            }
            $sub = UriTemplate::expandExpression($expression['expression'], $variables, isset($options['keySort']) ? (bool)$options['keySort'] : false);
            $result = substr_replace($result, $sub, $expression['offset'], strlen($expression['complete']));
        } catch (UriTemplateException $e) {
            $errors[] = $e->getMessage();
            continue;
        }
    }

    if ($errors) {
        throw new UriTemplateException('Invalid URI Template string: "%s"', array($template), $errors);
    }
    return $result;
}