Projet

Général

Profil

Paste
Télécharger (13,4 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / rules / modules / data.eval.inc @ 76df55b7

1
<?php
2

    
3
/**
4
 * @file
5
 * Contains rules integration for the data module needed during evaluation.
6
 *
7
 * @addtogroup rules
8
 * @{
9
 */
10

    
11
/**
12
 * Action: Modify data.
13
 */
14
function rules_action_data_set($wrapper, $value, $settings, $state, $element) {
15
  if ($wrapper instanceof EntityMetadataWrapper) {
16
    try {
17
      // Update the value first then save changes, if possible.
18
      $wrapper->set($value);
19
    }
20
    catch (EntityMetadataWrapperException $e) {
21
      throw new RulesEvaluationException('Unable to modify data "@selector": ' . $e->getMessage(), array('@selector' => $settings['data:select']));
22
    }
23
    // Save changes if a property of a variable has been changed.
24
    if (strpos($element->settings['data:select'], ':') !== FALSE) {
25
      $info = $wrapper->info();
26
      // We always have to save the changes in the parent entity. E.g. when the
27
      // node author is changed, we don't want to save the author but the node.
28
      $state->saveChanges(implode(':', explode(':', $settings['data:select'], -1)), $info['parent']);
29
    }
30
  }
31
  else {
32
    // A not wrapped variable (e.g. a number) is being updated. Just overwrite
33
    // the variable with the new value.
34
    return array('data' => $value);
35
  }
36
}
37

    
38
/**
39
 * Info alter callback for the data_set action.
40
 */
41
function rules_action_data_set_info_alter(&$element_info, $element) {
42
  $element->settings += array('data:select' => NULL);
43
  if ($wrapper = $element->applyDataSelector($element->settings['data:select'])) {
44
    $info = $wrapper->info();
45
    $element_info['parameter']['value']['type'] = $wrapper->type();
46
    $element_info['parameter']['value']['options list']  = !empty($info['options list']) ? 'rules_data_selector_options_list' : FALSE;
47
  }
48
}
49

    
50
/**
51
 * Action: Calculate a value.
52
 */
53
function rules_action_data_calc($input1, $op, $input2, $settings, $state, $element) {
54
  $info = $element->pluginParameterInfo();
55
  // Make sure to apply date offsets intelligently.
56
  if ($info['input_1']['type'] == 'date' && $info['input_2']['type'] == 'duration') {
57
    $input2 = ($op == '-') ? $input2 * -1 : $input2;
58
    return array('result' => (int) RulesDateOffsetProcessor::applyOffset($input1, $input2));
59
  }
60

    
61
  switch ($op) {
62
    case '+':
63
      $result = $input1 + $input2;
64
      break;
65
    case '-':
66
      $result = $input1 - $input2;
67
      break;
68
    case '*':
69
      $result = $input1 * $input2;
70
      break;
71
    case '/':
72
      $result = $input1 / $input2;
73
      break;
74
    case 'min':
75
      $result = min($input1, $input2);
76
      break;
77
    case 'max':
78
      $result = max($input1, $input2);
79
      break;
80
  }
81
  if (isset($result)) {
82
    // Ensure results are valid integer values if necessary.
83
    $variables = $element->providesVariables();
84
    $var_info = reset($variables);
85
    if ($var_info['type'] == 'integer') {
86
      $result = (int) $result;
87
    }
88
    return array('result' => $result);
89
  }
90
}
91

    
92
/**
93
 * Info alter callback for the data_calc action.
94
 */
95
function rules_action_data_calc_info_alter(&$element_info, RulesPlugin $element) {
96
  if ($info = $element->getArgumentInfo('input_1')) {
97
    // Only allow durations as offset for date values.
98
    if ($info['type'] == 'date') {
99
      $element_info['parameter']['input_2']['type'] = 'duration';
100
    }
101
    // Specify the data type of the result.
102
    $element_info['provides']['result']['type'] = $info['type'];
103

    
104
    if ($info['type'] == 'integer' && ($info2 = $element->getArgumentInfo('input_2')) && $info2['type'] == 'decimal') {
105
      $element_info['provides']['result']['type'] = 'decimal';
106
    }
107
    // A division with two integers results in a decimal.
108
    elseif (isset($element->settings['op']) && $element->settings['op'] == '/') {
109
      $element_info['provides']['result']['type'] = 'decimal';
110
    }
111
  }
112
}
113

    
114
/**
115
 * Action: Add a list item.
116
 */
117
function rules_action_data_list_add($list, $item, $unique = FALSE, $pos = 'end', $settings, $state) {
118
  // Optionally, only add the list item if it is not yet contained.
119
  if ($unique && rules_condition_data_list_contains($list, $item, $settings, $state)) {
120
    return;
121
  }
122

    
123
  switch ($pos) {
124
    case 'start':
125
      array_unshift($list, $item);
126
      break;
127

    
128
    default:
129
      $list[] = $item;
130
      break;
131
  }
132
  return array('list' => $list);
133
}
134

    
135
/**
136
 * Info alteration callback for the "Add and Remove a list item" actions.
137
 */
138
function rules_data_list_info_alter(&$element_info, RulesAbstractPlugin $element) {
139
  // Update the required type for the list item if it is known.
140
  $element->settings += array('list:select' => NULL);
141
  if ($wrapper = $element->applyDataSelector($element->settings['list:select'])) {
142
    if ($type = entity_property_list_extract_type($wrapper->type())) {
143
      $info = $wrapper->info();
144
      $element_info['parameter']['item']['type'] = $type;
145
      $element_info['parameter']['item']['options list']  = !empty($info['options list']) ? 'rules_data_selector_options_list' : FALSE;
146
    }
147
  }
148
}
149

    
150
/**
151
 * Action: Remove a list item.
152
 */
153
function rules_action_data_list_remove($list, $item) {
154
  foreach (array_keys($list, $item) as $key) {
155
    unset($list[$key]);
156
  }
157
  return array('list' => $list);
158
}
159

    
160
/**
161
 * Action: Add variable.
162
 */
163
function rules_action_variable_add($args, $element) {
164
  return array('variable_added' => $args['value']);
165
}
166

    
167
/**
168
 * Info alteration callback for variable add action.
169
 */
170
function rules_action_variable_add_info_alter(&$element_info, RulesAbstractPlugin $element) {
171
  if (isset($element->settings['type']) && $type = $element->settings['type']) {
172
    $cache = rules_get_cache();
173
    $type_info = $cache['data_info'][$type];
174
    $element_info['parameter']['value']['type'] = $type;
175
    $element_info['provides']['variable_added']['type'] = $type;
176

    
177
    // For lists, we default to an empty list so subsequent actions can add
178
    // items.
179
    if (entity_property_list_extract_type($type)) {
180
      $element_info['parameter']['value']['default value'] = array();
181
    }
182
  }
183
}
184

    
185
/**
186
 * Action: Convert a value.
187
 */
188
function rules_action_data_convert($arguments, RulesPlugin $element, $state) {
189

    
190
  $value_info = $element->getArgumentInfo('value');
191
  $from_type = $value_info['type'];
192
  $target_type = $arguments['type'];
193

    
194
  // First apply the rounding behavior if given.
195
  if (isset($arguments['rounding_behavior'])) {
196
    switch ($arguments['rounding_behavior']) {
197
      case 'up':
198
        $arguments['value'] = ceil($arguments['value']);
199
        break;
200
      case 'down':
201
        $arguments['value'] = floor($arguments['value']);
202
        break;
203
      default:
204
      case 'round':
205
        $arguments['value'] = round($arguments['value']);
206
        break;
207
    }
208
  }
209

    
210
  switch ($target_type) {
211
    case 'decimal':
212
      $result = floatval($arguments['value']);
213
      break;
214
    case 'integer':
215
      $result = intval($arguments['value']);
216
      break;
217
    case 'text':
218
      $result = strval($arguments['value']);
219
      break;
220
    case 'token':
221
      $result = strval($arguments['value']);
222
      break;
223
  }
224

    
225
  return array('conversion_result' => $result);
226
}
227

    
228
/**
229
 * Info alteration callback for variable add action.
230
 */
231
function rules_action_data_convert_info_alter(&$element_info, RulesAbstractPlugin $element) {
232

    
233
  if (isset($element->settings['type']) && $type = $element->settings['type']) {
234
    $element_info['provides']['conversion_result']['type'] = $type;
235

    
236
    if ($type != 'integer') {
237
      // Only support the rounding behavior option for integers.
238
      unset($element_info['parameter']['rounding_behavior']);
239
    }
240

    
241
    // Configure compatible source-types:
242
    switch ($type) {
243
      case 'integer':
244
        $sources = array('decimal', 'text', 'token', 'uri', 'date', 'duration', 'boolean');
245
        break;
246
      case 'decimal':
247
        $sources = array('integer', 'text', 'token', 'uri', 'date', 'duration', 'boolean');
248
        break;
249
      case 'text':
250
        $sources = array('integer', 'decimal', 'token', 'uri', 'date', 'duration', 'boolean');
251
        break;
252
      case 'token':
253
        $sources = array('integer', 'decimal', 'text', 'uri', 'date', 'duration', 'boolean');
254
        break;
255
    }
256
    $element_info['parameter']['value']['type'] = $sources;
257
  }
258
}
259

    
260
/**
261
 * Action: Create data.
262
 */
263
function rules_action_data_create($args, $element) {
264
  $type = $args['type'];
265
  $values = array();
266
  foreach ($element->pluginParameterInfo() as $name => $info) {
267
    if ($name != 'type') {
268
      // Remove the parameter name prefix 'param_'.
269
      $values[substr($name, 6)] = $args[$name];
270
    }
271
  }
272
  $cache = rules_get_cache();
273
  $type_info = $cache['data_info'][$type];
274
  if (isset($type_info['creation callback'])) {
275
    try {
276
      $data = $type_info['creation callback']($values, $type);
277
      return array('data_created' => $data);
278
    }
279
    catch (EntityMetadataWrapperException $e) {
280
      throw new RulesEvaluationException('Unable to create @data": ' . $e->getMessage(), array('@data' => $type), $element);
281
    }
282
  }
283
  else {
284
    throw new RulesEvaluationException('Unable to create @data, no creation callback found.', array('@data' => $type), $element, RulesLog::ERROR);
285
  }
286
}
287

    
288
/**
289
 * Info alteration callback for data create action.
290
 */
291
function rules_action_data_create_info_alter(&$element_info, RulesAbstractPlugin $element) {
292
  if (!empty($element->settings['type'])) {
293
    $type = $element->settings['type'];
294
    $cache = rules_get_cache();
295
    $type_info = $cache['data_info'][$type];
296
    if (isset($type_info['property info'])) {
297
      // Add the data type's properties as parameters.
298
      foreach ($type_info['property info'] as $property => $property_info) {
299
        // Prefix parameter names to avoid name clashes with existing parameters.
300
        $element_info['parameter']['param_' . $property] = array_intersect_key($property_info, array_flip(array('type', 'label', 'allow null')));
301
        if (empty($property_info['required'])) {
302
          $element_info['parameter']['param_' . $property]['optional'] = TRUE;
303
          $element_info['parameter']['param_' . $property]['allow null'] = TRUE;
304
        }
305
      }
306
    }
307
    $element_info['provides']['data_created']['type'] = $type;
308
  }
309
}
310

    
311
/**
312
 * Creation callback for array structured data.
313
 */
314
function rules_action_data_create_array($values = array(), $type) {
315
  // $values is an array already, so we can just pass it to the wrapper.
316
  return rules_wrap_data($values, array('type' => $type));
317
}
318

    
319
/**
320
 * Condition: Compare data.
321
 */
322
function rules_condition_data_is($data, $op, $value) {
323
  switch ($op) {
324
    default:
325
    case '==':
326
      // In case both values evaluate to FALSE, further differentiate between
327
      // NULL values and values evaluating to FALSE.
328
      if (!$data && !$value) {
329
        return (isset($data) && isset($value)) || (!isset($data) && !isset($value));
330
      }
331
      return $data == $value;
332
    case '<':
333
      return $data < $value;
334
    case '>':
335
      return $data > $value;
336
      // Note: This is deprecated by the text comparison condition and IN below.
337
    case 'contains':
338
      return is_string($data) && strpos($data, $value) !== FALSE || is_array($data) && in_array($value, $data);
339
    case 'IN':
340
      return is_array($value) && in_array($data, $value);
341
  }
342
}
343

    
344
/**
345
 * Info alteration callback for the data_is condition.
346
 *
347
 * If we check the bundle property of a variable, add an assertion so that later
348
 * evaluated elements can make use of this information.
349
 */
350
function rules_condition_data_is_info_alter(&$element_info, RulesAbstractPlugin $element) {
351
  $element->settings += array('data:select' => NULL, 'op' => '==');
352
  if ($wrapper = $element->applyDataSelector($element->settings['data:select'])) {
353
    $info = $wrapper->info();
354
    $element_info['parameter']['value']['type'] = $element->settings['op'] == 'IN' ? 'list<' . $wrapper->type() . '>' : $wrapper->type();
355
    $element_info['parameter']['value']['options list']  = !empty($info['options list']) ? 'rules_data_selector_options_list' : FALSE;
356
  }
357
}
358

    
359
/**
360
 * Condition: List contains.
361
 */
362
function rules_condition_data_list_contains($list, $item, $settings, $state) {
363
  $wrapper = $state->currentArguments['item'];
364
  if ($wrapper instanceof EntityStructureWrapper && $id = $wrapper->getIdentifier()) {
365
    // Check for equal items using the identifier if there is one.
366
    foreach ($state->currentArguments['list'] as $i) {
367
      if ($i->getIdentifier() == $id) {
368
        return TRUE;
369
      }
370
    }
371
    return FALSE;
372
  }
373
  return in_array($item, $list);
374
}
375

    
376
/**
377
* Condition: List count comparison.
378
*/
379
function rules_condition_data_list_count_is($list, $op = '==', $value) {
380
  switch ($op) {
381
    case '==':
382
      return count($list) == $value;
383
    case '<';
384
      return count($list) < $value;
385
    case '>';
386
      return count($list) > $value;
387
  }
388
}
389

    
390
/**
391
 * Condition: Data value is empty.
392
 */
393
function rules_condition_data_is_empty($data) {
394
  // Note that some primitive variables might not be wrapped at all.
395
  if ($data instanceof EntityMetadataWrapper) {
396
    try {
397
      // We cannot use the dataAvailable() method from the wrapper because it
398
      // is protected, so we catch possible exceptions with the value() method.
399
      $value = $data->value();
400
      return empty($value);
401
    }
402
    catch (EntityMetadataWrapperException $e) {
403
      // An exception means that the wrapper is somehow broken and we treat
404
      // that as empty.
405
      return TRUE;
406
    }
407
  }
408
  return empty($data);
409
}
410

    
411
/**
412
 * Condition: Textual comparison.
413
 */
414
function rules_data_text_comparison($text, $text2, $op = 'contains') {
415
  switch ($op) {
416
    case 'contains':
417
      return strpos($text, $text2) !== FALSE;
418
    case 'starts':
419
      return strpos($text, $text2) === 0;
420
    case 'ends':
421
     return strrpos($text, $text2) === (strlen($text) - strlen($text2));
422
    case 'regex':
423
     return (bool) preg_match('/'. str_replace('/', '\\/', $text2) .'/', $text);
424
  }
425
}