Created
September 1, 2013 05:44
-
-
Save jrschumacher/6402581 to your computer and use it in GitHub Desktop.
Convert a PHP Mongo query with Mongo* classes to MongoDB js query. Currently supports MongoId => ObjectId, MongoDate => ISODate, and MongoRegex => RegExp. [VERY ROUGH] -- Wrote this because I was tired of getting stuck and having to port the query by hand.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class MongoQueryStr { | |
protected static $indent = 0; | |
public static function convert($query) { | |
if(!is_array($query)) { | |
return false; | |
} | |
return self::parseRecursive($query); | |
} | |
protected static function parseRecursive($j) { | |
$q = ''; | |
self::$indent++; | |
$first = true; | |
foreach($j as $k => $v) { | |
$array = is_numeric($k); | |
if($first) { | |
$first = false; | |
if($array) | |
$q .= "[\n"; | |
else | |
$q .= "{\n"; | |
} | |
$q .= str_repeat("\t", self::$indent); | |
if(!$array) | |
$q .= "\"$k\": "; | |
if(is_array($v)) { | |
$q .= self::parseRecursive($v); | |
} | |
else if(is_object($v)) { | |
$q .= self::convertMongoClass($v); | |
} | |
else if(is_numeric($v)) { | |
$q .= (int) $v; | |
} | |
else if(is_bool($v)) { | |
$q .= $v ? "true" : "false"; | |
} | |
else { | |
$q .= "\"$v\""; | |
} | |
$q .= ",\n"; | |
} | |
self::$indent--; | |
return trim($q, ",\n")."\n".str_repeat("\t", self::$indent).($array ? "]" : "}"); | |
} | |
protected static function convertMongoClass($instance) { | |
if($instance instanceof \MongoId) { | |
return 'ObjectId("'.(string)$instance.'")'; | |
} | |
if($instance instanceof \MongoDate) { | |
return 'ISODate("'.date('c', $instance->sec).'")'; | |
} | |
if($instance instanceof \MongoRegex) { | |
return 'RegExp('.$instance.')'; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment