search.rb 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class Service::Translation::Search < Service::Base
  3. attr_reader :locale, :query, :limit, :collector_mode
  4. def initialize(locale:, query:, limit: 150)
  5. super()
  6. @locale = locale
  7. @query = query
  8. @limit = limit
  9. @collector_mode = query.blank? || query.strip.empty? ? :list : :search
  10. end
  11. def execute
  12. items = []
  13. total_count = 0
  14. Service::Translation::Search::Collector.collector_suggestions.each do |collector_module|
  15. collector = collector_module.new(locale:, query:, limit:, mode: collector_mode)
  16. # Filter out already existing suggestion from other collectors (e.g. same naming in object attributes and priority names).
  17. suggestions = collector.result.reject { |suggestion| items.pluck(:source).include?(suggestion[:source]) }
  18. items.concat(suggestions)
  19. total_count += suggestions.length
  20. end
  21. # Add existing translation at the end.
  22. items.concat(translations[:items])
  23. {
  24. items: items.take(limit),
  25. total_count: total_count + translations[:total_count]
  26. }
  27. end
  28. private
  29. def translations
  30. @translations ||= begin
  31. items = []
  32. total_count = 0
  33. Service::Translation::Search::Collector.collector_translations.each do |collector_module|
  34. collector = collector_module.new(locale:, query:, limit:, mode: collector_mode)
  35. items.concat collector.result
  36. total_count += collector.count
  37. end
  38. {
  39. items: items,
  40. total_count: total_count
  41. }
  42. end
  43. end
  44. end