summaryrefslogtreecommitdiff
path: root/app/finders/design_management/versions_finder.rb
blob: c4aefd3078e9927659d48c46092f6593762f0ce8 (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
# frozen_string_literal: true

module DesignManagement
  class VersionsFinder
    attr_reader :design_or_collection, :current_user, :params

    # The `design_or_collection` argument should be either a:
    #
    # - DesignManagement::Design, or
    # - DesignManagement::DesignCollection
    #
    # The object will have `#versions` called on it to set up the
    # initial scope of the versions.
    #
    # valid params:
    #   - earlier_or_equal_to: Version
    #   - sha: String
    #   - version_id: Integer
    #
    def initialize(design_or_collection, current_user, params = {})
      @design_or_collection = design_or_collection
      @current_user = current_user
      @params = params
    end

    def execute
      unless Ability.allowed?(current_user, :read_design, design_or_collection)
        return ::DesignManagement::Version.none
      end

      items = design_or_collection.versions
      items = by_earlier_or_equal_to(items)
      items = by_sha(items)
      items = by_version_id(items)
      items.ordered
    end

    private

    def by_earlier_or_equal_to(items)
      return items unless params[:earlier_or_equal_to]

      items.earlier_or_equal_to(params[:earlier_or_equal_to])
    end

    def by_version_id(items)
      return items unless params[:version_id]

      items.id_in(params[:version_id])
    end

    def by_sha(items)
      return items unless params[:sha]

      items.by_sha(params[:sha])
    end
  end
end