summaryrefslogtreecommitdiff
path: root/lib/querypath/Extension/QPXSL.php
blob: 4adb317ddd0a26acd7f7845d842405452c63613b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
/** @file
 * Provide QueryPath with XSLT support using the PHP libxslt module.
 *
 * This is called 'QPXSL' instead of 'QPXSLT' in accordance with the name
 * of the PHP extension that provides libxslt support.
 *
 * You must have PHP XSL support for this to function.
 *
 * @author M Butcher <matt@aleph-null.tv>
 * @license http://opensource.org/licenses/lgpl-2.1.php LGPL or MIT-like license.
 * @see QueryPathExtension
 * @see QueryPathExtensionRegistry::extend()
 * @see QPXSL
 * @see QPXML
 */
 
/**
 * Provide tools for running XSL Transformation (XSLT) on a document.
 *
 * This extension provides the {@link QPXSL::xslt()} function, which transforms
 * a source XML document into another XML document according to the rules in
 * an XSLT document.
 *
 * This QueryPath extension can be used as follows:
 * <code>
 * <?php
 * require 'QueryPath/QueryPath.php';
 * require 'QueryPath/Extension/QPXSL.php';
 *
 * qp('src.xml')->xslt('stylesheet.xml')->writeXML();
 * ?>
 *
 * This will transform src.xml according to the XSLT rules in 
 * stylesheet.xml. The results are returned as a QueryPath object, which 
 * is written to XML using {@link QueryPath::writeXML()}.
 * </code>
 *
 * @ingroup querypath_extensions
 */
class QPXSL implements QueryPathExtension {
  
  protected $src = NULL;
  
  public function __construct(QueryPath $qp) {
    $this->src = $qp;
  }
  
  /**
   * Given an XSLT stylesheet, run a transformation.
   *
   * This will attempt to read the provided stylesheet and then
   * execute it on the current source document.
   *
   * @param mixed $style
   *  This takes a QueryPath object or <em>any</em> of the types that the 
   *  {@link qp()} function can take.
   * @return QueryPath
   *  A QueryPath object wrapping the transformed document. Note that this is a 
   *  <i>different</em> document than the original. As such, it has no history.
   *  You cannot call {@link QueryPath::end()} to undo a transformation. (However,
   *  the original source document will remain unchanged.)
   */
  public function xslt($style) {
    if (!($style instanceof QueryPath)) {
      $style = qp($style);
    }
    $sourceDoc = $this->src->top()->get(0)->ownerDocument;
    $styleDoc = $style->get(0)->ownerDocument;
    $processor = new XSLTProcessor();
    $processor->importStylesheet($styleDoc);
    return qp($processor->transformToDoc($sourceDoc));
  }
}
QueryPathExtensionRegistry::extend('QPXSL');