Module: StdUriTemplate

Defined in:
lib/stduritemplate.rb

Defined Under Namespace

Modules: Operator, SubstitutionType

Class Method Summary collapse

Class Method Details

.add_expanded_value(prefix, value, result, max_char, replace_reserved) ⇒ Object



225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# File 'lib/stduritemplate.rb', line 225

def self.add_expanded_value(prefix, value, result, max_char, replace_reserved)
  string_value = convert_native_types(value)
  max = (max_char != -1) ? [max_char, string_value.length].min : string_value.length
  reserved_buffer = nil

  if (max > 0 && !prefix.nil?)
    result << prefix
  end

  max.times do |i|
    character = string_value[i]

    if character == '%' && !replace_reserved
      reserved_buffer = ''
    end

    to_append = character
    if is_surrogate(character) || replace_reserved || is_ucschar(character) || is_iprivate(character)
      to_append = URI.encode_www_form_component(character)
    end

    if reserved_buffer
      reserved_buffer << to_append

      if reserved_buffer.length == 3
        is_encoded = false
        begin
          encoded = URI.decode_www_form_component(reserved_buffer)
          is_encoded = !(encoded == reserved_buffer)
        rescue StandardError
        end

        if is_encoded
          result << reserved_buffer
        else
          result << "%25"
          result << reserved_buffer[1..-1] unless replace_reserved
        end

        reserved_buffer = nil
      end
    else
      if character == ' '
        result << "%20"
      elsif character == '%'
        result << "%25"
      else
        result << to_append
      end
    end
  end

  if reserved_buffer
    result << "%25"
    result << reserved_buffer[1..-1]
  end
end

.add_list_value(operator, token, value, result, max_char, composite) ⇒ Object



401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
# File 'lib/stduritemplate.rb', line 401

def self.add_list_value(operator, token, value, result, max_char, composite)
  first = true
  value.each do |v|
    if first
      add_value(operator, token, v, result, max_char)
      first = false
    else
      if composite
        add_separator(operator, result)
        add_value(operator, token, v, result, max_char)
      else
        result << ','
        add_value_element(operator, token, v, result, max_char)
      end
    end
  end
  !first
end

.add_map_value(operator, token, value, result, max_char, composite) ⇒ Object

Raises:

  • (ArgumentError)


420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
# File 'lib/stduritemplate.rb', line 420

def self.add_map_value(operator, token, value, result, max_char, composite)
  first = true
  raise ArgumentError, 'Value trimming is not allowed on Maps' if max_char != -1

  value.each do |key, val|
    if composite
      add_separator(operator, result) unless first
      add_value_element(operator, token, key.to_s, result, max_char)
      result << '='
    else
      if first
        add_value(operator, token, key.to_s, result, max_char)
      else
        result << ','
        add_value_element(operator, token, key.to_s, result, max_char)
      end
      result << ','
    end
    add_value_element(operator, token, val, result, max_char)
    first = false
  end
  !first
end

.add_prefix(op, result) ⇒ Object



155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
# File 'lib/stduritemplate.rb', line 155

def self.add_prefix(op, result)
  case op
  when Operator::HASH
    result << '#'
  when Operator::DOT
    result << '.'
  when Operator::SLASH
    result << '/'
  when Operator::SEMICOLON
    result << ';'
  when Operator::QUESTION_MARK
    result << '?'
  when Operator::AMP
    result << '&'
  end
end

.add_separator(op, result) ⇒ Object



172
173
174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/stduritemplate.rb', line 172

def self.add_separator(op, result)
  case op
  when Operator::DOT
    result << '.'
  when Operator::SLASH
    result << '/'
  when Operator::SEMICOLON
    result << ';'
  when Operator::QUESTION_MARK, Operator::AMP
    result << '&'
  else
    result << ','
  end
end

.add_string_value(operator, token, value, result, max_char) ⇒ Object



397
398
399
# File 'lib/stduritemplate.rb', line 397

def self.add_string_value(operator, token, value, result, max_char)
  add_value(operator, token, value, result, max_char)
end

.add_value(op, token, value, result, max_char) ⇒ Object



187
188
189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/stduritemplate.rb', line 187

def self.add_value(op, token, value, result, max_char)
  case op
  when Operator::PLUS, Operator::HASH
    add_expanded_value(nil, value, result, max_char, false)
  when Operator::QUESTION_MARK, Operator::AMP
    result << token + '='
    add_expanded_value(nil, value, result, max_char, true)
  when Operator::SEMICOLON
    result << token
    add_expanded_value('=', value, result, max_char, true)
  when Operator::DOT, Operator::SLASH, Operator::NO_OP
    add_expanded_value(nil, value, result, max_char, true)
  end
