uc_coupon_handler_field_codes.inc 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. /**
  3. * @file
  4. * Views handler for a list of bulk codes based on a coupon
  5. */
  6. /**
  7. * Generate a list of the codes associated with this coupon
  8. */
  9. class uc_coupon_handler_field_codes extends views_handler_field_prerender_list {
  10. /**
  11. * Define option default values.
  12. */
  13. function option_definition() {
  14. $options = parent::option_definition();
  15. $options['max_num'] = array('default' => 0);
  16. $options['scope'] = array('default' => 'all');
  17. return $options;
  18. }
  19. /**
  20. * Provide options to limit number of codes, and to limit to coupons which still have uses remaining (or which don't)
  21. */
  22. function options_form(&$form, &$form_state) {
  23. parent::options_form($form, $form_state);
  24. $form['max_num'] = array(
  25. '#title' => t('Maximum number of codes to list (or 0 for unlimited)'),
  26. '#type' => 'textfield',
  27. '#default_value' => $this->options['max_num'],
  28. );
  29. $form['scope'] = array(
  30. '#type' => 'radios',
  31. '#title' => t('Codes to display'),
  32. '#options' => array(
  33. 'all' => t('All'),
  34. 'avail' => t('Available codes'),
  35. 'used' => t('Unavailable codes'),
  36. ),
  37. '#default_value' => $this->options['scope'],
  38. );
  39. }
  40. /**
  41. * Expand the coupon codes for each coupon in the result set.
  42. *
  43. * @see views_handler_field::pre_render()
  44. */
  45. function pre_render($values) {
  46. foreach ($values as $value) {
  47. $cid = $value->{$this->field_alias};
  48. $coupon = uc_coupon_load($cid);
  49. // Find the maximum number of codes to display.
  50. $limit = $coupon->bulk ? $coupon->data['bulk_number'] : 1;
  51. if ($this->options['max_num'] && $this->options['max_num'] < $limit) {
  52. $limit = $this->options['max_num'];
  53. }
  54. $coupon->usage = uc_coupon_count_usage($cid);
  55. // List selected coupons.
  56. for ($i = 0; $i < $limit; $i++) {
  57. $icoupon = $limit > 1 ? clone $coupon : $coupon;
  58. if ($coupon->bulk) {
  59. $icoupon->code = uc_coupon_get_bulk_code($coupon, $i);
  60. }
  61. if ($this->include_coupon($icoupon)) {
  62. $this->items[$cid][] = array('coupon' => $icoupon);
  63. }
  64. }
  65. }
  66. }
  67. function include_coupon($coupon) {
  68. if ($this->options['scope'] == 'all') {
  69. return TRUE;
  70. }
  71. else {
  72. $uses = $coupon->usage['codes'][$coupon->code];
  73. $unused = $coupon->max_uses == 0 || $coupon->max_uses > $uses;
  74. return $unused xor $this->options['scope'] == 'used';
  75. }
  76. }
  77. /**
  78. * Render a single coupon code.
  79. */
  80. function render_item($count, $item) {
  81. return theme('uc_coupon_code', array('coupon' => $item['coupon']));
  82. }
  83. }