Class: Datadog::AppSec::Utils::HTTP::MediaType

Inherits:
Object
  • Object
show all
Defined in:
lib/datadog/appsec/utils/http/media_type.rb

Overview

Constant Summary collapse

WILDCARD =
'*'
TOKEN_RE =
/[-#$%&'*+.^_`|~A-Za-z0-9]+/.freeze
PARAMETER_RE =
%r{
  (?:
    (?<parameter_name>#{TOKEN_RE})
    =
    (?:
      (?<parameter_value>#{TOKEN_RE})
      |
      "(?<parameter_value>[^"]+)"
    )
  )
}ix.freeze
MEDIA_TYPE_RE =
%r{
  \A
  (?<type>#{TOKEN_RE})/(?<subtype>#{TOKEN_RE})
  (?<parameters>
    (?:
      \s*;\s*
      #{PARAMETER_RE}
    )*
  )
  \Z
}ix.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(type:, subtype:, parameters: {}) ⇒ MediaType

Returns a new instance of MediaType.



79
80
81
82
83
# File 'lib/datadog/appsec/utils/http/media_type.rb', line 79

def initialize(type:, subtype:, parameters: {})
  @type = type
  @subtype = subtype
  @parameters = parameters
end

Instance Attribute Details

#parametersObject (readonly)

Returns the value of attribute parameters.



44
45
46
# File 'lib/datadog/appsec/utils/http/media_type.rb', line 44

def parameters
  @parameters
end

#subtypeObject (readonly)

Returns the value of attribute subtype.



44
45
46
# File 'lib/datadog/appsec/utils/http/media_type.rb', line 44

def subtype
  @subtype
end

#typeObject (readonly)

Returns the value of attribute type.



44
45
46
# File 'lib/datadog/appsec/utils/http/media_type.rb', line 44

def type
  @type
end

Class Method Details

.parse(media) ⇒ Object



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
# File 'lib/datadog/appsec/utils/http/media_type.rb', line 46

def self.parse(media)
  match = MEDIA_TYPE_RE.match(media)
  return if match.nil?

  type = match['type'] || WILDCARD
  type.downcase!

  subtype = match['subtype'] || WILDCARD
  subtype.downcase!

  parameters = {}
  params = match['parameters']

  unless params.nil? || params.empty?
    params.scan(PARAMETER_RE) do |name, unquoted_value, quoted_value|
      # NOTE: Order of unquoted_value and quoted_value does not matter,
      #       as they are mutually exclusive by the regex.
      # @type var value: ::String?
      value = unquoted_value || quoted_value
      next if name.nil? || value.nil?

      # See https://github.com/soutaro/steep/issues/2051
      name.downcase! # steep:ignore NoMethod
      value.downcase!

      # See https://github.com/soutaro/steep/issues/2051
      parameters[name] = value # steep:ignore ArgumentTypeMismatch
    end
  end

  new(type: type, subtype: subtype, parameters: parameters)
end

Instance Method Details

#to_sObject



85
86
87
88
89
# File 'lib/datadog/appsec/utils/http/media_type.rb', line 85

def to_s
  return "#{@type}/#{@subtype}" if @parameters.empty?

  "#{@type}/#{@subtype};#{@parameters.map { |k, v| "#{k}=#{v}" }.join(";")}"
end