AxKit2

 view release on metacpan or  search on metacpan

lib/AxKit2/XSP/SimpleTaglib.pm  view on Meta::CPAN

    # 2b. {ns}:name       => ns specified, prefix ''        <= actual result
    # 2b. {ns}:name       => ns specified, prefix undefined <= desired result
    $prefix = undef if $ns and not $prefix;

    # 3b. {}prefix:name   => ns '',        prefix specified <= actual result
    # 3b. {}prefix:name   => ns undefined, prefix specified <= desired result
    $ns = undef if not $ns and $prefix;

    # 4a. {}name,         => ns is '',     prefix undefined <= actual result
    # 4a. {}name,         => ns is '',     prefix is ''     <= desired result
    $prefix = '' if not $prefix and defined $ns and $ns eq '';

    # 4c. :name           => ns undefined, prefix is ''     <= actual result
    # 4c. :name           => ns is '',     prefix is ''     <= desired result
    $ns = '' if not $ns and defined $prefix and $prefix eq '';

    ($ns, $prefix, $name);
}

sub _lookup_prefix {
    my ($ns, $namespaces) = @_;
    my $i = 0;
    foreach my $namespace (@$namespaces) {
        my ($nsprefix, $nsuri) = @$namespace;
        ++$i;
        next unless $nsuri eq $ns;
        #$nsprefix = "stlns$i" if $nsprefix eq '' and $nsuri ne '';
        return $nsprefix;
    }
    #return "stlns$i";
    return "";
}

sub _lookup_ns {
    my ($prefix, $namespaces) = @_;
    $prefix ||= '';
    my $i = 0;
    foreach my $namespace (@$namespaces) {
        my ($nsprefix, $nsuri) = @$namespace;
        #++$i;
        next unless $nsprefix eq $prefix;
        #$nsprefix = "stlns$i" if $nsprefix eq '' and $nsuri ne '';
        return wantarray ? ($nsuri, $nsprefix) : $nsuri;
    }
    my ($nsprefix, $nsuri) = @{$namespaces->[-1]}; # default namespace
    return wantarray ? ($nsuri, $nsprefix) : $nsuri;
}


sub xmlize {
    my ($document, $parent, $namespaces, @data) = @_;
    foreach my $data (@data) {
        if (UNIVERSAL::isa($data,'XML::LibXML::Document')) {
            $data = $data->getDocumentElement();
        }
        if (UNIVERSAL::isa($data,'XML::LibXML::Node')) {
            $document->importNode($data);
            $parent->appendChild($data);
            next;
        }
        die 'data is not a hash ref or DOM fragment!' unless ref($data) eq 'HASH';
        while (my ($key, $val) = each %$data) {
            my $outer_namespaces_added = 0;
            if (substr($key,0,1) eq '@') {
                $key = substr($key,1);
                die 'attribute value is not a simple scalar!' if ref($val);
                next if $key =~ m/^xmlns(?::|$)/; # already processed these
                my ($ns, $prefix, $name) = parse_namespace($key);
                #$prefix = _lookup_prefix($ns, $namespaces) if $ns and not $prefix;
                $ns = _lookup_ns($prefix, $namespaces) if not $ns and $prefix;
                $name = $prefix.':'.$name if $prefix;
                if ($ns and $prefix) {
                    $parent->setAttributeNS($ns,$name,$val);
                } else {
                    $parent->setAttribute($name,$val);
                }
                next;
            }

            my ($ns, $prefix, $name) = parse_namespace($key);
            $prefix = _lookup_prefix($ns, $namespaces) if $ns and not $prefix;
            if (defined $ns) {
                unshift @$namespaces, [ $prefix => $ns ];
                $outer_namespaces_added++;
            }
            my @data = ref($val) eq 'ARRAY'? @$val:$val;
            foreach my $data (@data) {
                my $namespaces_added = 0;
                if (ref($data) and ref($data) eq 'HASH') {
                    # search for namespace declarations in attributes
                    while (my ($key, $val) = each %$data) {
                        if ($key =~ m/^\@xmlns(?::|$)(.*)/) {
                            unshift @$namespaces, [ $1 => $val ];
                            $namespaces_added++;
                        }
                    }
                }

                my $elem;
                if (length($key)) {
                    my($nsuri, $nsprefix, $local) = ($ns, $prefix, $name);
                    ($nsuri, $nsprefix) = _lookup_ns($nsprefix, $namespaces) if not defined $nsuri;
                    $local = $nsprefix.':'.$local if $nsprefix;
                    if ($nsuri) {
                        $elem = $document->createElementNS($nsuri,$local);
                    } else {
                        $elem = $document->createElement($local);
                    }
                    $parent->appendChild($elem);
                } else {
                    $elem = $parent;
                }

                if (ref($data)) {
                    xmlize($document, $elem, $namespaces, $data);
                } else {
                    my $tn = $document->createTextNode($data);
                    $elem->appendChild($tn);
                }
                splice(@$namespaces, 0, $namespaces_added) if $namespaces_added; # remove added namespaces
            }

lib/AxKit2/XSP/SimpleTaglib.pm  view on Meta::CPAN

        }
    }
    if ($$handlerAttributes{'stack'}) {
        shift @{$stacklevel{$rtpkg}};
        shift @{$stackcur{$rtpkg}};
        $e->append_to_script('shift @'.makeVariableName($rtpkg)."_stack;\n");
        $e->append_to_script('$'.makeVariableName($rtpkg).'_stack = $'.makeVariableName($rtpkg)."_stack[".$stackcur{$rtpkg}[0]."];\n");
    } elsif ($$attribs{$stacklevel{$rtpkg}[0]}) {
        shift @{$stackcur{$rtpkg}};
        $e->append_to_script('$'.makeVariableName($rtpkg).'_stack = $'.makeVariableName($rtpkg).'_stack['.$stackcur{$rtpkg}[0]."];\n");
    }
    #warn('script len: '.length($e->{XSP_Script}).', end tag: '.$tag);
    return '';
}

