A regular expression Views filter handler which allows for extensibility.

Public

</> CopyGet raw version
php
  1. <?php
  2.  
  3. // @file views_block.views.inc
  4. function views_block_views_data() {
  5. [..]
  6. // Body
  7. $data['block_custom']['body'] = array(
  8. 'title' => t('Body'),
  9. 'help' => t('The block body.'),
  10. 'field' => array(
  11. 'handler' => 'views_handler_field',
  12. ),
  13. 'filter' => array(
  14. 'handler' => 'views_handler_filter_regex',
  15. ),
  16. );
  17. [..]
  18. return $data;
  19. }
  20.  
  21.  
  22. // @file views_handler_filter_regex.inc
  23. class views_handler_filter_regex extends views_handler_filter {
  24. var $always_multiple = TRUE;
  25.  
  26. function operator_options() {
  27. // Return placeholders that will be expanded at query creation time.
  28. return array(
  29. 'match' => t('Matches regex'),
  30. 'nomatch' => t('Does not match regex'),
  31. );
  32. }
  33.  
  34. function admin_summary() {
  35. if (!empty($this->options['exposed'])) {
  36. return t('exposed');
  37. }
  38. return parent::admin_summary();
  39. }
  40.  
  41. function value_form(&$form, &$form_state) {
  42. $form['value'] = array(
  43. '#type' => 'textfield',
  44. '#title' => t('Value'),
  45. '#size' => 30,
  46. '#default_value' => $this->value,
  47. );
  48. }
  49.  
  50. function query() {
  51. // Find actual regex operators depending on database type.
  52. $db_type = Database::getConnection()->databaseType();
  53. switch ($db_type) {
  54. case 'mysql':
  55. $match = 'REGEXP';
  56. $nomatch = 'NOT REGEXP';
  57. break;
  58. case 'pgsql':
  59. $match = '*~'; // case insensitive match
  60. $nomatch = '!*~';
  61. break;
  62. default:
  63. // Allow other modules to define these operators.
  64. $operators = &drupal_static(__METHOD__);
  65. if (empty($operators)) {
  66. // hook_views_regex_operators($db_type)
  67. // @param $db_type - the type of database engine being used ('mysql' and 'pgsql' will not be called).
  68. // @return array('match' => operator for matching, 'not match' => operator for negative matching);
  69. $operators = module_invoke_all('views_regex_operators', $db_type);
  70. }
  71. if (empty($operators)) {
  72. watchdog('views_regex', 'No regex operators found for database type %type.', array('%type' => $db_type));
  73. return array();
  74. }
  75. $match = $operators['match'];
  76. $nomatch = $operators['not match'];
  77. }
  78. // Replace placeholder with actual operator.
  79. $this->operator = $this->operator === 'match' ? $match : $nomatch;
  80. parent::query();
  81. }
  82. }