end

.add_value_element(op, token, value, result, max_char) ⇒ Object



202
203
204
205
206
207
208
209
# File 'lib/stduritemplate.rb', line 202

def self.add_value_element(op, token, value, result, max_char)
  case op
  when Operator::PLUS, Operator::HASH
    add_expanded_value(nil, value, result, max_char, false)
  when Operator::QUESTION_MARK, Operator::AMP, Operator::SEMICOLON, Operator::DOT, Operator::SLASH, Operator::NO_OP
    add_expanded_value(nil, value, result, max_char, true)
  end
end

.check_varname(token, col) ⇒ Object



347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
# File 'lib/stduritemplate.rb', line 347

def self.check_varname(token, col)
  if token.start_with?('.') || token.end_with?('.')
    raise ArgumentError, "Variable name cannot start or end with a dot at col:#{col}"
  end

  if token.include?('..')
    raise ArgumentError, "Variable name cannot contain consecutive dots at col:#{col}"
  end

  i = 0
  while i < token.length
    if token[i] == '%'
      if i + 2 >= token.length || !hex_digit?(token[i + 1]) || !hex_digit?(token[i + 2])
        raise ArgumentError, "Invalid percent encoding in variable name at col:#{col}"
      end
      i += 3
    else
      i += 1
    end
  end
end

.convert_native_types(value) ⇒ Object



333
334
335
336
337
338
339
340
341
# File 'lib/stduritemplate.rb', line 333

def self.convert_native_types(value)
  if ([Integer, Float, String].any? { |type| value.is_a?(type) }) || ([true, false].include? value)
    value.to_s
  elsif ([DateTime].any? { |type| value.is_a?(type) })
    value.strftime("%Y-%m-%dT%H:%M:%SZ")
  else
    raise ArgumentError, "Illegal class passed as substitution, found #{value.class}"
  end
end

.empty?(subst_type, value) ⇒ Boolean

Returns:

  • (Boolean)


312
313
314
315
316
317
318
319
320
321
322
323
# File 'lib/stduritemplate.rb', line 312

def self.empty?(subst_type, value)
  case subst_type
  when SubstitutionType::STRING
    value.nil?
  when SubstitutionType::LIST
    value.respond_to?(:empty?) ? value.empty? : true
  when SubstitutionType::MAP
    value.respond_to?(:empty?) ? value.empty? : true
  else
    true
  end
end

.expand(template, substitutions) ⇒ Object



6
7
8
# File 'lib/stduritemplate.rb', line 6

def self.expand(template, substitutions)
  expand_impl(template, substitutions)
end

.expand_impl(str, substitutions) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/stduritemplate.rb', line 80

def self.expand_impl(str, substitutions)
  result = ''
  token = nil
  operator = nil
  composite = false
  max_char_buffer = nil
  first_token = true

  str.chars.each_with_index do |character, i|
    case character
    when '{'
      token = ''
      first_token = true
    when '}'
      if token
        if !max_char_buffer.nil? && max_char_buffer.empty?
          raise ArgumentError, "Empty prefix after colon at col:#{i}"
        end
        expanded = expand_token(operator, token, composite, get_max_char(max_char_buffer, i), first_token, substitutions, result, i)
        first_token = false if expanded && first_token
        token = nil
        operator = nil
        composite = false
        max_char_buffer = nil
      else
        raise ArgumentError, "Failed to expand token, invalid at col:#{i}"
      end
    when ','
      if token
        if !max_char_buffer.nil? && max_char_buffer.empty?
          raise ArgumentError, "Empty prefix after colon at col:#{i}"
        end
        expanded = expand_token(operator, token, composite, get_max_char(max_char_buffer, i), first_token, substitutions, result, i)
        first_token = false if expanded && first_token
        token = ''
        composite = false
        max_char_buffer = nil
      end
    else
      if token
        if operator.nil?
          operator = get_operator(character, token, i)
        elsif max_char_buffer
          if character >= '0' && character <= '9'
            max_char_buffer << character
          else
            raise ArgumentError, "Illegal character identified in the token at col:#{i}"
          end
        else
          if character == ':'
            max_char_buffer = ''
          elsif character == '*'
            composite = true
          else
            validate_literal(character, i)
            token << character
          end
        end
      else
        if character.ord > 0x7F
          character.encode('UTF-8').bytes.each { |b| result << sprintf("%%%02X", b) }
        else
          result << character
        end
      end
    end
  end

  if token.nil?
    result
  else
    raise ArgumentError, 'Unterminated token'
  end
end

.expand_token(operator, token, composite, max_char, first_token, substitutions, result, col) ⇒ Object

Raises:

  • (ArgumentError)


