SubscriberRegexBuilder.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace dokuwiki\Subscriptions;
  3. use Exception;
  4. class SubscriberRegexBuilder
  5. {
  6. /**
  7. * Construct a regular expression for parsing a subscription definition line
  8. *
  9. * @param string|array $user
  10. * @param string|array $style
  11. * @param string|array $data
  12. *
  13. * @return string complete regexp including delimiters
  14. * @throws Exception when no data is passed
  15. * @author Andreas Gohr <andi@splitbrain.org>
  16. *
  17. */
  18. public function buildRegex($user = null, $style = null, $data = null)
  19. {
  20. // always work with arrays
  21. $user = (array)$user;
  22. $style = (array)$style;
  23. $data = (array)$data;
  24. // clean
  25. $user = array_filter(array_map('trim', $user));
  26. $style = array_filter(array_map('trim', $style));
  27. $data = array_filter(array_map('trim', $data));
  28. // user names are encoded
  29. $user = array_map('auth_nameencode', $user);
  30. // quote
  31. $user = array_map('preg_quote_cb', $user);
  32. $style = array_map('preg_quote_cb', $style);
  33. $data = array_map('preg_quote_cb', $data);
  34. // join
  35. $user = join('|', $user);
  36. $style = join('|', $style);
  37. $data = join('|', $data);
  38. // any data at all?
  39. if ($user . $style . $data === '') {
  40. throw new Exception('no data passed');
  41. }
  42. // replace empty values, set which ones are optional
  43. $sopt = '';
  44. $dopt = '';
  45. if ($user === '') {
  46. $user = '\S+';
  47. }
  48. if ($style === '') {
  49. $style = '\S+';
  50. $sopt = '?';
  51. }
  52. if ($data === '') {
  53. $data = '\S+';
  54. $dopt = '?';
  55. }
  56. // assemble
  57. return "/^($user)(?:\\s+($style))$sopt(?:\\s+($data))$dopt$/";
  58. }
  59. }