Projet

Général

Profil

Paste
Télécharger (12,7 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / entity / entity_token.tokens.inc @ 74f6bef0

1
<?php
2

    
3
/**
4
 * @file
5
 * Provides tokens for entity properties which have no token yet.
6
 */
7

    
8
/**
9
 * Defines the types of properties to be added as token.
10
 *
11
 * @return
12
 *   An array mapping token types to the usual (entity) type names.
13
 */
14
function entity_token_types() {
15
  $return = entity_token_types_chained();
16
  return $return + drupal_map_assoc(array('text', 'integer', 'decimal', 'duration', 'boolean', 'uri'));
17
}
18

    
19
/**
20
 * Defines a list of token types that need to be chained.
21
 *
22
 * @return
23
 *   If a (token) type is given, whether the given type needs to be chained.
24
 *   Else a full list of token types to be chained as returned by
25
 *   entity_token_token_types().
26
 */
27
function entity_token_types_chained($type = NULL) {
28
  // This functions gets called rather often when replacing tokens, thus
29
  // we statically cache $types using the advanced drupal static pattern.
30
  static $drupal_static_fast;
31
  if (!isset($drupal_static_fast)) {
32
    $drupal_static_fast['types'] = &drupal_static(__FUNCTION__, array());
33
  }
34
  $types = &$drupal_static_fast['types'];
35

    
36
  if (!$types) {
37
    // Add entities.
38
    foreach (entity_get_info() as $entity_type => $info) {
39
      if ($token_type = isset($info['token type']) ? $info['token type'] : $entity_type) {
40
        $types[$token_type] = $entity_type;
41
      }
42
    }
43
    // Add 'date' and 'site' tokens.
44
    $types['date'] = 'date';
45
    $types['site'] = 'site';
46
    // Add a 'struct' type.
47
    $types['struct'] = 'struct';
48
  }
49

    
50
  if (isset($type)) {
51
    return isset($types[$type]) || entity_property_list_extract_type($type);
52
  }
53
  return $types;
54
}
55

    
56
/**
57
 * Gets the right token type for a given property info array.
58
 */
59
function _entity_token_map_to_token_type($property_info) {
60
  $lookup = &drupal_static(__FUNCTION__);
61

    
62
  if (!$lookup) {
63
    // Initialize a lookup array mapping property types to token types.
64
    $lookup = array_flip(entity_token_types());
65
  }
66

    
67
  $type = isset($property_info['type']) ? $property_info['type'] : 'text';
68
  // Just use the type 'struct' for all structures.
69
  if (!empty($property_info['property info'])) {
70
    $type = 'struct';
71
  }
72

    
73
  if ($item_type = entity_property_list_extract_type($type)) {
74
    return isset($lookup[$item_type]) ? "list<$lookup[$item_type]>" : FALSE;
75
  }
76
  return isset($lookup[$type]) ? $lookup[$type] : FALSE;
77
}
78

    
79
/**
80
 * Implements hook_token_info_alter().
81
 */
82
function entity_token_token_info_alter(&$info) {
83
  $entity_info = entity_get_info();
84
  $token_types = entity_token_types_chained();
85

    
86
  // Loop over all chain-able token types, as those may contain further tokens,
87
  // e.g. entity types or 'site'.
88
  foreach ($token_types as $token_type => $type) {
89
    // Just add all properties regardless whether it's in a bundle, but only if
90
    // there is no token of the property yet.
91
    foreach (entity_get_all_property_info($type) as $name => $property) {
92
      $name = str_replace('_', '-', $name);
93
      $property += array('type' => 'text', 'description' => $property['label']);
94
      $property_token_type = _entity_token_map_to_token_type($property);
95

    
96
      if (!isset($info['tokens'][$token_type][$name]) && $property_token_type) {
97

    
98
        $info['tokens'][$token_type][$name] = array(
99
          'name' => $property['label'],
100
          'description' => $property['description'],
101
          'type' => $property_token_type,
102
          // Mark the token so we know we have to provide the value afterwards.
103
          'entity-token' => TRUE,
104
        );
105
      }
106
      if ($property_token_type == 'struct' && !empty($property['property info'])) {
107
        $info['tokens'][$token_type][$name]['dynamic'] = TRUE;
108
        $help = array();
109
        foreach ($property['property info'] as $key => $property_info) {
110
          $help[] = $key . ' (' . $property_info['label'] . ')';
111
        }
112
        $info['tokens'][$token_type][$name]['description'] .= ' ' . t('The following properties may be appended to the token: @keys',
113
          array('@keys' => implode(', ', $help))
114
        );
115
      }
116
    }
117
  }
118

    
119
  // Make sure all chain-able token types we support are registered.
120
  foreach ($token_types as $token_type => $type) {
121

    
122
    if (!empty($info['tokens'][$token_type]) && !isset($info['types'][$token_type])) {
123
      if (isset($entity_info[$type])) {
124
        $info['types'][$token_type] = array(
125
          'name' => $entity_info[$type]['label'],
126
          'description' => t('Tokens related to the "@name" entities.', array('@name' => $entity_info[$type]['label'])),
127
          'needs-data' => $token_type,
128
        );
129
      }
130
      else {
131
        $info['types'][$token_type] = array(
132
          'name' => drupal_strtoupper($token_type),
133
          'description' => t('@name tokens.', array('@name' => drupal_strtoupper($token_type))),
134
          'needs-data' => $token_type,
135
        );
136
      }
137
    }
138
    if (!empty($info['tokens'][$token_type]) && !isset($info['types']["list<$token_type>"]) && $token_type != 'site') {
139
      if (isset($entity_info[$type])) {
140
        $info['types']["list<$token_type>"] = array(
141
          'name' => t('List of @entities', array('@entities' => isset($entity_info[$type]['plural label']) ? $entity_info[$type]['plural label'] : $entity_info[$type]['label'] . 's')),
142
          'description' => t('Tokens related to the "@name" entities.', array('@name' => $entity_info[$type]['label'])),
143
          'needs-data' => "list<$token_type>",
144
        );
145
      }
146
      else {
147
        $info['types']["list<$token_type>"] = array(
148
          'name' => t('List of @type values', array('@type' => $token_type)),
149
          'description' => t('Tokens for lists of @type values.', array('@type' => $token_type)),
150
          'needs-data' => "list<$token_type>",
151
        );
152
      }
153
      // Also add some basic token replacements for lists...
154
      for ($i = 0; $i < 4; $i++) {
155
        $info['tokens']["list<$token_type>"][$i] = array(
156
          'name' => t('@type with delta @delta', array('@delta' => $i, '@type' => $info['types'][$token_type]['name'])),
157
          'description' => t('The list item with delta @delta. Delta values start from 0 and are incremented by one per list item.', array('@delta' => $i)),
158
          'type' => $token_type,
159
        );
160
      }
161
    }
162
  }
163
}
164

    
165
/**
166
 * Implements hook_tokens().
167
 */
168
function entity_token_tokens($type, $tokens, array $data = array(), array $options = array()) {
169
  $token_types = entity_token_types_chained();
170
  $replacements = array();
171

    
172
  if (isset($token_types[$type]) && (!empty($data[$type]) || $type == 'site')) {
173
    $data += array($type => FALSE);
174

    
175
    // Make use of token module's token cache if available.
176
    $info = module_exists('token') ? token_get_info() : token_info();
177
    foreach ($tokens as $name => $original) {
178
      // Provide the token for all properties marked to stem from us.
179
      if (!empty($info['tokens'][$type][$name]['entity-token']) || $type == 'struct') {
180
        $wrapper = !isset($wrapper) ? _entity_token_wrap_data($type, $token_types[$type], $data[$type], $options) : $wrapper;
181
        $property_name = str_replace('-', '_', $name);
182
        try {
183
          $replacement = _entity_token_get_token($wrapper->$property_name, $options);
184
          if (isset($replacement)) {
185
            $replacements[$original] = $replacement;
186
          }
187
        }
188
        catch (EntityMetadataWrapperException $e) {
189
          // If tokens for not existing values are requested, just do nothing.
190
        }
191
      }
192
    }
193

    
194
    // Properly chain everything of a type marked as needs chaining.
195
    $info['tokens'] += array($type => array());
196
    foreach ($info['tokens'][$type] as $name => $token_info) {
197
      if (!empty($token_info['entity-token']) && isset($token_info['type']) && entity_token_types_chained($token_info['type'])) {
198

    
199
        if ($chained_tokens = token_find_with_prefix($tokens, $name)) {
200
          $wrapper = !isset($wrapper) ? _entity_token_wrap_data($type, $token_types[$type], $data[$type], $options) : $wrapper;
201
          $property_name = str_replace('-', '_', $name);
202

    
203
          try {
204
            // Pass on 'struct' properties wrapped, else un-wrap the data.
205
            $value = ($token_info['type'] == 'struct') ? $wrapper->$property_name : $wrapper->$property_name->value();
206
            $replacements += token_generate($token_info['type'], $chained_tokens, array($token_info['type'] => $value), $options);
207
          }
208
          catch (EntityMetadataWrapperException $e) {
209
            // If tokens for not existing values are requested, just do nothing.
210
          }
211
        }
212
      }
213
    }
214
  }
215
  // Add support for evaluating tokens for "list<type"> types.
216
  elseif ($item_token_type = entity_property_list_extract_type($type)) {
217
    foreach ($tokens as $name => $original) {
218
      // Care about getting entries of a list.
219
      if (is_numeric($name)) {
220
        $wrapper = !isset($wrapper) ? _entity_token_wrap_data($type, "list<$token_types[$item_token_type]>", $data[$type], $options) : $wrapper;
221
        try {
222
          $replacement = _entity_token_get_token($wrapper->get($name), $options);
223
          if (isset($replacement)) {
224
            $replacements[$original] = $replacement;
225
          }
226
        }
227
        catch (EntityMetadataWrapperException $e) {
228
          // If tokens for not existing values are requested, just do nothing.
229
        }
230
      }
231
      // Care about generating chained tokens for list-items.
232
      else {
233
        $parts = explode(':', $name, 2);
234
        $delta = $parts[0];
235

    
236
        if (is_numeric($delta) && $chained_tokens = token_find_with_prefix($tokens, $delta)) {
237
          $wrapper = !isset($wrapper) ? _entity_token_wrap_data($type, "list<$token_types[$item_token_type]>", $data[$type], $options) : $wrapper;
238
          try {
239
            $replacements += token_generate($item_token_type, $chained_tokens, array($item_token_type => $wrapper->get($delta)->value()), $options);
240
          }
241
          catch (EntityMetadataWrapperException $e) {
242
            // If tokens for not existing values are requested, just do nothing.
243
          }
244
        }
245
      }
246
    }
247
  }
248

    
249
  // Add support for chaining struct data. As struct data has no registered
250
  // tokens, we have to chain based upon wrapper property info.
251
  if ($type == 'struct') {
252
    $wrapper = $data[$type];
253
    foreach ($wrapper as $name => $property) {
254
      $token_type = _entity_token_map_to_token_type($property->info());
255

    
256
      if (entity_token_types_chained($token_type) && $chained_tokens = token_find_with_prefix($tokens, $name)) {
257
        try {
258
          // Pass on 'struct' properties wrapped, else un-wrap the data.
259
          $value = ($token_type == 'struct') ? $property : $property->value();
260
          $replacements += token_generate($token_type, $chained_tokens, array($token_type => $value), $options);
261
        }
262
        catch (EntityMetadataWrapperException $e) {
263
          // If tokens for not existing values are requested, just do nothing.
264
        }
265
      }
266
    }
267
  }
268

    
269
  return $replacements;
270
}
271

    
272
/**
273
 * Wraps the given data by correctly obeying the options.
274
 */
275
function _entity_token_wrap_data($token_type, $type, $data, $options) {
276
  if ($type == 'site') {
277
    $wrapper = entity_metadata_site_wrapper();
278
  }
279
  elseif ($type == 'struct') {
280
    // 'struct' data items are passed on wrapped.
281
    $wrapper = $data;
282
  }
283
  else {
284
    $wrapper = entity_metadata_wrapper($type, $data);
285
  }
286
  if (isset($options['language']) && $wrapper instanceof EntityStructureWrapper) {
287
    $wrapper->language($options['language']->language);
288
  }
289
  return $wrapper;
290
}
291

    
292
/**
293
 * Gets the token replacement by correctly obeying the options.
294
 */
295
function _entity_token_get_token($wrapper, $options) {
296

    
297
  if ($wrapper->value() === NULL) {
298
    // Do not provide a replacement if there is no value.
299
    return NULL;
300
  }
301

    
302
  if (empty($options['sanitize'])) {
303
    // When we don't need sanitized tokens decode already sanitizied texts.
304
    $options['decode'] = TRUE;
305
  }
306
  $langcode = isset($options['language']) ? $options['language']->language : NULL;
307

    
308
  // If there is a label for a property, e.g. defined by an options list or an
309
  // entity label, make use of it.
310
  if ($label = $wrapper->label()) {
311
    return empty($options['sanitize']) ? $label : check_plain($label);
312
  }
313

    
314
  switch ($wrapper->type()) {
315
    case 'integer':
316
      return $wrapper->value();
317
    case 'decimal':
318
      return number_format($wrapper->value(), 2);
319
    case 'date':
320
      return format_date($wrapper->value(), 'medium', '', NULL, $langcode);
321
    case 'duration':
322
      return format_interval($wrapper->value(), 2, $langcode);
323
    case 'boolean':
324
      return $wrapper->value() ? t('true') : t('false');
325
    case 'uri':
326
    case 'text':
327
      return $wrapper->value($options);
328
  }
329

    
330
  // Care for outputing list values.
331
  if ($wrapper instanceof EntityListWrapper) {
332
    $output = array();
333
    foreach ($wrapper as $item) {
334
      $output[] = _entity_token_get_token($item, $options);
335
    }
336
    return implode(', ', $output);
337
  }
338
  // Else we do not have a good string to output, e.g. for struct values. Just
339
  // output the string representation of the wrapper.
340
  return (string) $wrapper;
341
}