369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
# File 'lib/stduritemplate.rb', line 369

def self.expand_token(operator, token, composite, max_char, first_token, substitutions, result, col)
  raise ArgumentError, "Found an empty token at col:#{col}" if token.empty?
  check_varname(token, col)

  value = substitutions[token]
  subst_type = get_substitution_type(value, col)
  if (subst_type == SubstitutionType::EMPTY || empty?(subst_type, value))
    return false
  end

  if first_token
    add_prefix(operator, result)
  else
    add_separator(operator, result)
  end

  case subst_type
  when SubstitutionType::STRING
    add_string_value(operator, token, value, result, max_char)
  when SubstitutionType::LIST
    add_list_value(operator, token, value, result, max_char, composite)
  when SubstitutionType::MAP
    add_map_value(operator, token, value, result, max_char, composite)
  end

  true
end

.get_max_char(buffer, col) ⇒ Object



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
# File 'lib/stduritemplate.rb', line 31

def self.get_max_char(buffer, col)
  return -1 if buffer.nil?

  value = buffer.to_s

  if value.empty?
    -1
  else
    begin
      parsed = Integer(value)
    rescue ArgumentError
      raise ArgumentError, "Cannot parse max chars at col:#{col}"
    end

    if value.start_with?('0')
      raise ArgumentError, "Leading zeros are not allowed in max chars at col:#{col}"
    end

    if parsed < 1 || parsed > 9999
      raise ArgumentError, "Max chars must be between 1 and 9999 at col:#{col}"
    end

    parsed
  end
end

.get_operator(c, token, col) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/stduritemplate.rb', line 57

def self.get_operator(c, token, col)
  case c
  when '+'
    Operator::PLUS
  when '#'
    Operator::HASH
  when '.'
    Operator::DOT
  when '/'
    Operator::SLASH
  when ';'
    Operator::SEMICOLON
  when '?'
    Operator::QUESTION_MARK
  when '&'
    Operator::AMP
  else
    validate_literal(c, col)
    token << c
    Operator::NO_OP
  end
end

.get_substitution_type(value, col) ⇒ Object



298
299
300
301
302
303
304
305
306
307
308
309
310
# File 'lib/stduritemplate.rb', line 298

def self.get_substitution_type(value, col)
  if value.nil?
    SubstitutionType::EMPTY
  elsif is_native_type(value)
    SubstitutionType::STRING
  elsif map?(value)
    SubstitutionType::MAP
  elsif list?(value)
    SubstitutionType::LIST
  else
    raise ArgumentError, "Illegal class passed as substitution, found #{value.class} at col:#{col}"
  end
end

.hex_digit?(c) ⇒ Boolean

Returns:

  • (Boolean)


343
344
345
# File 'lib/stduritemplate.rb', line 343

def self.hex_digit?(c)
  (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')
end

.is_iprivate(cp) ⇒ Object



215
216
217
# File 'lib/stduritemplate.rb', line 215

def self.is_iprivate(cp)
  (0xE000..0xF8FF).include?(cp.ord)
end

.is_native_type(value) ⇒ Object



325
326
327
328
329
330
331
# File 'lib/stduritemplate.rb', line 325

def self.is_native_type(value)
  if (([Integer, Float, String].any? { |type| value.is_a?(type) }) || ([true, false].include? value))
    true
  else
    false
  end
end

.is_surrogate(cp) ⇒ Object



211
212
213
# File 'lib/stduritemplate.rb', line 211

def self.is_surrogate(cp)
  cp.bytes.length > 1
end

.is_ucschar(cp) ⇒ Object



219
220
221
222
223
# File 'lib/stduritemplate.rb', line 219

def self.is_ucschar(cp)
  (0xA0..0xD7FF).include?(cp.ord) ||
    (0xF900..0xFDCF).include?(cp.ord) ||
    (0xFDF0..0xFFEF).include?(cp.ord)
end

.list?(value) ⇒ Boolean

Returns:

  • (Boolean)


283
284
285
# File 'lib/stduritemplate.rb', line 283

def self.list?(value)
  value.kind_of?(Array) || value.kind_of?(Enumerable)
end

.map?(value) ⇒ Boolean

Returns:

  • (Boolean)


287
288
289
# File 'lib/stduritemplate.rb', line 287

def self.map?(value)
  value.kind_of?(Hash)
end

.validate_literal(c, col) ⇒ Object



24
25
26
27
28
29
# File 'lib/stduritemplate.rb', line 24

def self.validate_literal(c, col)
  case c
  when '+', '#', '/', ';', '?', '&', ' ', '!', '=', '$', '|', '*', ':', '~', '-'
    raise ArgumentError, "Illegal character identified in the token at col:#{col}"
  end
end