CommentersSorter.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-License-Identifier: AGPL-3.0-or-later
  5. */
  6. namespace OCA\Comments\Collaboration;
  7. use OCP\Collaboration\AutoComplete\ISorter;
  8. use OCP\Comments\ICommentsManager;
  9. class CommentersSorter implements ISorter {
  10. public function __construct(
  11. private ICommentsManager $commentsManager,
  12. ) {
  13. }
  14. public function getId(): string {
  15. return 'commenters';
  16. }
  17. /**
  18. * Sorts people who commented on the given item atop (descelating) of the
  19. * others
  20. *
  21. * @param array &$sortArray
  22. * @param array $context
  23. */
  24. public function sort(array &$sortArray, array $context): void {
  25. $commenters = $this->retrieveCommentsInformation($context['itemType'], $context['itemId']);
  26. if (count($commenters) === 0) {
  27. return;
  28. }
  29. foreach ($sortArray as $type => &$byType) {
  30. if (!isset($commenters[$type])) {
  31. continue;
  32. }
  33. // at least on PHP 5.6 usort turned out to be not stable. So we add
  34. // the current index to the value and compare it on a draw
  35. $i = 0;
  36. $workArray = array_map(function ($element) use (&$i) {
  37. return [$i++, $element];
  38. }, $byType);
  39. usort($workArray, function ($a, $b) use ($commenters, $type) {
  40. $r = $this->compare($a[1], $b[1], $commenters[$type]);
  41. if ($r === 0) {
  42. $r = $a[0] - $b[0];
  43. }
  44. return $r;
  45. });
  46. // and remove the index values again
  47. $byType = array_column($workArray, 1);
  48. }
  49. }
  50. /**
  51. * @return array<string, array<string, int>>
  52. */
  53. protected function retrieveCommentsInformation(string $type, string $id): array {
  54. $comments = $this->commentsManager->getForObject($type, $id);
  55. if (count($comments) === 0) {
  56. return [];
  57. }
  58. $actors = [];
  59. foreach ($comments as $comment) {
  60. if (!isset($actors[$comment->getActorType()])) {
  61. $actors[$comment->getActorType()] = [];
  62. }
  63. if (!isset($actors[$comment->getActorType()][$comment->getActorId()])) {
  64. $actors[$comment->getActorType()][$comment->getActorId()] = 1;
  65. } else {
  66. $actors[$comment->getActorType()][$comment->getActorId()]++;
  67. }
  68. }
  69. return $actors;
  70. }
  71. protected function compare(array $a, array $b, array $commenters): int {
  72. $a = $a['value']['shareWith'];
  73. $b = $b['value']['shareWith'];
  74. $valueA = $commenters[$a] ?? 0;
  75. $valueB = $commenters[$b] ?? 0;
  76. return $valueB - $valueA;
  77. }
  78. }