summaryrefslogtreecommitdiff
path: root/lib/scim/kit/v2/schema.rb
blob: 64576c44850195f174ee03ae9547abf9457631ef (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
# frozen_string_literal: true

module Scim
  module Kit
    module V2
      # Represents a SCIM Schema
      class Schema
        include Templatable

        attr_reader :id, :name, :attributes
        attr_accessor :meta, :description

        def initialize(id:, name:, location:)
          @id = id
          @name = name
          @description = name
          @meta = Meta.new('Schema', location)
          @meta.created = @meta.last_modified = @meta.version = nil
          @attributes = []
          yield self if block_given?
        end

        def add_attribute(name:, type: :string)
          attribute = AttributeType.new(name: name, type: type, schema: self)
          yield attribute if block_given?
          attributes << attribute
        end

        def core?
          id.include?(Schemas::CORE) || id.include?(Messages::CORE)
        end

        class << self
          def build(**args)
            item = new(**args)
            yield item
            item
          end

          def from(hash)
            Schema.new(
              id: hash[:id],
              name: hash[:name],
              location: hash[:location]
            ) do |x|
              x.meta = Meta.from(hash[:meta])
              hash[:attributes].each do |y|
                x.attributes << parse_attribute_type(y)
              end
            end
          end

          def parse(json)
            from(JSON.parse(json, symbolize_names: true))
          end

          private

          def parse_attribute_type(hash)
            attribute_type = AttributeType.from(hash)
            hash[:subAttributes]&.each do |sub_attr_hash|
              attribute_type.attributes << parse_attribute_type(sub_attr_hash)
            end
            attribute_type
          end
        end
      end
    end
  end
end