Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CRM-18981 Add a 'validate' action to CiviCRM API #8624

Merged
merged 4 commits into from
Aug 27, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions api/v3/Generic/Validate.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2016 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/

/**
* @package CiviCRM_APIv3
*/

/**
* Provide meta-data for this api.
*
* @param array $params
*/
function _civicrm_api3_generic_validate_spec(&$params) {
$params['action']['api.required'] = TRUE;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add $params['action']['title'] = ts('blah blah');

for a huge test improvement

$params['action']['title'] = ts('API Action');
}

/**
* Generic api wrapper used for validation of entity-action pair.
*
* @param array $apiRequest
*
* @return mixed
*/
function civicrm_api3_generic_validate($apiRequest) {
$errors = _civicrm_api3_validate($apiRequest['entity'], $apiRequest['params']['action'], $apiRequest['params']);

return civicrm_api3_create_success($errors, $apiRequest['params'], $apiRequest['entity'], 'validate');
}
90 changes: 90 additions & 0 deletions api/v3/utils.php
Original file line number Diff line number Diff line change
Expand Up @@ -1537,6 +1537,96 @@ function _civicrm_api3_custom_data_get(&$returnArray, $checkPermission, $entity,
}
}

/**
* Used by the Validate API.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Super trivial - but the full whitespace standard would have a blank line here

* @param string $entity
* @param string $action
* @param array $params
*
* @return array $errors
*/
function _civicrm_api3_validate($entity, $action, $params) {
$errors = array();
$fields = civicrm_api3($entity, 'getfields', array('sequential' => 1, 'api_action' => $action));
$fields = $fields['values'];

// Check for required fields.
foreach ($fields as $values) {
if (!empty($values['api.required']) && empty($params[$values['name']])) {
$errors[$values['name']] = array(
'message' => "Mandatory key(s) missing from params array: " . $values['name'],
'code' => "mandatory_missing",
);
}
}

// Select only the fields which have been input as a param.
$finalfields = array();
foreach ($fields as $values) {
if (array_key_exists($values['name'], $params)) {
$finalfields[] = $values;
}
}

// This derives heavily from the function "_civicrm_api3_validate_fields".
// However, the difference is that try-catch blocks are nested in the loop, making it
// possible for us to get all errors in one go.
foreach ($finalfields as $fieldInfo) {
$fieldName = $fieldInfo['name'];
try {
_civicrm_api3_validate_switch_cases($fieldName, $fieldInfo, $entity, $params);
}
catch (Exception $e) {
$errors[$fieldName] = array(
'message' => $e->getMessage(),
'code' => 'incorrect_value',
);
}
}

return array($errors);
}
/**
* Used by the Validate API.
* @param array $fieldInfo
* @param string $entity
* @param array $params
*
* @throws Exception
*/
function _civicrm_api3_validate_switch_cases($fieldName, $fieldInfo, $entity, $params) {
switch (CRM_Utils_Array::value('type', $fieldInfo)) {
case CRM_Utils_Type::T_INT:
_civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
break;

case CRM_Utils_Type::T_DATE:
case CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME:
case CRM_Utils_Type::T_TIMESTAMP:
//field is of type date or datetime
_civicrm_api3_validate_date($params, $fieldName, $fieldInfo);
break;

case CRM_Utils_Type::T_TEXT:
_civicrm_api3_validate_html($params, $fieldName, $fieldInfo);
break;

case CRM_Utils_Type::T_STRING:
_civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
break;

case CRM_Utils_Type::T_MONEY:
list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);

foreach ((array) $fieldValue as $fieldvalue) {
if (!CRM_Utils_Rule::money($fieldvalue) && !empty($fieldvalue)) {
throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
}
}
break;
}
}

/**
* Validate fields being passed into API.
*
Expand Down
89 changes: 89 additions & 0 deletions tests/phpunit/api/v3/ValidateTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2016 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/

/**
* Tests for the generic validate API action.
*
* @package CiviCRM_APIv3
* @group headless
*/
class api_v3_ValidateTest extends CiviUnitTestCase {
/**
* This method is called before a test is executed.
*/
protected function setUp() {
parent::setUp();
}

public function testEmptyContactValidate() {
$validation = $this->callAPISuccess('Contact', 'validate', array('action' => "create"));
$expectedOut = array(
'contact_type' => array(
'message' => "Mandatory key(s) missing from params array: contact_type",
'code' => "mandatory_missing",
),
);
$this->assertEquals($validation['values'][0], $expectedOut);
Copy link
Contributor Author

@saurabhbatra96 saurabhbatra96 Aug 3, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

$validation['values'][0] - this nesting seems like a necessary evil. Cannot return the output in this dictionary format without using it:

    {
    "is_error": 0,
    "version": 3,
    "count": 1,
    "id": 0,
    "values": [
        {
            "contact_type": {
                "message": "Mandatory key(s) missing from params array: contact_type",
                "code": "mandatory_missing"
            }
        }
    ]
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmm - should it be up one?

ie

$result['values']['contact_type'] => you would need to add field_name to the response array for when it's called with 'is_sequential'

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Up for a chat on mattermost?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is just how civicrm_api3_create_success arranges the API output.
I could instead go for:

{
    "is_error": 0,
    "version": 3,
    "count": 1,
    "id": 0,
    "values": [
           {
                "name": "total_amount",
                "message": "Mandatory key(s) missing from params array: total_amount",
                "code": "mandatory_missing"
            },
            {
                "name": "contact_id",
                "message": "Mandatory key(s) missing from params array: contact_id",
                "code": "mandatory_missing"
            }
    ]
}

}

public function testContributionValidate() {
$validation = $this->callAPISuccess('Contribution', 'validate', array('action' => "create", 'total_amount' => "100w"));
$totalAmountErrors = array(
'message' => "total_amount is not a valid amount: 100w",
'code' => "incorrect_value",
);

$contactIdErrors = array(
'message' => "Mandatory key(s) missing from params array: contact_id",
'code' => "mandatory_missing",
);

$this->assertEquals($validation['values'][0]['total_amount'], $totalAmountErrors);
$this->assertEquals($validation['values'][0]['contact_id'], $contactIdErrors);
}

public function testContributionDateValidate() {
$params = array(
'action' => "create",
'financial_type_id' => "1",
'total_amount' => "100",
'contact_id' => "1",
'receive_date' => 'abc',
);
$validation = $this->callAPISuccess('Contribution', 'validate', $params);

$expectedOut = array(
'receive_date' => array(
'message' => "receive_date is not a valid date: abc",
'code' => "incorrect_value",
),
);

$this->assertEquals($validation['values'][0], $expectedOut);
}

}