main
 1# frozen_string_literal: true
 2
 3module Scim
 4  module Kit
 5    module V2
 6      # Represents an application SCIM configuration.
 7      class Configuration
 8        # @private
 9        class Builder
10          attr_reader :configuration
11
12          def initialize(configuration)
13            @configuration = configuration
14          end
15
16          def service_provider_configuration(location:)
17            configuration.service_provider_configuration =
18              ServiceProviderConfiguration.new(location: location)
19            yield configuration.service_provider_configuration
20          end
21
22          def resource_type(id:, location:)
23            configuration.resource_types[id] ||=
24              ResourceType.new(location: location)
25            configuration.resource_types[id].id = id
26            yield configuration.resource_types[id]
27          end
28
29          def schema(id:, name:, location:)
30            configuration.schemas[id] ||= Schema.new(
31              id: id,
32              name: name,
33              location: location
34            )
35            yield configuration.schemas[id]
36          end
37        end
38
39        attr_accessor :service_provider_configuration
40        attr_accessor :resource_types
41        attr_accessor :schemas
42
43        def initialize(http: Scim::Kit::Http.new)
44          @http = http
45          @resource_types = {}
46          @schemas = {}
47
48          yield Builder.new(self) if block_given?
49        end
50
51        def load_from(base_url)
52          base_url = "#{base_url}/"
53          uri = URI.join(base_url, 'ServiceProviderConfig')
54          json = http.get(uri)
55
56          self.service_provider_configuration = ServiceProviderConfiguration.parse(json, json)
57
58          load_items(base_url, 'Schemas', Schema, schemas)
59          load_items(base_url, 'ResourceTypes', ResourceType, resource_types)
60        end
61
62        private
63
64        attr_reader :http
65
66        def load_items(base_url, path, type, items)
67          hashes = http.get(URI.join(base_url, path))
68          hashes.each do |hash|
69            item = type.from(hash)
70            items[item.id] = item
71          end
72        end
73      end
74    end
75  end
76end