Welcome to mirror list, hosted at ThFree Co, Russian Federation.

count_service.rb « snippets « services « app - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: ba421c5777e263b9ccc58316818b2669f7a6f571 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# frozen_string_literal: true

# Service for calculating visible Snippet counts via one query
# for the given user or project.
#
# Authorisation level checks will be included, ensuring the correct
# counts will be returned for the given user (if any).
#
# Basic usage:
#
#   user = User.find(1)
#
#   Snippets::CountService.new(user, author: user).execute
#   #=> {
#     are_public: 1,
#     are_internal: 1,
#     are_private: 1,
#     all: 3
#   }
#
# Counts can be scoped to a project:
#
#   user = User.find(1)
#   project = Project.find(1)
#
#   Snippets::CountService.new(user, project: project).execute
#   #=> {
#     are_public: 1,
#     are_internal: 1,
#     are_private: 0,
#     all: 2
#   }
#
# Either a project or an author *must* be supplied.
module Snippets
  class CountService
    def initialize(current_user, author: nil, project: nil)
      if !author && !project
        raise(
          ArgumentError, 'Must provide either an author or a project'
        )
      end

      @snippets_finder = SnippetsFinder.new(current_user, author: author, project: project)
    end

    def execute
      counts = snippet_counts
      return {} unless counts

      counts.slice(
        :are_public,
        :are_private,
        :are_internal,
        :are_public_or_internal,
        :total
      )
    end

    private

    # rubocop: disable CodeReuse/ActiveRecord
    def snippet_counts
      @snippets_finder.execute
        .reorder(nil)
        .select("
          count(case when snippets.visibility_level=#{Snippet::PUBLIC} and snippets.secret is FALSE then 1 else null end) as are_public,
          count(case when snippets.visibility_level=#{Snippet::INTERNAL} then 1 else null end) as are_internal,
          count(case when snippets.visibility_level=#{Snippet::PRIVATE} then 1 else null end) as are_private,
          count(case when visibility_level=#{Snippet::PUBLIC} OR visibility_level=#{Snippet::INTERNAL} then 1 else null end) as are_public_or_internal,
          count(*) as total
        ")
        .take
    end
    # rubocop: enable CodeReuse/ActiveRecord
  end
end