1;

__END__

=pod

=head1 NAME

AxKit2::XSP::SimpleTaglib - alternate XSP taglib helper

=head1 SYNOPSIS

    package Your::XSP::Package;
    use AxKit2::XSP::SimpleTaglib;

    ... more initialization stuff, start_document handler, utility functions, whatever
	you like, but no parse_start/end handler needed - if in doubt, just leave empty ...

    sub some_tag : XSP_attrib(id) XSP_attribOrChild(some-param) XSP_node(result) XSP_keepWhitespace {
        my ($tag, $attr, $stack, $struct) = @_;
        return do_something($$attr{'some-param'},$$attr{'id'});
    }
    
    # old style usage no longer documented, but still supported


=head1 DESCRIPTION

This taglib helper allows you to easily write tag handlers with most of the common
behaviours needed. It manages all 'Design Patterns' from the XSP man page plus
several other useful tag styles, including object-like access as in ESQL.

=head2 Simple handler subs

A tag "<yourNS:foo>" will trigger a call to sub "foo" during the closing tag event.
What happens in between can be configured in many ways
using Perl function attributes. In the rare cases where some action has to happen during
the opening tag event, you may provide a sub "foo__open" (double underscore)
which will be called at the appropriate time. Usually you would only do that for 'if'-
style tags which enclose some block of code. 'if'-style tags usually also need the C<XSP_compile>
flag.

Contrary to the former behaviour, your tag handler is called during the XSP execution stage,
so you should directly return the result value. The C<XSP_compile> flag is available to
have your handler called in the parse stage, when the XSP script is being constructed. Then,
it is the responsibility of the handler to return a I<Perl code fragment> to be appended to
the XSP script.

As a comparison, TaglibHelper subs are strictly run-time called, while plain taglibs without
any helper are strictly compile-time called.

B<Warning:> The old usage is still fully supported, but you should not use it anymore. It may
become deprecated in a future release and will be removed entirely afterwards. Porting it
to the new style usage is quite easy: remove the line reading "package I<your-taglib>::Handler;",
then prefix "XSP_" to all Perl attributes (e.g., "childStruct" becomes "XSP_childStruct"), and add
"XSP_compile" to every handler sub. If after your refactoring some handler sub doesn't carry any
Perl attribute anymore, add a plain "XSP" Perl attribute.

