home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / xampp / xampp-perl-addon-1.4.9-installer.exe / ToObjects.pm < prev    next >
Encoding:
Text File  |  2001-07-17  |  15.7 KB  |  577 lines

  1. #
  2. # Copyright (C) 1999 Ken MacLeod
  3. # XML::PatAct::ToObjects is free software; you can redistribute it and/or
  4. # modify it under the same terms as Perl itself.
  5. #
  6. # $Id: ToObjects.pm,v 1.5 1999/12/22 21:15:00 kmacleod Exp $
  7. #
  8.  
  9. # The original XML::Grove::ToObjects actually generated and compiled a
  10. # sub for matching actions, possibly a performance improvement of three
  11. # or four times over all the comparisons made in start_element() and
  12. # end_element().
  13.  
  14. use strict;
  15.  
  16. use UNIVERSAL;
  17.  
  18. package XML::PatAct::ToObjects;
  19. use vars qw{ $VERSION $name_re };
  20.  
  21. # will be substituted by make-rel script
  22. $VERSION = "0.07";
  23.  
  24. # FIXME I doubt this is a correct Perl RE for productions [4] and
  25. # [5] in the XML 1.0 specification, especially considering Unicode chars
  26. $name_re = '[A-Za-z_:][A-Za-z0-9._:-]*';
  27.  
  28. sub new {
  29.     my $type = shift;
  30.     my $self = ($#_ == 0) ? { %{ (shift) } } : { @_ };
  31.  
  32.     bless $self, $type;
  33.  
  34.     my $usage = <<'EOF';
  35. usage: XML::PatAct::ToObjects->new( Matcher => $matcher,
  36.                     Patterns => $patterns );
  37. EOF
  38.  
  39.     die "No Matcher specified\n$usage\n"
  40.     if !defined $self->{Matcher};
  41.     die "No Patterns specified\n$usage\n"
  42.     if !defined $self->{Patterns};
  43.  
  44.     # Parse action items
  45.     $self->{Actions} = [ ];
  46.     my $patterns = $self->{Patterns};
  47.     my $ii = 1;
  48.     while ($ii <= $#$patterns) {
  49.         if (ref $patterns->[$ii]) {
  50.         push @{$self->{Actions}},
  51.           $self->_parse_action($patterns->[$ii]);
  52.     } else {
  53.         # is a code fragment
  54.     }
  55.     $ii += 2;
  56.     }
  57.  
  58.     if (defined $self->{GroveBuilder}) {
  59.     require XML::Grove::Builder;
  60.     import XML::Grove::Builder;
  61.     $self->{GroveBuilder} = XML::Grove::Builder->new();
  62.     }
  63.  
  64.     return $self;
  65. }
  66.  
  67. sub start_document {
  68.     my ($self, $document) = @_;
  69.  
  70.     $self->{Matcher}->initialize($self);
  71.     $self->{Parents} = [ { Contents => [  ] } ];
  72.     $self->{ActionStack} = [ ];
  73.     $self->{States} = [ 'normal' ];
  74.     $self->{Document} = $document;
  75.     $self->{Names} = [ ];
  76.     $self->{Nodes} = [ ];
  77.     $self->{Data} = undef;
  78.     $self->{SourceIsGrove} = UNIVERSAL::isa($document, 'Data::Grove');
  79.     if (!defined $self->{CharacterDataType}) {
  80.     require Data::Grove;
  81.     import Data::Grove;
  82.     $self->{CharacterDataType} = 'Data::Grove::Characters';
  83.     }
  84. }
  85.  
  86. sub end_document {
  87.     my ($self, $document) = @_;
  88.  
  89.     $self->{Matcher}->finalize();
  90.     # FIXME check to make sure no other fields were assigned to
  91.     my $value = $self->{Parents}[0]{Contents};
  92.  
  93.     # release all the info that is just used during event handling
  94.     $self->{Matcher} = $self->{Parents} = $self->{ActionStack} = undef;
  95.     $self->{States} = $self->{Document} = $self->{Names} = undef;
  96.     $self->{Nodes} = $self->{Data} = $self->{SourceIsGrove} = undef;
  97.  
  98.     return $value;
  99. }
  100.  
  101. sub start_element {
  102.     my ($self, $element) = @_;
  103.  
  104.     push @{$self->{Names}}, $element->{Name};
  105.     push @{$self->{Nodes}}, $element;
  106.  
  107.     my $index = $self->{Matcher}->match($element,
  108.                     $self->{Names},
  109.                     $self->{Nodes});
  110.  
  111.     my $action;
  112.     if (!defined $index) {
  113.     $action = undef;
  114.     } else {
  115.     $action = $self->{Actions}[$index];
  116.     }
  117.  
  118.     push @{$self->{ActionStack}}, $action;
  119.  
  120.     my $state = $self->{States}[-1];
  121.     push @{$self->{States}}, $state;
  122.  
  123.     if (($state eq 'as-grove') and !$self->{SourceIsGrove}) {
  124.     $self->{GroveBuilder}->start_element($element);
  125.     }
  126.  
  127.     return if (($state ne 'normal') && ($state ne 'pcdata'));
  128.  
  129.     if (defined($action) and defined($action->{PCData})) {
  130.     $self->{States}[-1] = 'pcdata';
  131.     }
  132.  
  133.     if (!defined($action) or $action->{Holder}) {
  134.     # ignore this element but continue processing below
  135.     return;
  136.     }
  137.  
  138.     if ($action->{Ignore} or $action->{FieldValue}) {
  139.     # ignore (discard) this element and it's children
  140.     $self->{States}[-1] = 'discarding';
  141.     return;
  142.     }
  143.  
  144.     if ($action->{AsString}) {
  145.     $self->{Data} = [ ];
  146.     $self->{States}[-1] = 'as-string';
  147.     return;
  148.     }
  149.  
  150.     if ($action->{AsGrove}) {
  151.     $self->{States}[-1] = 'as-grove';
  152.     if (!$self->{SourceIsGrove}) {
  153.         $self->{GroveBuilder}->start_document( { } );
  154.         $self->{GroveBuilder}->start_element($element);
  155.     }
  156.     return;
  157.     }
  158.  
  159.     if (defined $action->{Make}) {
  160.     my @args;
  161.     if (defined $element->{Attributes}) {
  162.         if (defined $self->{CopyAttributes}) {
  163.         push @args, %{$element->{Attributes}};
  164.         } elsif ($self->{CopyId} && defined($element->{Attributes}{ID})) {
  165.         # FIXME use code from XML::Grove::IDs
  166.         push (@args, ID => $element->{Attributes}{ID});
  167.         }
  168.     }
  169.  
  170.     if (defined $action->{Args}) {
  171.         eval 'push (@args, (' . $action->{Args} . '))';
  172.         if ($@) {
  173.         warn "$@\nwhile processing pattern/action #$index\n";
  174.         }
  175.     }
  176.  
  177.     if ($action->{Make} eq 'HASH') {
  178.         push @{$self->{Parents}}, { @args };
  179.     } else {
  180.         my $is_defined = 0;
  181.         #eval "\$is_defined = defined %{$action->{Make}" . "::}";
  182.         if ($is_defined) {
  183.         push @{$self->{Parents}}, $action->{Make}->new( @args );
  184.         } else {
  185.         push (@{$self->{Parents}},
  186.               bless ({ @args }, $action->{Make}));
  187.         }
  188.     }
  189.  
  190.     if ($action->{ContentsAsGrove}) {
  191.         $self->{States}[-1] = 'as-grove';
  192.         if (!$self->{SourceIsGrove}) {
  193.         $self->{GroveBuilder}->start_document( { } );
  194.         }
  195.     }
  196.  
  197.     return;
  198.     }
  199.  
  200.     # Place to store all the rest of gathered contents
  201.     push (@{$self->{Parents}}, { } );
  202. }
  203.  
  204. sub end_element {
  205.     my ($self, $end_element) = @_;
  206.  
  207.     my $name = pop @{$self->{Names}};
  208.     my $element = pop @{$self->{Nodes}};
  209.  
  210.     my $action = pop @{$self->{ActionStack}};
  211.     my $state = pop @{$self->{States}};
  212.  
  213.     if ($state eq 'as-grove' and !$self->{SourceIsGrove}) {
  214.     $self->{GroveBuilder}->end_element($end_element);
  215.     }
  216.  
  217.     if (!defined($action) or $action->{Holder}) {
  218.     return;
  219.     }
  220.  
  221.     if ($action->{Ignore}) {
  222.     return;
  223.     }
  224.  
  225.     my $value;
  226.  
  227.     if ($action->{AsString}) {
  228.     $value = join("", @{$self->{Data}});
  229.     } elsif ($action->{AsGrove}) {
  230.     if ($self->{SourceIsGrove}) {
  231.         $value = $element;
  232.     } else {
  233.         # get just the root element of the document fragment
  234.         $value = $self->{GroveBuilder}->end_document({ })->{Contents}[0];
  235.     }
  236.     } elsif (defined $action->{FieldValue}) {
  237.     $value = $action->{FieldValue};
  238.     $value =~ s/%\{($name_re)\}/$element->{Attributes}{$1}/ge;
  239.     } elsif (defined $action->{Make}) {
  240.     $value = pop @{$self->{Parents}};
  241.     if ($action->{ContentsAsGrove}) {
  242.         if ($self->{SourceIsGrove}) {
  243.         $value->{Contents} = $element->{Contents};
  244.         } else {
  245.         $value->{Contents} =
  246.             $self->{GroveBuilder}->end_document({ })->{Contents};
  247.         }
  248.     }
  249.     } else {
  250.     $value = pop(@{$self->{Parents}})->{Contents};
  251.     }
  252.  
  253.     if ($action->{FieldIsArray}) {
  254.     push @{$self->{Parents}[-1]{$action->{Field}}}, $value;
  255.     } elsif (defined $action->{Field}) {
  256.     $self->{Parents}[-1]{$action->{Field}} = $value;
  257.     } else {
  258.     push @{$self->{Parents}[-1]{Contents}}, $value;
  259.     }
  260. }
  261.  
  262. sub characters {
  263.     my ($self, $characters) = @_;
  264.  
  265.     my $state = $self->{States}[-1];
  266.     if ($state eq 'as-string') {
  267.     push @{$self->{Data}}, $characters->{Data};
  268.     } elsif ($state eq 'as-grove' and !$self->{SourceIsGrove}) {
  269.     $self->{GroveBuilder}->characters($characters);
  270.     } elsif ($state eq 'pcdata') {
  271.     push (@{$self->{Parents}[-1]{Contents}},
  272.           $self->{CharacterDataType}->new(%$characters));
  273.     }
  274. }
  275.  
  276. # we ignore processing instructions and ignorable whitespace by not
  277. # defining those functions
  278.  
  279. ###
  280. ### private functions
  281. ###
  282.  
  283. sub _parse_action {
  284.     my $self = shift; my $source = shift;
  285.  
  286.     my $action = {};
  287.  
  288.     while ($#$source > -1) {
  289.     my $option = shift @$source;
  290.     if ($option eq '-holder') {
  291.         $action->{Holder} = 1;
  292.     } elsif ($option eq '-make') {
  293.         $action->{Make} = shift @$source;
  294.     } elsif ($option eq '-args') {
  295.         my $args = shift @$source;
  296.         $args =~ s/%\{($name_re)\}/(\$element->{Attributes}{'$1'})/g;
  297.         $action->{Args} = $args;
  298.     } elsif ($option eq '-field') {
  299.         $action->{Field} = shift @$source;
  300.     } elsif ($option eq '-push-field') {
  301.         $action->{Field} = shift @$source;
  302.         $action->{FieldIsArray} = 1;
  303.     } elsif ($option eq '-as-string') {
  304.         $action->{AsString} = 1;
  305.     } elsif ($option eq '-value') {
  306.         $action->{FieldValue} = shift @$source;
  307.     } elsif ($option eq '-grove') {
  308.         $self->{GroveBuilder} = 1;
  309.         $action->{AsGrove} = 1;
  310.     } elsif ($option eq '-grove-contents') {
  311.         $self->{GroveBuilder} = 1;
  312.         $action->{ContentsAsGrove} = 1;
  313.     } elsif ($option eq '-ignore') {
  314.         $action->{Ignore} = 1;
  315.     } elsif ($option eq '-pcdata') {
  316.         $action->{PCData} = 1;
  317.     } else {
  318.         die "$option: undefined option\n";
  319.     }
  320.     }
  321.  
  322.     return $action;
  323. }
  324.  
  325. 1;
  326.  
  327. __END__
  328.  
  329. =head1 NAME
  330.  
  331. XML::PatAct::ToObjects - An action module for creating Perl objects
  332.  
  333. =head1 SYNOPSIS
  334.  
  335.  use XML::PatAct::ToObjects;
  336.  
  337.  my $patterns = [ PATTERN => [ OPTIONS ],
  338.           PATTERN => "PERL-CODE",
  339.           ... ];
  340.  
  341.  my $matcher = XML::PatAct::ToObjects->new( Patterns => $patterns,
  342.                         Matcher => $matcher,
  343.                         CopyId => 1,
  344.                         CopyAttributes => 1 );
  345.  
  346.  
  347. =head1 DESCRIPTION
  348.  
  349. XML::PatAct::ToObjects is a PerlSAX handler for applying
  350. pattern-action lists to XML parses or trees.  XML::PatAct::ToObjects
  351. creates Perl objects of the types and contents of the action items you
  352. define.
  353.  
  354. New XML::PatAct::ToObject instances are creating by calling `new()'.
  355. Parameters can be passed as a list of key, value pairs or a hash.
  356. `new()' requires the Patterns and Matcher parameters, the rest are
  357. optional:
  358.  
  359. =over 4
  360.  
  361. =item Patterns
  362.  
  363. The pattern-action list to apply.
  364.  
  365. =item Matcher
  366.  
  367. An instance of the pattern or query matching module.
  368.  
  369. =item CopyId
  370.  
  371. Causes the `ID' attribute, if any, in a source XML element to be
  372. copied to an `ID' attribute in newly created objects.  Note that IDs
  373. may be lost of no pattern matches that element or an object is not
  374. created (C<-make>) for that element.
  375.  
  376. =item CopyAttributes
  377.  
  378. Causes all attributes of the element to be copied to the newly created
  379. objects.
  380.  
  381. =back
  382.  
  383. Each action can either be a list of options defined below or a string
  384. containing a fragment of Perl code.  If the action is a string of Perl
  385. code then simple then some simple substitutions are made as described
  386. further below.
  387.  
  388. Options that can be used in an action item containing an option-list:
  389.  
  390. =over 4
  391.  
  392. =item B<-holder>
  393.  
  394. Ignore this element, but continue processing it's children (compare to
  395. B<-ignore>).  C<-pcdata> may be used with this option.
  396.  
  397. =item B<-ignore>
  398.  
  399. Ignore (discard) this element and it's children (compare to B<-holder>).
  400.  
  401. =item B<-pcdata>
  402.  
  403. Character data in this element should be copied to the C<Contents>
  404. field.
  405.  
  406. =item B<-make> I<PACKAGE>
  407.  
  408. Create an object blessed into I<PACKAGE>, and continue processing this
  409. element and it's children.  I<PACKAGE> may be the type `C<HASH>' to
  410. simply create an anonyous hash.
  411.  
  412. =item B<-args> I<ARGUMENTS>
  413.  
  414. Use I<ARGUMENTS> in creating the object specified by B<-make>.  This
  415. is commonly used to copy element attributes into fields in the newly
  416. created object.  For example:
  417.  
  418.   -make => 'HASH', -args => 'URL => %{href}'
  419.  
  420. would copy the `C<href>' attribute in an element to the `C<URL>' field
  421. of the newly created hash.
  422.  
  423. =item B<-field> I<FIELD>
  424.  
  425. Store this element, object, or children of this element in the parent
  426. object's field named by I<FIELD>.
  427.  
  428. =item B<-push-field> I<FIELD>
  429.  
  430. Similar to B<-field>, except that I<FIELD> is an array and the
  431. contents are pushed onto that array.
  432.  
  433. =item B<-value> I<VALUE>
  434.  
  435. Use I<VALUE> as a literal value to store in I<FIELD>, otherwise
  436. ignoring this element and it's children.  Only valid with B<-field> or
  437. B<-push-field>.  `C<%{I<ATTRIBUTE>}>' notation can be used to
  438. substitute the value of an attribute into the literal value.
  439.  
  440. =item B<-as-string>
  441.  
  442. Convert the contents of this element to a string (as in
  443. C<XML::Grove::AsString>) and store in I<FIELD>.  Only valid with
  444. B<-field> or B<-push-field>.
  445.  
  446. =item B<-grove>
  447.  
  448. Copy this element to I<FIELD> without further processing.  The element
  449. can then be processed later as the Perl objects are manipulated.  Only
  450. valid with B<-field> or B<-push-field>.  If ToObjects is used with
  451. PerlSAX, this will use XML::Grove::Builder to build the grove element.
  452.  
  453. =item B<-grove-contents>
  454.  
  455. Used with B<-make>, B<-grove-contents> creates an object but then
  456. takes all of the content of that element and stores it in Contents.
  457.  
  458. =back
  459.  
  460. If an action item is a string, that string is treated as a fragment of
  461. Perl code.  The following simple substitutions are performed on the
  462. fragment to provide easy access to the information being converted:
  463.  
  464. =over 4
  465.  
  466. =item B<@ELEM@>
  467.  
  468. The object that caused this action to be called.  If ToObjects is used
  469. with PerlSAX this will be a hash with the element name and attributes,
  470. with XML::Grove this will be the element object, with Data::Grove it
  471. will be the matching object, and with XML::DOM it will be an
  472. XML::DOM::Element.
  473.  
  474. =back
  475.  
  476. =head1 EXAMPLE
  477.  
  478. The example pattern-action list below will convert the following XML
  479. representing a Database schema:
  480.  
  481.     <schema>
  482.       <table>
  483.         <name>MyTable</name>
  484.         <summary>A short summary</summary>
  485.         <description>A long description that may
  486.           contain a subset of HTML</description>
  487.         <column>
  488.           <name>MyColumn1</name>
  489.           <summary>A short summary</summary>
  490.           <description>A long description</description>
  491.           <unique/>
  492.           <non-null/>
  493.           <default>42</default>
  494.         </column>
  495.       </table>
  496.     </schema>
  497.  
  498. into Perl objects looking like:
  499.  
  500.     [
  501.       { Name => "MyTable",
  502.         Summary => "A short summary",
  503.         Description => $grove_object,
  504.         Columns => [
  505.           { Name => "MyColumn1",
  506.             Summary => "A short summary",
  507.             Description => $grove_object,
  508.             Unique => 1,
  509.             NonNull => 1,
  510.             Default => 42
  511.           }
  512.         ]
  513.       }
  514.     ]
  515.  
  516. Here is a Perl script and pattern-action list that will perform the
  517. conversion using the simple name matching pattern module
  518. XML::PatAct::MatchName.  The script accepts a Schema XML file as an
  519. argument (C<$ARGV[0]>) to the script.  This script creates a grove as
  520. one of it's objects, so it requires the XML::Grove module.
  521.  
  522.     use XML::Parser::PerlSAX;
  523.     use XML::PatAct::MatchName;
  524.     use XML::PatAct::ToObjects;
  525.  
  526.     my $patterns = [
  527.       'schema'      => [ qw{ -holder                                  } ],
  528.       'table'       => [ qw{ -make Schema::Table                      } ],
  529.       'name'        => [ qw{ -field Name -as-string                   } ],
  530.       'summary'     => [ qw{ -field Summary -as-string                } ],
  531.       'description' => [ qw{ -field Description -grove                } ],
  532.       'column'      => [ qw{ -make Schema::Column -push-field Columns } ],
  533.       'unique'      => [ qw{ -field Unique -value 1                   } ],
  534.       'non-null'    => [ qw{ -field NonNull -value 1                  } ],
  535.       'default'     => [ qw{ -field Default -as-string                } ],
  536.     ];
  537.  
  538.     my $matcher = XML::PatAct::MatchName->new( Patterns => $patterns );
  539.     my $handler = XML::PatAct::ToObjects->new( Patterns => $patterns,
  540.                                                Matcher => $matcher);
  541.  
  542.     my $parser = XML::Parser::PerlSAX->new( Handler => $handler );
  543.     my $schema = $parser->parse(Source => { SystemId => $ARGV[0] } );
  544.  
  545. =head1 TODO
  546.  
  547. =over 4
  548.  
  549. =item *
  550.  
  551. It'd be nice if patterns could be applied even in B<-as-string> and
  552. B<-grove>.
  553.  
  554. =item *
  555.  
  556. Implement Perl code actions.
  557.  
  558. =item *
  559.  
  560. B<-as-xml> to write XML into the field.
  561.  
  562. =back
  563.  
  564.  
  565.  
  566. =head1 AUTHOR
  567.  
  568. Ken MacLeod, ken@bitsko.slc.ut.us
  569.  
  570. =head1 SEE ALSO
  571.  
  572. perl(1), Data::Grove(3)
  573.  
  574. ``Using PatAct Modules'' and ``Creating PatAct Modules'' in libxml-perl.
  575.  
  576. =cut
  577.