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