Manager.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-License-Identifier: AGPL-3.0-or-later
  5. */
  6. namespace OC\Collaboration\AutoComplete;
  7. use OCP\Collaboration\AutoComplete\IManager;
  8. use OCP\Collaboration\AutoComplete\ISorter;
  9. use Psr\Container\ContainerExceptionInterface;
  10. use Psr\Container\ContainerInterface;
  11. use Psr\Log\LoggerInterface;
  12. class Manager implements IManager {
  13. /** @var string[] */
  14. protected array $sorters = [];
  15. /** @var ISorter[] */
  16. protected array $sorterInstances = [];
  17. public function __construct(
  18. private ContainerInterface $container,
  19. private LoggerInterface $logger,
  20. ) {
  21. }
  22. public function runSorters(array $sorters, array &$sortArray, array $context): void {
  23. $sorterInstances = $this->getSorters();
  24. while ($sorter = array_shift($sorters)) {
  25. if (isset($sorterInstances[$sorter])) {
  26. $sorterInstances[$sorter]->sort($sortArray, $context);
  27. } else {
  28. $this->logger->warning('No sorter for ID "{id}", skipping', [
  29. 'app' => 'core', 'id' => $sorter
  30. ]);
  31. }
  32. }
  33. }
  34. public function registerSorter($className): void {
  35. $this->sorters[] = $className;
  36. }
  37. protected function getSorters(): array {
  38. if (count($this->sorterInstances) === 0) {
  39. foreach ($this->sorters as $sorter) {
  40. try {
  41. $instance = $this->container->get($sorter);
  42. } catch (ContainerExceptionInterface) {
  43. $this->logger->notice(
  44. 'Skipping not registered sorter. Class name: {class}',
  45. ['app' => 'core', 'class' => $sorter],
  46. );
  47. continue;
  48. }
  49. if (!$instance instanceof ISorter) {
  50. $this->logger->notice('Skipping sorter which is not an instance of ISorter. Class name: {class}',
  51. ['app' => 'core', 'class' => $sorter]);
  52. continue;
  53. }
  54. $sorterId = trim($instance->getId());
  55. if (trim($sorterId) === '') {
  56. $this->logger->notice('Skipping sorter with empty ID. Class name: {class}',
  57. ['app' => 'core', 'class' => $sorter]);
  58. continue;
  59. }
  60. $this->sorterInstances[$sorterId] = $instance;
  61. }
  62. }
  63. return $this->sorterInstances;
  64. }
  65. }