Acronym.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. namespace dokuwiki\Parsing\ParserMode;
  3. class Acronym extends AbstractMode
  4. {
  5. // A list
  6. protected $acronyms = array();
  7. protected $pattern = '';
  8. /**
  9. * Acronym constructor.
  10. *
  11. * @param string[] $acronyms
  12. */
  13. public function __construct($acronyms)
  14. {
  15. usort($acronyms, array($this,'compare'));
  16. $this->acronyms = $acronyms;
  17. }
  18. /** @inheritdoc */
  19. public function preConnect()
  20. {
  21. if (!count($this->acronyms)) return;
  22. $bound = '[\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]';
  23. $acronyms = array_map(['\\dokuwiki\\Parsing\\Lexer\\Lexer', 'escape'], $this->acronyms);
  24. $this->pattern = '(?<=^|'.$bound.')(?:'.join('|', $acronyms).')(?='.$bound.')';
  25. }
  26. /** @inheritdoc */
  27. public function connectTo($mode)
  28. {
  29. if (!count($this->acronyms)) return;
  30. if (strlen($this->pattern) > 0) {
  31. $this->Lexer->addSpecialPattern($this->pattern, $mode, 'acronym');
  32. }
  33. }
  34. /** @inheritdoc */
  35. public function getSort()
  36. {
  37. return 240;
  38. }
  39. /**
  40. * sort callback to order by string length descending
  41. *
  42. * @param string $a
  43. * @param string $b
  44. *
  45. * @return int
  46. */
  47. protected function compare($a, $b)
  48. {
  49. $a_len = strlen($a);
  50. $b_len = strlen($b);
  51. if ($a_len > $b_len) {
  52. return -1;
  53. } elseif ($a_len < $b_len) {
  54. return 1;
  55. }
  56. return 0;
  57. }
  58. }