/lib/DAV/StringUtil.php

https://github.com/fruux/sabre-dav · PHP · 91 lines · 40 code · 18 blank · 33 comment · 4 complexity · 005c497470fb89d1b8f4f90b580ed08d MD5 · raw file

  1. <?php declare (strict_types=1);
  2. namespace Sabre\DAV;
  3. /**
  4. * String utility
  5. *
  6. * This class is mainly used to implement the 'text-match' filter, used by both
  7. * the CalDAV calendar-query REPORT, and CardDAV addressbook-query REPORT.
  8. * Because they both need it, it was decided to put it in Sabre\DAV instead.
  9. *
  10. * @copyright Copyright (C) fruux GmbH (https://fruux.com/)
  11. * @author Evert Pot (http://evertpot.com/)
  12. * @license http://sabre.io/license/ Modified BSD License
  13. */
  14. class StringUtil {
  15. /**
  16. * Checks if a needle occurs in a haystack ;)
  17. *
  18. * @param string $haystack
  19. * @param string $needle
  20. * @param string $collation
  21. * @param string $matchType
  22. * @return bool
  23. */
  24. static function textMatch($haystack, $needle, $collation, $matchType = 'contains') {
  25. switch ($collation) {
  26. case 'i;ascii-casemap' :
  27. // default strtolower takes locale into consideration
  28. // we don't want this.
  29. $haystack = str_replace(range('a', 'z'), range('A', 'Z'), $haystack);
  30. $needle = str_replace(range('a', 'z'), range('A', 'Z'), $needle);
  31. break;
  32. case 'i;octet' :
  33. // Do nothing
  34. break;
  35. case 'i;unicode-casemap' :
  36. $haystack = mb_strtoupper($haystack, 'UTF-8');
  37. $needle = mb_strtoupper($needle, 'UTF-8');
  38. break;
  39. default :
  40. throw new Exception\BadRequest('Collation type: ' . $collation . ' is not supported');
  41. }
  42. switch ($matchType) {
  43. case 'contains' :
  44. return strpos($haystack, $needle) !== false;
  45. case 'equals' :
  46. return $haystack === $needle;
  47. case 'starts-with' :
  48. return strpos($haystack, $needle) === 0;
  49. case 'ends-with' :
  50. return strrpos($haystack, $needle) === strlen($haystack) - strlen($needle);
  51. default :
  52. throw new Exception\BadRequest('Match-type: ' . $matchType . ' is not supported');
  53. }
  54. }
  55. /**
  56. * This method takes an input string, checks if it's not valid UTF-8 and
  57. * attempts to convert it to UTF-8 if it's not.
  58. *
  59. * Note that currently this can only convert ISO-8859-1 to UTF-8 (latin-1),
  60. * anything else will likely fail.
  61. *
  62. * @param string $input
  63. * @return string
  64. */
  65. static function ensureUTF8($input) {
  66. $encoding = mb_detect_encoding($input, ['UTF-8', 'ISO-8859-1'], true);
  67. if ($encoding === 'ISO-8859-1') {
  68. return utf8_encode($input);
  69. } else {
  70. return $input;
  71. }
  72. }
  73. }