Class: BBortcodes::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/bbortcodes/parser.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(registry: nil, config: nil) ⇒ Parser

Returns a new instance of Parser.



9
10
11
12
13
# File 'lib/bbortcodes/parser.rb', line 9

def initialize(registry: nil, config: nil)
  @registry = registry || BBortcodes.registry
  @config = config || BBortcodes.config
  @transform = Transform.new
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



7
8
9
# File 'lib/bbortcodes/parser.rb', line 7

def config
  @config
end

#registryObject (readonly)

Returns the value of attribute registry.



7
8
9
# File 'lib/bbortcodes/parser.rb', line 7

def registry
  @registry
end

Instance Method Details

#parse(text, context: nil, only: nil) ⇒ Array<String, Array<Shortcode>>

Parse a string containing shortcodes

Parameters:

  • The text to parse

  • (defaults to: nil)

    The rendering context

  • (defaults to: nil)

    Only process these shortcode types

Returns:

  • The processed text and array of shortcode instances



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
# File 'lib/bbortcodes/parser.rb', line 20

def parse(text, context: nil, only: nil)
  # Validate input size
  max_length = config.max_input_length
  if text.bytesize > max_length
    raise ParseError, "Input too large: #{text.bytesize} bytes (max: #{max_length})"
  end

  context = prepare_context(context)

  # Parse the text into a tree structure with timeout protection
  # Create grammar with current registered tag names
  tag_names = @registry.tag_names
  grammar = Grammar.new(tag_names)

  begin
    parsed = Timeout.timeout(config.parse_timeout) do
      grammar.parse(text)
    end
  rescue Timeout::Error
    raise ParseError, "Parsing timeout exceeded (#{config.parse_timeout}s) - input may be too complex"
  rescue Parslet::ParseFailed => e
    handle_parse_error(e, text)
    return [text, []]
  end

  # Transform the parse tree
  tree = @transform.apply(parsed)

  # Convert to shortcode instances and render
  shortcodes = []
  output = process_tree(tree, context, only, shortcodes, parent_shortcode: nil, depth: 0)

  [output, shortcodes]
end