Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagephp
class MyModule extends Module {
...
	public function addService($package, array $vars=null, $parent_package=null, $parent_service=null, $status="pending") {
		// Get the module row used for this service
		$row = $this->getModuleRow();

        // Filter the given $vars into an array of key/value pairs that will be passed to the API
        $params = $this->getFieldsFromInput((array)$vars, $package);
		
		// Attempt to validate the input and return on failure
		$this->validateService($package, $vars);
		if ($this->Input->errors())
			return;

		// Only provision the service remotely if 'use_module' is true
		if (isset($vars['use_module']) && $vars['use_module'] == "true") {
			// Log the input being sent remotely, careful to mask any sensitive information
			$masked_params = $params;
			$masked_params['mymodule_field'] = "***";

			// Set the URL to where the remote request is being sent (assuming 'host_name' is a valid module row meta field)
			$remote_url = $row->meta->host_name;
			$this->log($remote_url . "|api_command", serialize($masked_params), "input", true);

			// Provision the service remotely (this is dependent on the module's API, omitted here)
			$response = $this->makeRequest($params);

			// Return on error
			if ($this->Input->errors())
				return;
		}

		// Return the service fields
		return array(
			array(
				'key' => "mymodule_field",
				'value' => (isset($vars['mymodule_field']) ? $vars['mymodule_field'] : null),
				'encrypted' => 0
			)
		);
	}

	private function makeRequest($params) {
		// Get the module row used for this service
		$row = $this->getModuleRow();

		// Perform the remote request (this is dependent on the module's API, omitted here)
		$response = $this->apiCall($params);

		// Retrieve the response from the module and evaluate its result as true/false, setting any input errors
		$success = true;
		if (isset($response->status) && !$response->status) {
			$this->Input->setErrors(array('api' => array('response' => Language::_("MyModule.!error.api.response", true))));
			$success = false;
		}
		
		// Log the response
		$this->log($row->meta->host_name, $response, "output", $success);

		// Return the result
		if (!$success)
			return;
		return $response;
	}

	private function apiCall($params) {
		// Make the API call to the module (this is dependent on the module's API, omitted here)
		return (object)array('status' => false);
	}
...
}

...