Perl attributes without the 'XSP_' prefix cause a warning (actually, sometimes even two, one from Perl
and one from SimpleTaglib), as lower-case Perl attributes are reserved for Perl itself.

=head2 Context sensitive handler subs

A sub named "foo___bar" (triple underscore) gets called on the following XML input:
"<yourNS:foo><yourNS:bar/></yourNS:foo>". Handler subs may have any nesting depth.
The rule for opening tag handlers applies here as well. The sub name must represent the
exact tag hierarchy (within your namespace).

=head2 Names, parameters, return values

Names for subs and variables get created by replacing any non-alphanumeric characters in the
original tag or attribute to underscores. For example, 'get-id' becomes 'get_id'.

In the default (run-time called) mode, subs get 4 parameters: the tag name, a hashref
containing attributes and child tags specified through C<XSP_child>/C<XSP_attribOrChild>, a
hashref for taglib private data (the current C<XSP_stack> hashref, if C<XSP_stack> is used),
and the C<XSP_smart> object, if applicable.

In C<XSP_compile> mode, the called subs get passed 3 parameters: The parser object, the tag name,
and an attribute hash (no ref!). This hash only contains XML attributes declared using the
'attrib()' Perl function attribute. (Try not to confuse these two meanings of 'attribute' -
unfortunately XML and Perl both call them that way.) The other declared parameters get converted
into local variables with prefix 'attr_', or, in the case of 'XSP_smart', converted into the
'$xml_subtree' object. These local variables are only available inside your code fragment which
becomes part of the XSP script, unlike the attribute hash which is passed directly to
your handler as the third parameter.

If a sub has an output attribute ('node', 'expr', etc.), the sub (or code fragment) will be run
in list context. If necessary, returned lists get converted to scalars by joining them
without separation. Code fragments from plain subs (without an output attribute) inherit
their context and have their return value left unmodified.

=head2 Precedence

If more than one handler matches a tag, the following rules determine which one is chosen.
Remember, though, that only tags in your namespace are considered.

=over 4

=item 1.

If any surrounding tag has a matching 'child' or 'attribOrChild'
attribute, the internal handler for the innermost matching tag gets chosen.

=item 2.

If any, the handler sub with the deepest tag hierarchy gets called.

=item 3.

If any parent tag carries the C<XSP_smart> attribute, the tag is collected in the
XML::Smart object tree.

=item 4.

If no handler sub matches, sub "_default" is tried.

=back

=head2 Utility functions

AxKit2::Transformer::XSP contains a few handy utility subs to help build your code fragment:

=over 4

=item start_elem, end_elem, start_attr, end_attr

these create elements and attributes
in the output document. Call them just like you call start_expr and end_expr.

=item makeSingleQuoted

given a scalar as input, it returns a scalar which yields
the exact input value when evaluated; handy when using unknown text as-is in code fragments.

=item makeVariableName

creates a valid, readable perl identifier from arbitrary input text.
The return values might overlap.

=back

=head1 PERL ATTRIBUTES

Perl function attributes are used to define how XML output should be generated from your
code fragment and how XML input should be presented to your handler.  Note that
parameters to attributes get handled as if 'q()' enclosed them (explicit quote marks are
not needed). Furthermore, commas separate parameters (except for childStruct), so a
parameter cannot contain a comma.

=head2 Output attributes

Choose exactly one of these to select output behaviour.

=head3 C<XSP>

Makes this tag behave not special at all. If merely flags this sub as being a valig tag handler.
For security and stability reasons, only subs carrying any XSP attribute are available as tags.

=head3 C<XSP_expr>

Makes this tag behave like an '<xsp:expr>' tag, creating text nodes or inline text as appropriate.
Choose this if you create plain text which may be used everywhere, including inside code. This
attribute has no parameters.

=head3 C<XSP_node(name)>

Makes this tag create an XML node named C<name>. The tag encloses all content as well as the
results of the handler sub.
Choose this if you want to create one XML node with all your output.

=head3 C<XSP_nodelist(name)>

