You are here

function entity_property_verify_data_type in Entity API 7

Verifies that the given data can be safely used as the given type regardless of the PHP variable type of $data. Example: the string "15" is a valid integer, but "15nodes" is not.

Return value

bool Whether the data is valid for the given type.

1 call to entity_property_verify_data_type()
EntityMetadataWrapper::validate in includes/entity.wrapper.inc
Returns whether $value is a valid value to set.

File

includes/entity.property.inc, line 237
Provides API functions around hook_entity_property_info(). Also see entity.info.inc, which cares for providing entity property info for all core entity types.

Code

function entity_property_verify_data_type($data, $type) {

  // As this may be called very often statically cache the entity info using
  // the fast pattern.
  static $drupal_static_fast;
  if (!isset($drupal_static_fast)) {

    // Make use of the same static as entity info.
    entity_get_info();
    $drupal_static_fast['entity_info'] =& drupal_static('entity_get_info');
  }
  $info =& $drupal_static_fast['entity_info'];

  // First off check for entities, which may be represented by their ids too.
  if (isset($info[$type])) {
    if (is_object($data)) {
      return TRUE;
    }
    elseif (isset($info[$type]['entity keys']['name'])) {

      // Read the data type of the name key from the metadata if available.
      $key = $info[$type]['entity keys']['name'];
      $property_info = entity_get_property_info($type);
      $property_type = isset($property_info['properties'][$key]['type']) ? $property_info['properties'][$key]['type'] : 'token';
      return entity_property_verify_data_type($data, $property_type);
    }
    return entity_property_verify_data_type($data, empty($info[$type]['fieldable']) ? 'text' : 'integer');
  }
  switch ($type) {
    case 'site':
    case 'unknown':
      return TRUE;
    case 'date':
    case 'duration':
    case 'integer':
      return is_numeric($data) && strpos($data, '.') === FALSE;
    case 'decimal':
      return is_numeric($data);
    case 'text':
      return is_scalar($data);
    case 'token':
      return is_scalar($data) && preg_match('!^[a-z][a-z0-9_]*$!', $data);
    case 'boolean':
      return is_scalar($data) && (is_bool($data) || $data == 0 || $data == 1);
    case 'uri':
      return valid_url($data, TRUE);
    case 'list':
      return is_array($data) && array_values($data) == $data || is_object($data) && $data instanceof EntityMetadataArrayObject;
    case 'entity':
      return is_object($data) && $data instanceof EntityDrupalWrapper;
    case 'struct':
    default:
      return is_object($data) || is_array($data);
  }
}