SearchResultSorter.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Morris Jobke <hey@morrisjobke.de>
  7. * @author Robin McCorkell <robin@mccorkell.me.uk>
  8. * @author Roeland Jago Douma <roeland@famdouma.nl>
  9. *
  10. * @license AGPL-3.0
  11. *
  12. * This code is free software: you can redistribute it and/or modify
  13. * it under the terms of the GNU Affero General Public License, version 3,
  14. * as published by the Free Software Foundation.
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. * GNU Affero General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU Affero General Public License, version 3,
  22. * along with this program. If not, see <http://www.gnu.org/licenses/>
  23. *
  24. */
  25. namespace OC\Share;
  26. use OCP\ILogger;
  27. class SearchResultSorter {
  28. private $search;
  29. private $encoding;
  30. private $key;
  31. private $log;
  32. /**
  33. * @param string $search the search term as was given by the user
  34. * @param string $key the array key containing the value that should be compared
  35. * against
  36. * @param string $encoding optional, encoding to use, defaults to UTF-8
  37. * @param ILogger $log optional
  38. */
  39. public function __construct($search, $key, ILogger $log = null, $encoding = 'UTF-8') {
  40. $this->encoding = $encoding;
  41. $this->key = $key;
  42. $this->log = $log;
  43. $this->search = mb_strtolower($search, $this->encoding);
  44. }
  45. /**
  46. * User and Group names matching the search term at the beginning shall appear
  47. * on top of the share dialog. Following entries in alphabetical order.
  48. * Callback function for usort. http://php.net/usort
  49. */
  50. public function sort($a, $b) {
  51. if(!isset($a[$this->key]) || !isset($b[$this->key])) {
  52. if(!is_null($this->log)) {
  53. $this->log->error('Sharing dialogue: cannot sort due to ' .
  54. 'missing array key', array('app' => 'core'));
  55. }
  56. return 0;
  57. }
  58. $nameA = mb_strtolower($a[$this->key], $this->encoding);
  59. $nameB = mb_strtolower($b[$this->key], $this->encoding);
  60. $i = mb_strpos($nameA, $this->search, 0, $this->encoding);
  61. $j = mb_strpos($nameB, $this->search, 0, $this->encoding);
  62. if($i === $j || $i > 0 && $j > 0) {
  63. return strcmp(mb_strtolower($nameA, $this->encoding),
  64. mb_strtolower($nameB, $this->encoding));
  65. } elseif ($i === 0) {
  66. return -1;
  67. } else {
  68. return 1;
  69. }
  70. }
  71. }