searchresultsorter.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. /**
  3. * Copyright (c) 2014 Arthur Schiwon <blizzz@owncloud.com>
  4. * This file is licensed under the Affero General Public License version 3 or
  5. * later.
  6. * See the COPYING-README file.
  7. *
  8. */
  9. namespace OC\Share;
  10. class SearchResultSorter {
  11. private $search;
  12. private $encoding;
  13. private $key;
  14. private $log;
  15. /**
  16. * @param string $search the search term as was given by the user
  17. * @param string $key the array key containing the value that should be compared
  18. * against
  19. * @param string $encoding optional, encoding to use, defaults to UTF-8
  20. * @param \OC\Log $log optional
  21. */
  22. public function __construct($search, $key, \OC\Log $log = null, $encoding = 'UTF-8') {
  23. $this->encoding = $encoding;
  24. $this->key = $key;
  25. $this->log = $log;
  26. $this->search = mb_strtolower($search, $this->encoding);
  27. }
  28. /**
  29. * User and Group names matching the search term at the beginning shall appear
  30. * on top of the share dialog. Following entries in alphabetical order.
  31. * Callback function for usort. http://php.net/usort
  32. */
  33. public function sort($a, $b) {
  34. if(!isset($a[$this->key]) || !isset($b[$this->key])) {
  35. if(!is_null($this->log)) {
  36. $this->log->error('Sharing dialogue: cannot sort due to ' .
  37. 'missing array key', array('app' => 'core'));
  38. }
  39. return 0;
  40. }
  41. $nameA = mb_strtolower($a[$this->key], $this->encoding);
  42. $nameB = mb_strtolower($b[$this->key], $this->encoding);
  43. $i = mb_strpos($nameA, $this->search, 0, $this->encoding);
  44. $j = mb_strpos($nameB, $this->search, 0, $this->encoding);
  45. if($i === $j || $i > 0 && $j > 0) {
  46. return strcmp(mb_strtolower($nameA, $this->encoding),
  47. mb_strtolower($nameB, $this->encoding));
  48. } elseif ($i === 0) {
  49. return -1;
  50. } else {
  51. return 1;
  52. }
  53. }
  54. }