Provide "shift" and "pop" array tokens

Public
</> CopyGet raw version
php
  1. /**
  2.  * Implements hook_token_info().
  3.  */
  4. function MY_MODULE_token_info() {
  5. $info = array();
  6.  
  7. $info['tokens']['array']['shift'] = array(
  8. 'name' => t('Shift'),
  9. 'description' => t('Remove the first item from an array'),
  10. 'type' => 'array',
  11. );
  12.  
  13. $info['tokens']['array']['pop'] = array(
  14. 'name' => t('Pop'),
  15. 'description' => t('Remove the last item from an array'),
  16. 'type' => 'array',
  17. );
  18.  
  19. return $info;
  20. }
  21.  
  22. /**
  23.  * Implements hook_tokens().
  24.  */
  25. function MY_MODULE_tokens($type, $tokens, array $data = array(), array $options = array()) {
  26. $replacements = array();
  27.  
  28. if ($type == 'array' && !empty($data['array']) && is_array($data['array'])) {
  29. $array = $data['array'];
  30.  
  31. foreach ($tokens as $name => $original) {
  32. switch ($name) {
  33.  
  34. case 'shift':
  35. array_shift($array); // Remove the first item.
  36. $replacements[$original] = token_render_array($array, $options);
  37. break;
  38. case 'pop':
  39. array_pop($array); // Remove the last item.
  40. $replacements[$original] = token_render_array($array, $options);
  41. break;
  42. }
  43. }
  44.  
  45. // [array:shift:*] chained tokens.
  46. if ($shifted_tokens = token_find_with_prefix($tokens, 'shift')) {
  47. array_shift($array); // Remove the first item.
  48. $replacements += token_generate('array', $shifted_tokens, array('array' => $array), array('array sort' => FALSE) + $options);
  49. }
  50.  
  51. // [array:pop:*] chained tokens.
  52. if ($popped_tokens = token_find_with_prefix($tokens, 'pop')) {
  53. array_pop($array); // Remove the last item.
  54. $replacements += token_generate('array', $popped_tokens, array('array' => $array), array('array sort' => FALSE) + $options);
  55. }
  56. }
  57.  
  58. return $replacements;
  59. }