You are here

function ctools_break_phrase in Chaos Tool Suite (ctools) 7

Same name and namespace in other branches
  1. 6 ctools.module \ctools_break_phrase()

Parse integer sequences of the form "x,y,z" or "x+y+z" into separate values.

A string with integers separated by comma (,) is reported as an 'and' set; separation by a plus sign (+) or a space ( ) is an 'or' set. The meaning of this is up to the caller. Negative or fractional numbers are not recognised.

Additional space characters within or around the sequence are not allowed.

Parameters

$str: The string to parse.

Return value

object An object containing the properties:

  • operator: Either 'and' or 'or' when there are multiple matched values.

Absent when invalid_input is TRUE or there is only one value.

  • value: An array of integers (never strings) from $str. An empty array is

returned if the input is empty. A single integer input is returned as a single value, but no 'operator' is defined.

  • invalid_input: TRUE if input could not be parsed and the values array

will contain just -1. This property is otherwise absent.

3 calls to ctools_break_phrase()
CtoolsModuleTestCase::testBreakPhrase in tests/ctools.test
Test that the break phrase function behaves as expected.
ctools_terms_context in plugins/arguments/terms.inc
Discover if this argument gives us the term we crave.
ctools_terms_from_node_context in plugins/relationships/terms_from_node.inc
Return a new context based on an existing context.

File

./ctools.module, line 309
CTools primary module file.

Code

function ctools_break_phrase($str) {
  $object = new stdClass();
  if (preg_match('/^([0-9]+[+ ])+[0-9]+$/', $str)) {

    // The '+' character in a query string may be parsed as ' '.
    $object->operator = 'or';
    $object->value = preg_split('/[+ ]/', $str);
  }
  elseif (preg_match('/^([0-9]+,)*[0-9]+$/', $str)) {
    $object->operator = 'and';
    $object->value = explode(',', $str);
  }

  // Keep an 'error' value if invalid strings were given.
  if (!empty($str) && (empty($object->value) || !is_array($object->value))) {
    $object->value = array(
      -1,
    );
    $object->invalid_input = TRUE;
    return $object;
  }
  if (empty($object->value)) {
    $object->value = array();
  }

  // Doubly ensure that all values are numeric only.
  foreach ($object->value as $id => $value) {
    $object->value[$id] = (int) $value;
  }
  return $object;
}