Makes this tag create a list of XML nodes named C<name>. The tag(s) do not enclose content nodes,
which become preceding siblings of the generated nodes. The return value gets converted to a
node list by enclosing each element with an XML node named C<name>.
Choose this if you want to create a list of uniform XML nodes with all your output.

=head3 C<XSP_exprOrNode(name,attrname,attrvalue)>

Makes this tag behave described under either 'node()' or 'expr', depending on the value of
XML attribute C<attrname>. If that value matches C<attrvalue>, it will work like 'node()',
otherwise it will work like 'expr'. C<attrname> defaults to 'as', C<attrvalue> defaults to
'node', thus leaving out both parameters means that 'as="node"' will select 'node()' behaviour.
Choose this if you want to let the XSP author decide what to generate.

=head3 C<XSP_exprOrNodelist(name,attrname,attrvalue)>

Like exprOrNode, selecting between 'expr' and 'nodelist()' behaviour.

=head3 C<XSP_struct>

Makes this tag create a more complex XML fragment. You may return a single hashref or an array
of hashrefs, which get converted into an XML structure. Each hash element may contain a scalar,
which gets converted into an XML tag with the key as name and the value as content. Alternatively,
an element may contain an arrayref, which means that an XML tag encloses each single array element.
Finally, you may use hashrefs in place of scalars to create substructures. To create attributes on
tags, use a hashref that contain the attribute names prefixed by '@'. A '' (empty
string) as key denotes the text contents of that node.

You can also use a XML::LibXML::Document or XML::LibXML::Node object in place of a hashref. You
can, for example, simply return an XML::LibXML::Document object and it gets inserted at the current
location. You may also return an array of documents/nodes, and you may even mix plain hashrefs
with DOM objects as you desire.

Finally, you may also return an XML::Simple object.

In an expression context, passes on the unmodified return value.

=head2 Other output attributes

These may appear more than once and modify output behaviour.

=head3 C<XSP_compile>

Makes this tag called at XSP compile time, not run time. It must return a Perl code fragment.
For more details, see the sections above.

=head3 C<XSP_nodeAttr(name,expr,...)>

Adds an XML attribute named C<name> to all generated nodes. C<expr> gets evaluated at run time.
Evaluation happens once for each generated node. Of course, this tag only makes sense with
'node()' type handlers.

=head2 Input attributes

These tags specify how input gets handled. Most may appear more than once, if that makes sense.

=head3 C<XSP_attrib(name,...)>

Declares C<name> as a (non-mandatory) XML attribute. All attributes declared this way get
passed to your handler sub in the attribute hash (the third argument to your handler).

=head3 C<XSP_child(name,...)>

Declares a child tag C<name>. It always lies within the same namespace as the taglib itself. The
contents of the tag, if any, get saved in a local variable named $attr_C<name> and made
available to your code fragment. If the child tag appears more than once, the last value
overrides any previous value.

=head3 C<XSP_attribOrChild(name,...)>

Declares an attribute or child tag named C<name>. A variable is created just like for 'child()',
containing the attribute or child tag contents. If both appear, the contents of the child tag take
precedence.

=head3 C<XSP_keepWhitespace>

Makes this tag preserve contained whitespace.

=head3 C<XSP_captureContent>

Makes this tag store the enclosed content in '$_' for later retrieval in your code fragment instead
of adding it to the enclosing element. Non-text nodes will not work as expected.

=head3 C<XSP_stack(attrname)>

This will create a stack of objects for your taglib. Each taglib has exactly one stack, however.

Stacks work like this:

Whenever a tag is encountered that is flagged with C<XSP_stack>, a new empty stack frame (hashref) is created.
ALL handler subs get this hashref as their third argument where they may store/retrieve any data.

If the user wants to access a outer stack frame (object), she may add the I<attrname> attribute to ANY of your
tags. The value of that attribute specifies how much to go back: 0 is the innermost stack frame, 1 is
the surrounding one, and so on. The tag with I<attrname> and ALL tags below then get the selected stack frame
instead of the innermost one until another I<attrname> selects a new frame, or another C<XSP_stack> opens a
new one.

Most prominent example of this mode of operation is ESQL, which uses this technique to nest SQL queries.

=head3 C<XSP_smart>

