From 3a779e02ecc481cde8e345ede7a2220e69a44d69 Mon Sep 17 00:00:00 2001
From: Mark Carver <mark.carver@me.com>
Date: Sat, 24 Dec 2016 09:04:45 -0600
Subject: [PATCH] Issue #2836007 by markcarver: Add "load arguments" ability

---
 includes/callback.inc | 50 ++++++++++++++++++++++++++++++++++++++++++++------
 js.api.php            | 49 ++++++++++++++++++++++++++++++++++++++-----------
 js.module             |  1 +
 3 files changed, 83 insertions(+), 17 deletions(-)

diff --git a/includes/callback.inc b/includes/callback.inc
index 275d19b..7a25d7c 100644
--- a/includes/callback.inc
+++ b/includes/callback.inc
@@ -253,6 +253,9 @@ function js_callback_process_request(&$info) {
     }
   }
 
+  // Load argument callbacks.
+  $load_arguments = $info['load arguments'];
+
   // Retrieve the default parameters of the callback function.
   foreach (array('access', 'callback') as $type) {
     $data = $request_data;
@@ -263,23 +266,58 @@ function js_callback_process_request(&$info) {
     if (function_exists($function)) {
       $f = new ReflectionFunction($function);
       foreach ($f->getParameters() as $param) {
-        $default = NULL;
-        if ($param->isDefaultValueAvailable()) {
-          $default = $param->getDefaultValue();
+        // Determine if there's a default value.
+        $default = $param->isDefaultValueAvailable() ? $param->getDefaultValue() : NULL;
+
+        // Determine if callback parameter has been type hinted with a class.
+        if ($class = $param->getClass()) {
+          $default = array('class' => $class->getName(), 'default' => $default);
         }
+
+        // Set the default value.
         $parameters[$param->name] = $default;
+
+        // Give callback definitions a chance to completely disable autoloading.
+        if ($load_arguments !== FALSE && is_array($load_arguments)) {
+          // Automatically determine load function, if it wasn't explicitly set.
+          if (!isset($load_arguments[$param->name])) {
+            $load_callback = $param->name . '_load';
+            if (function_exists($load_callback)) {
+              $load_arguments[$param->name] = $load_callback;
+            }
+          }
+          // Otherwise, remove it if it's empty or not callable.
+          elseif (!$load_arguments[$param->name] || !is_callable($load_arguments[$param->name])) {
+            unset($load_arguments[$param->name]);
+          }
+        }
       }
     }
     foreach ($parameters as $name => $default_value) {
       // Check to see if the parameter exists.
       if (isset($data[$name])) {
+        $value = $data[$name];
+
+        // Load the parameter using a load argument callback, if one exists.
+        if (is_array($load_arguments) && isset($load_arguments[$name])) {
+          $value = call_user_func_array($load_arguments[$name], array($value));
+        }
+
+        // Ensure class type hinting is passing the proper value.
+        if (is_array($default_value) && isset($default_value['class'])) {
+          if (!is_object($value) || (get_class($value) !== $default_value['class'] && !is_subclass_of($value, $default_value['class']))) {
+            $value = $default_value['default'];
+          }
+        }
         // Convert the type of variable in the $_REQUEST array to match the
         // same variable type as the parameter's default value.
-        if (!is_null($default_value)) {
-          settype($data[$name], gettype($default_value));
+        elseif (!is_null($default_value)) {
+          settype($value, gettype($default_value));
         }
+
         // Move the value of the $_REQUEST data into the parameter array.
-        $parameters[$name] = $data[$name];
+        $parameters[$name] = $value;
+
         // Remove the request data since it has been moved.
         unset($data[$name]);
       }
diff --git a/js.api.php b/js.api.php
index fed7ab5..f618dc8 100644
--- a/js.api.php
+++ b/js.api.php
@@ -30,7 +30,12 @@
  *     current user. WARNING: If not set, no access checks are performed at all.
  *     Defaults to "user_access" if the below option (access arguments) has
  *     a value.
- *   - access arguments: (optional) Arguments for the access callback.
+ *   - access arguments: (optional) Internal use. Normally, you won't need
+ *     to assign any callback arguments as they will automatically be determined
+ *     based on the names of passed parameters and callback function signatures.
+ *     If set, these static values will be passed to the callback function
+ *     before anything else. To automatically "load" arguments, see the "load
+ *     arguments" and "process request" properties below.
  *   - delivery callback: (optional) The function to call to package the results
  *     of the callback function and send it to the browser. Defaults to
  *     js_deliver_json(). Note that this function is called even if the
@@ -48,6 +53,18 @@
  *     support. JS auto-detects the language string in request paths. Set
  *     this option to TRUE to enable translations, if you're not getting the
  *     desired results.
+ *   - load arguments: (optional) An associative array of key/value pairs where
+ *     parameter name is the key and a callback is the value. The callback will
+ *     be passed a single argument, the value of the passed parameter. The JS
+ *     module automatically detects any "PARAMETER_load" functions that exist
+ *     based on if "process request" is enabled and the function explicitly
+ *     specifies that parameter in it's callback function signature. For
+ *     example: if one of the parameters passed is "node" and the callback
+ *     function signature defines a $node argument, then a "node_load" function
+ *     will be invoked (if the function exists). Optionally, to disable the
+ *     automatic load callback for a parameter, you can set the callback to
+ *     FALSE or to disable all automatic "load arguments" processing you may
+ *     set FALSE for the entire "load arguments" property.
  *   - methods: (optional) The request methods allowed. This must be an array
  *     of string values. If the request does not match any of the allowed
  *     methods defined by the callback, it will be rejected.
@@ -85,20 +102,30 @@ function hook_js_info() {
   // Simple callback definition:
   $callbacks['simple'] = array();
 
-  // Example of a more complex definition:
+  /* Example of a more complex definition:
+
+  function my_module_custom_access_check($node = NULL) {
+    // Node did not load or is not the right type.
+    if (!isset($node) || $node->type !== 'custom_bundle') {
+      return FALSE;
+    }
+    // Node is a fully loaded, determine access based on field value.
+    $field = field_get_items('node', $node, 'field_custom_bool_toggle');
+    return !!$field[0]['value'];
+  }
+
+  function my_module_custom_callback_function($node, $my_custom_param) {
+    // Node is fully loaded, retrieve a custom field value.
+    $field = field_get_items('node', $node, 'field_custom_field_text');
+    return $field[0]['value'];
+  }
+   */
   $callbacks['complex'] = array(
+    'bootstrap' => DRUPAL_BOOTSTRAP_LANGUAGE,
     'access callback'  => 'my_module_custom_access_check',
-    'access arguments' => array(1, 2),
-    'bootstrap' => DRUPAL_BOOTSTRAP_SESSION,
     'callback function' => 'my_module_custom_callback_function',
-    'callback arguments' => array(1, 2),
-    'delivery callback' => 'my_module_custom_delivery_callback',
-    'includes' => array('path', 'authorize', 'form'),
-    'dependencies' => array('system', 'views'),
-    'lang' => TRUE,
-    'method' => array('PUT'),
+    'dependencies' => array('field', 'node', 'system'),
     'skip init' => TRUE,
-    'process request' => FALSE,
     'token' => FALSE,
   );
   return $callbacks;
diff --git a/js.module b/js.module
index 98d87d1..2d63e5b 100644
--- a/js.module
+++ b/js.module
@@ -736,6 +736,7 @@ function js_get_callback($module = NULL, $callback = NULL, $reset = FALSE) {
             'dependencies' => array(),
             'includes' => array(),
             'lang' => FALSE,
+            'load arguments' => array(),
             'methods' => array('POST'),
             'module' => $_module,
             'process request' => TRUE,
-- 
2.8.3

