- cast default values correctly
[plcapi.git] / php / methods.py
index 0b54370..5b66594 100755 (executable)
@@ -5,7 +5,7 @@
 # Mark Huang <mlhuang@cs.princeton.edu>
 # Copyright (C) 2005 The Trustess of Princeton University
 #
-# $Id: gen_php_api.py,v 1.13 2006/03/23 04:29:08 mlhuang Exp $
+# $Id: methods.py,v 1.2 2006/11/10 06:32:26 mlhuang Exp $
 #
 
 import os, sys
@@ -15,6 +15,25 @@ from PLC.API import PLCAPI
 from PLC.Method import *
 from PLC.Auth import Auth
 
+def php_cast(value):
+    """
+    Casts Python values to PHP values.
+    """
+    
+    if value is None:
+        return "NULL"
+    elif isinstance(value, (list, tuple, set)):
+        return "array(%s)" % ", ".join([php_cast(v) for v in value])
+    elif isinstance(value, dict):
+        items = ["%s => %s" % (php_cast(k), php_cast(v)) for (k, v) in value.items()]
+        return "array(%s)" % ", ".join(items)
+    elif isinstance(value, (int, long, bool, float)):
+        return str(value)
+    else:
+        unicode_repr = repr(unicode(value))
+        # Truncate the leading 'u' prefix
+        return unicode_repr[1:]
+
 # Class functions
 api = PLCAPI(None)
 
@@ -49,9 +68,9 @@ for method in api.methods:
         # Declare parameter
         arg = "$" + name
 
-        # Set optional parameters to special value NULL
+        # Set optional parameters to their defaults
         if name not in min_args:
-            arg += " = NULL"
+            arg += " = " + php_cast(default)
 
         args.append(arg)
 
@@ -70,10 +89,7 @@ for method in api.methods:
             print "  $args[] = $this->auth;"
             continue
 
-        if name in min_args:
-            print "  $args[] = $%s;" % name
-        else:
-            print "  if ($%s !== NULL) { $args[] = $%s; }" % (name, name)
+        print "  $args[] = $%s;" % name
 
     # Call API function
     print "  return $this->call('%s', $args);" % method