Collects all unknown tags (that are in your taglib's name space) in an XML::Smart object and
passes it as the fourth element to your handler sub.

You must have XML::Smart installed to use this feature.

B<Note:> This attribute replaces the former childStruct attribute, which was way too complex.
The code is not yet removed, however, so legacy taglibs will still work. Backwards compatibility
will be removed in a future release.

=head1 XML NAMESPACES

By default, all output element nodes are placed in the same namespace
as the tag library.  To specify a different namespace or no namespace,
the desired namespace can be placed within curly braces before the
node name in an output attribute:

  {namespaceURI}name

To specify a prefix, place it after the namespace:

  {namespaceURI}prefix:name

For example, to create an XML node named C<otherNS:name> and associate
the prefix 'otherNS' with the namespace 'http://mydomain/NS/other/v1':

  node({http://mydomain/NS/other/v1}otherNS:name)

To create an XML node with no namespace, use an empty namespace:

  node({}name)

This notation for specifying namespaces can also be used in the
C<struct> output attribute.  Alternatively, the standard "xmlns" XML
attribute may be used to specify namespaces.  For example, the
following are equivalent:

  sub sample_struct : XSP_struct {
    return { '{http://mydomain/NS/other/v1}otherNS:name' => 'value' };
  }

lib/AxKit2/XSP/SimpleTaglib.pm  view on Meta::CPAN

    };
  }

Namespace scoping in the hashref is patterned after XML documents.
You may refer to previously declared namespaces by using the same
prefix, and you may override previously declared namespaces with new
declarations (either with the curly-braced notation or by using
"xmlns" XML attributes).

To specify a default namespace for all unqualified node names in the
hashref, state it as a parameter to the C<struct> output attribute:

  XSP_struct(namespaceURI)

You may also specify a prefix:

  XSP_struct({namespaceURI}prefix)

For example, the following is equivalent to the previous example:

  sub sample_struct : XSP_struct({http://mydomain/NS/other/v1}otherNS) {
    return { 'name' => 'value' };
  }

To turn off the default namespace for all node names, use an empty
namespace:

  sub sample_struct : XSP_struct({}) {
    return { 'name' => 'value' };
  }

By default, XML attributes created with the C<nodeAttr> output
attribute are not in a namespace.  The curly-braced notation can be
used to specify a namespace.  For example:

  XSP_nodeAttr({http://www.w3.org/TR/REC-html40}html:href,'http://www.axkit.org/')

If you are specifying more than one attribute in the same namespace,
you can refer to previously declared namespaces by using the same
prefix:

  XSP_nodeAttr({http://www.w3.org/TR/REC-html40}html:href,'http://www.axkit.org/',html:class,'link')

A prefix is required to associate a namespace with an attribute. Default namespaces
(those without a prefix) do not apply to attributes and are ignored.


=head1 EXAMPLES

Refer to the Demo tag libraries included in the AxKit distribution and look at the source
code of AxKit::XSP::Sessions and AxKit::XSP::Auth for full-featured examples. Beware, though,
they probably still use the old syntax.

=head1 BUGS AND HINTS

=head2 Miscellaneous

Because of the use of perl attributes, SimpleTaglib will only work with Perl 5.6.0 or later.
This software is already tested quite well and works for a number of simple and complex
taglibs. Still, you may have to experiment with the attribute declarations, as the differences
can be quite subtle but decide between 'it works' and 'it doesn't'. XSP can be quite fragile if
you start using heavy trickery.

If some tags don't work as expected, try surrounding the offending tag with
<xsp:content>, this is a common gotcha (but correct and intended). If you find you need
<xsp:expr> around a tag, please contact the author, that is probably a bug.

=head1 AUTHOR

Jörg Walter <jwalt@cpan.org>

=head1 COPYRIGHT

Copyright 2001-2003 Jörg Walter <jwalt@cpan.org>
All rights reserved. This program is free software; you can redistribute it and/or
modify it under the same terms as AxKit itself.

=head1 SEE ALSO

AxKit, AxKit2::Transformer::XSP, AxKit2::XSP::TaglibHelper, XML::Smart

=cut



( run in 0.966 second using v1.01-cache-2.11-cpan-364913b4093 )