GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Push — 2.x ( b807ec...c3a6ab )
by Patrick D
02:30
created

DOMDoc::appendSibling()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3.1406

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 6
cts 8
cp 0.75
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 9
nc 3
nop 2
crap 3.1406
1
<?php namespace BetterDOMDocument;
2
3
use Symfony\Component\CssSelector\CssSelectorConverter;
4
5
/**
6
 * Highwire Better DOM Document
7
 *
8
 * Copyright (c) 2010-2011 Board of Trustees, Leland Stanford Jr. University
9
 * This software is open-source licensed under the GNU Public License Version 2 or later
10
 */
11
class DOMDoc extends \DOMDocument {
12
13
  private $auto_ns = FALSE;
14
  public  $ns = array();
15
  public  $default_ns = FALSE;
16
  public  $error_checking = 'strict'; // Can be 'strict', 'warning', 'none' / FALSE
17
  
18
  /**
19
   * Create a new DOMDoc
20
   *
21
   * @param mixed $xml
22
   *  $xml can either be an XML string, a DOMDocument, or a DOMElement. 
23
   *  You can also pass FALSE or NULL (or omit it) and load XML later using loadXML or loadHTML
24
   * 
25
   * @param mixed $auto_register_namespaces 
26
   *  Auto-register namespaces. All namespaces in the root element will be registered for use in xpath queries.
27
   *  Namespaces that are not declared in the root element will not be auto-registered
28
   *  Defaults to TRUE (Meaning it will auto register all auxiliary namespaces but not the default namespace).
29
   *  Pass a prefix string to automatically register the default namespace.
30
   *  Pass FALSE to disable auto-namespace registeration
31
   * 
32
   * @param bool $error_checking
33
   *  Can be 'strict', 'warning', or 'none. Defaults to 'strict'.
34
   *  'none' supresses all errors
35
   *  'warning' is the default behavior in DOMDocument
36
   *  'strict' corresponds to DOMDocument strictErrorChecking TRUE
37
   */
38 24
  public function __construct($xml = FALSE, $auto_register_namespaces = TRUE, $error_checking = 'strict') {
39 24
    parent::__construct();
40
41 24
    $this->setErrorChecking($error_checking);
42
    
43 24
    if(is_object($xml)){
44 17
      if (is_a($xml, 'DOMElement')) {
45 8
        $this->appendChild($this->importNode($xml, true));
46
      }
47 17
      if (is_a($xml, 'BetterDOMDocument\DOMDoc')) {
48
        if ($xml->documentElement) {
49
          $this->appendChild($this->importNode($xml->documentElement, true));
50
        }
51
        $this->ns = $xml->ns;
52
      }
53 17
      if (is_a($xml, 'DOMDocument')) {
54 17
        if ($xml->documentElement) {
55 17
          $this->appendChild($this->importNode($xml->documentElement, true));
56
        }
57
      }
58
    }
59 17
    else if (is_string($xml) && !empty($xml)) {
60 14
      if ($this->error_checking == 'none') {
61
        @$this->loadXML($xml, LIBXML_COMPACT);
62
      }
63 14
      else if (!$this->loadXML($xml, LIBXML_COMPACT)) {
64
        trigger_error('BetterDOMDocument\DOMDoc: Could not load: ' . htmlspecialchars($xml), E_USER_WARNING);
65
      }
66
    }
67
68 24
    if ($auto_register_namespaces) {
69 24
      $this->AutoRegisterNamespace($auto_register_namespaces);
70
    }
71 24
  }
72
73
  /**
74
   * Register a namespace to be used in xpath queries
75
   *
76
   * @param string $prefix
77
   *  Namespace prefix to register
78
   *
79
   * @param string $url
80
   *  Connonical URL for this namespace prefix
81
   */
82 13
  public function registerNamespace($prefix, $url) {
83 13
    $this->ns[$prefix] = $url;
84 13
  }
85
86
  /**
87
   * Get the list of registered namespaces as an array
88
   */
89 7
  public function getNamespaces() {
90 7
    return $this->ns;
91
  }
92
93
  /**
94
   * Given a namespace URL, get the prefix
95
   * 
96
   * @param string $url
97
   *  Connonical URL for this namespace prefix
98
   * 
99
   * @return string|false
100
   *  The namespace prefix or FALSE if there is no namespace with that URL
101
   */
102 1
  public function lookupPrefix($url) {
103 1
    return array_search($url, $this->ns);
104
  }
105
106
  /**
107
   * Given a namespace prefix, get the URL
108
   * 
109
   * @param string $prefix
110
   *  namespace prefix
111
   * 
112
   * return string|false
113
   *  The namespace URL or FALSE if there is no namespace with that prefix
114
   */
115 1
  public function lookupURL($prefix) {
116 1
    if (isset($this->ns[$prefix])) {
117 1
      return $this->ns[$prefix];
118
    }
119
    else {
120
      return FALSE;
121
    }
122
  }
123
124
  /**
125
   * Given an xpath, get a list of nodes.
126
   * 
127
   * @param string $xpath
128
   *  xpath to be used for query
129
   * 
130
   * @param mixed $context
131
   *  $context can either be an xpath string, or a DOMElement
132
   *  Provides context for the xpath query
133
   * 
134
   * @return DOMList|false
135
   *  A DOMList object, which is very similar to a DOMNodeList, but with better iterabilility.
136
   */
137 18
  public function xpath($xpath, $context = NULL) {
138 18
    $this->createContext($context, 'xpath', FALSE);
139
140 18
    if ($context === FALSE) {
141
      return FALSE;
142
    }
143
    
144 18
    $xob = new \DOMXPath($this);
145
146
    // Register the namespaces
147 18
    foreach ($this->ns as $namespace => $url) {
148 9
      $xob->registerNamespace($namespace, $url);
149
    }
150
151 18
    if ($context) {
152 3
      $result = $xob->query($xpath, $context);
153
    }
154
    else {
155 18
      $result = $xob->query($xpath);
156
    }
157
158 18
    if ($result) {
159 18
      return new DOMList($result, $this);
160
    }
161
    else {
162
      return FALSE;
163
    }
164
  }
165
166
167
  /**
168
   * Given an xpath, get a single node (first one found)
169
   * 
170
   * @param string $xpath
171
   *  xpath to be used for query
172
   * 
173
   * @param mixed $context
174
   *  $context can either be an xpath string, or a DOMElement
175
   *  Provides context for the xpath query
176
   * 
177
   * @return mixed
178
   *  The first node found by the xpath query
179
   */
180 18
  public function xpathSingle($xpath, $context = NULL) {
181 18
    $result = $this->xpath($xpath, $context);
182
    
183 18
    if (empty($result) || !count($result)) {
184 2
      return FALSE;
185
    }
186
    else {
187 17
      return $result->item(0);
188
    }
189
  }
190
191
192
  /**
193
   * Given an CSS selector, get a list of nodes.
194
   * 
195
   * @param string $css_selector
196
   *  CSS Selector to be used for query
197
   * 
198
   * @param mixed $context
199
   *  $context can either be an xpath string, or a DOMElement
200
   *  Provides context for the CSS selector
201
   * 
202
   * @return DOMList|false
203
   *  A DOMList object, which is very similar to a DOMNodeList, but with better iterabilility.
204
   */
205 1
  public function select($css_selector, $context = NULL) {
206 1
    $converter = new CssSelectorConverter();
207 1
    $xpath = $converter->toXPath($css_selector);
208
209 1
    return $this->xpath($xpath, $context);
210
  }
211
212
  /**
213
   * Given an CSS selector, get a single node.
214
   * 
215
   * @param string $css_selector
216
   *  CSS Selector to be used for query
217
   * 
218
   * @param mixed $context
219
   *  $context can either be an xpath string, or a DOMElement
220
   *  Provides context for the CSS selector
221
   * 
222
   * @return DOMList
223
   *  A DOMList object, which is very similar to a DOMNodeList, but with better iterabilility.
224
   */
225 1
  public function selectSingle($css_selector, $context = NULL) {
226 1
    $converter = new CssSelectorConverter();
227 1
    $xpath = $converter->toXPath($css_selector);
228
229 1
    return $this->xpathSingle($xpath, $context);
230
  }
231
232
  /**
233
   * Get the document (or an element) as an array
234
   *
235
   * @param string $raw
236
   *  Can be either FALSE, 'full', or 'inner'. Defaults to FALSE.
237
   *  When set to 'full' every node's full XML is also attached to the array
238
   *  When set to 'inner' every node's inner XML is attached to the array.
239
   * 
240
   * @param mixed $context 
241
   *  Optional context node. Can pass an DOMElement object or an xpath string.
242
   *  If passed, only the given node will be used when generating the array 
243
   */
244 1
  public function getArray($raw = FALSE, $context = NULL) {
245 1
    $array = false;
246
247 1
    $this->createContext($context, 'xpath', FALSE);
248
    
249 1
    if ($context) {
250 1
      if ($raw == 'full') {
251 1
        $array['#raw'] = $this->saveXML($context);
252
      }
253 1
      if ($raw == 'inner') {
254 1
        $array['#raw'] = $this->innerText($context);
255
      }
256 1
      if ($context->hasAttributes()) {
257 1
        foreach ($context->attributes as $attr) {
258 1
          $array['@'.$attr->nodeName] = $attr->nodeValue;
259
        }
260
      }
261
  
262 1
      if ($context->hasChildNodes()) {
263 1
        if ($context->childNodes->length == 1 && $context->firstChild->nodeType == XML_TEXT_NODE) {
264 1
          $array['#text'] = $context->firstChild->nodeValue;
265
        }
266
        else {
267 1
          foreach ($context->childNodes as $childNode) {
268 1
            if ($childNode->nodeType == XML_ELEMENT_NODE) {
269 1
              $array[$childNode->nodeName][] = $this->getArray($raw, $childNode);
270
            }
271 1
            elseif ($childNode->nodeType == XML_CDATA_SECTION_NODE) {
272 1
              $array['#text'] = $childNode->textContent;
273
            }
274
          }
275
        }
276
      }
277
    }
278
    // Else no node was passed, which means we are processing the entire domDocument
279
    else {
280 1
      foreach ($this->childNodes as $childNode) {
281 1
        if ($childNode->nodeType == XML_ELEMENT_NODE) {
282 1
          $array[$childNode->nodeName][] = $this->getArray($raw, $childNode);
283
        }
284
      }
285
    }
286
287 1
    return $array;
288
  }
289
  
290
  /**
291
   * Get the inner text of an element
292
   * 
293
   * @param mixed $context 
294
   *  Optional context node. Can pass an DOMElement object or an xpath string.
295
   */
296 1
  public function innerText($context = NULL) {
297 1
    $this->createContext($context, 'xpath');
298
    
299 1
    $pattern = "/<".preg_quote($context->nodeName)."\b[^>]*>(.*)<\/".preg_quote($context->nodeName).">/s";
300 1
    $matches = array();
301 1
    if (preg_match($pattern, $this->saveXML($context), $matches)) {
302 1
      return $matches[1];
303
    }
304
    else {
305 1
      return '';
306
    }
307
  }
308
309
  /**
310
   * Create an DOMElement from XML and attach it to the DOMDocument
311
   * 
312
   * Note that this does not place it anywhere in the dom tree, it merely imports it.
313
   * 
314
   * @param string $xml 
315
   *  XML string to import
316
   */
317 5
  public function createElementFromXML($xml) {
318
    
319
    // To make thing easy and make sure namespaces work properly, we add the root namespace delcarations if it is not declared
320 5
    $namespaces = $this->ns;
321 5
    $xml = preg_replace_callback('/<[^\?^!].+?>/s', function($root_match) use ($namespaces) {
322 5
      preg_match('/<([^ <>]+)[\d\s]?.*?>/s', $root_match[0], $root_tag);
323 5
      $new_root = $root_tag[1];
324 5
      if (strpos($new_root, ':')) {
325
        $parts = explode(':', $new_root);
326
        $prefix = $parts[0]; 
327
        if (isset($namespaces[$prefix])) {
328
          if (!strpos($root_match[0], "xmlns:$prefix")) {
329
            $new_root .= " xmlns:$prefix='" . $namespaces[$prefix] . "'";             
330
          }
331
        }
332
      }
333 5
      return str_replace($root_tag[1], $new_root, $root_match[0]);
334 5
    }, $xml, 1);
335
336 5
    $dom = new DOMDoc($xml, $this->auto_ns);
337 5
    if (!$dom->documentElement) {
338
      trigger_error('BetterDomDocument\DOMDoc Error: Invalid XML: ' . $xml);
339
    }
340 5
    $element = $dom->documentElement;
341
    
342
    // Merge the namespaces
343 5
    foreach ($dom->getNamespaces() as $prefix => $url) {
344
      $this->registerNamespace($prefix, $url);
345
    }
346
    
347 5
    return $this->importNode($element, true);
348
  }
349
350
  /**
351
   * Append a child to the context node, make it the last child
352
   * 
353
   * @param mixed $newnode
354
   *  $newnode can either be an XML string, a DOMDocument, or a DOMElement. 
355
   * 
356
   * @param mixed $context
357
   *  $context can either be an xpath string, or a DOMElement
358
   *  Omiting $context results in using the root document element as the context
359
   * 
360
   * @return DOMElement|false
361
   *  The $newnode, properly attached to DOMDocument. If you passed $newnode as a DOMElement
362
   *  then you should replace your DOMElement with the returned one.
363
   */
364 1 View Code Duplication
  public function append($newnode, $context = NULL) {
365 1
    $this->createContext($newnode, 'xml');
366 1
    $this->createContext($context, 'xpath');
367
    
368 1
    if (!$context || !$newnode) {
369
      return FALSE;
370
    }
371
372 1
    return $context->appendChild($newnode);
373
  }
374
  
375
  /**
376
   * Append a child to the context node, make it the first child
377
   * 
378
   * @param mixed $newnode
379
   *  $newnode can either be an XML string, a DOMDocument, or a DOMElement. 
380
   * 
381
   * @param mixed $context
382
   *  $context can either be an xpath string, or a DOMElement
383
   *  Omiting $context results in using the root document element as the context
384
   *
385
   * @return DOMElement|false
386
   *  The $newnode, properly attached to DOMDocument. If you passed $newnode as a DOMElement
387
   *  then you should replace your DOMElement with the returned one.
388
   */
389 1 View Code Duplication
  public function prepend($newnode, $context = NULL) {
1 ignored issue
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
390 1
    $this->createContext($newnode, 'xml');
391 1
    $this->createContext($context, 'xpath');
392
    
393 1
    if (!$context || !$newnode) {
394
      return FALSE;
395
    }
396
    
397 1
    return $context->insertBefore($newnode, $context->firstChild);
398
  }
399
400
  /**
401
   * Prepend a sibling to the context node, put it just before the context node
402
   * 
403
   * @param mixed $newnode
404
   *  $newnode can either be an XML string, a DOMDocument, or a DOMElement. 
405
   * 
406
   * @param mixed $context
407
   *  $context can either be an xpath string, or a DOMElement
408
   *  Omiting $context results in using the root document element as the context 
409
   * 
410
   * @return DOMElement|false
411
   *  The $newnode, properly attached to DOMDocument. If you passed $newnode as a DOMElement
412
   *  then you should replace your DOMElement with the returned one.
413
   */
414 1 View Code Duplication
  public function prependSibling($newnode, $context = NULL) {
415 1
    $this->createContext($newnode, 'xml');
416 1
    $this->createContext($context, 'xpath');
417
    
418 1
    if (!$context || !$newnode) {
419
      return FALSE;
420
    }
421
    
422 1
    return $context->parentNode->insertBefore($newnode, $context);
423
  }
424
  
425
  /**
426
   * Append a sibling to the context node, put it just after the context node
427
   * 
428
   * @param mixed $newnode
429
   *  $newnode can either be an XML string, a DOMDocument, or a DOMElement. 
430
   * 
431
   * @param mixed $context
432
   *  $context can either be an xpath string, or a DOMElement
433
   *  Omiting $context results in using the root document element as the context 
434
   * 
435
   * @return DOMElement|false
436
   *  The $newnode, properly attached to DOMDocument. If you passed $newnode as a DOMElement
437
   *  then you should replace your DOMElement with the returned one.
438
   */
439 1
  public function appendSibling($newnode, $context) {
440 1
    $this->createContext($newnode, 'xml');
441 1
    $this->createContext($context, 'xpath');
442
    
443 1
    if (!$context){
444
      return FALSE;
445
    }
446
    
447 1
    if ($context->nextSibling) { 
448
      // $context has an immediate sibling : insert newnode before this one 
449 1
      return $context->parentNode->insertBefore($newnode, $context->nextSibling); 
450
    }
451
    else { 
452
      return $context->parentNode->appendChild($newnode); 
453
    }
454
  }
455
  
456
  /**
457
   * Given an xpath or DOMElement, return a new DOMDoc.
458
   * 
459
   * @param mixed $node
460
   *  $node can either be an xpath string or a DOMElement. 
461
   * 
462
   * @return DOMDoc
463
   *  A new DOMDoc created from the xpath or DOMElement
464
   */
465 7
  public function extract($node, $auto_register_namespaces = TRUE, $error_checking = 'none') {
466 7
    $this->createContext($node, 'xpath');
467 7
    $dom = new DOMDoc($node, $auto_register_namespaces, $error_checking);
468 7
    $dom->ns = $this->ns;
469 7
    return $dom;
470
  }
471
  
472
  /**
473
   * Given a pair of nodes, replace the first with the second
474
   * 
475
   * @param mixed $node
476
   *  Node to be replaced. Can either be an xpath string or a DOMDocument (or even a DOMNode).
477
   * 
478
   * @param mixed $replace
479
   *  Replace $node with $replace. Replace can be an XML string, or a DOMNode
480
   * 
481
   * @return mixed
482
   *   The overwritten / replaced node.
483
   */
484 2
  public function replace($node, $replace) {
485 2
    $this->createContext($node, 'xpath');
486 2
    $this->createContext($replace, 'xml');
487
    
488 2
    if (!$node || !$replace) {
489
      return FALSE;
490
    }
491
        
492 2
    if (!$replace->ownerDocument->documentElement->isSameNode($this->documentElement)) {
493
      $replace = $this->importNode($replace, true);
494
    }
495 2
    $node->parentNode->replaceChild($replace, $node);
496 2
    $node = $replace;
497 2
    return $node;
498
  }
499
500
  /**
501
   * Given a node(s), remove / delete them
502
   * 
503
   * @param mixed $node
504
   *  Can pass a DOMNode, a NodeList, DOMNodeList, an xpath string, or an array of any of these.
505
   */
506 1
  public function remove($node) {
507
    // We can't use createContext here because we want to use the entire nodeList (not just a single element)
508 1
    if (is_string($node)) {
509 1
      $node = $this->xpath($node);
510
    }
511
    
512 1
    if ($node) {
513 1
      if (is_array($node) || get_class($node) == 'BetterDOMDocument\DOMList') {
514 1
        foreach($node as $item) {
515 1
          $this->remove($item);
516
        }
517
      }
518 1
      else if (get_class($node) == 'DOMNodeList') {
519
        $this->remove(new DOMList($node, $this));
520
      }
521
      else {
522 1
        $parent = $node->parentNode;
523 1
        $parent->removeChild($node);
524
      }
525
    }
526 1
  }
527
  
528
  /**
529
   * Given an XSL string, transform the DOMDoc (or a passed context node)
530
   * 
531
   * @param string $xsl
532
   *   XSL Transormation
533
   * 
534
   * @param mixed $context
535
   *   $context can either be an xpath string, or a DOMElement. Ommiting it
536
   *   results in transforming the entire document
537
   * 
538
   * @return a new DOMDoc
539
   */
540 4
  public function tranform($xsl, $context = NULL) {
541 4
    if (!$context) {
542 2
      $doc = $this;
543
    }
544
    else {
545 2
      if (is_string($context)) {
546 1
        $context = $this->xpathSingle($context);
547
      }
548 2
      $doc = new DOMDoc($context);
549
    }
550
    
551 4
    $xslDoc = new DOMDoc($xsl);
552 4
    $xslt = new \XSLTProcessor();
553 4
    $xslt->importStylesheet($xslDoc);
554
    
555 4
    return new DOMDoc($xslt->transformToDoc($doc));
556
  }
557
558
  /**
559
   * Given a node, change it's namespace to the specified namespace in situ
560
   * 
561
   * @param mixed $node
562
   *  Node to be changed. Can either be an xpath string or a DOMElement.
563
   * 
564
   * @param mixed $prefix
565
   *   prefix for the new namespace
566
   * 
567
   * @param mixed $url
568
   *   The URL for the new namespace
569
   * 
570
   * @return mixed
571
   *   The node with the new namespace. The node will also be changed in-situ in the document as well.
572
   */
573 1
  public function changeNamespace($node, $prefix, $url) {
574 1
    $this->createContext($node, 'xpath');
575
    
576 1
    if (!$node) {
577
      return FALSE;
578
    }
579
    
580 1
    $this->registerNamespace($prefix, $url);
581
582 1
    if (get_class($node) == 'DOMElement') {
583
      $xsl = '
584
        <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
585
          <xsl:template match="*">
586 1
            <xsl:element name="' . $prefix . ':{local-name()}" namespace="' . $url . '">
587
             <xsl:copy-of select="@*"/>
588
             <xsl:apply-templates/>
589
            </xsl:element>
590
          </xsl:template>
591 1
        </xsl:stylesheet>';
592
593 1
      $transformed = $this->tranform($xsl, $node);
594 1
      return $this->replace($node, $transformed->documentElement);   
595
    }
596
    else {
597
      // @@TODO: Report the correct calling file and number
598
      throw new Exception("Changing the namespace of a " . get_class($node) . " is not supported");
599
    }
600
  }
601
602
  /**
603
   * Get a lossless HTML representation of the XML
604
   *
605
   * Transforms the document (or passed context) into a set of HTML spans.
606
   * The element name becomes the class, all other attributes become HTML5
607
   * "data-" attributes.
608
   * 
609
   * @param mixed $context
610
   *   $context can either be an xpath string, or a DOMElement. Ommiting it
611
   *   results in transforming the entire document
612
   * 
613
   * @param array $options
614
   *   Options for transforming the HTML into XML. The following options are supported:
615
   *   'xlink' => {TRUE or xpath}
616
   *     Transform xlink links into <a href> elements. If you specify 'xlink' => TRUE then 
617
   *     it will transform all elements with xlink:type = simple into a <a href> element. 
618
   *     Alternatively you may specify your own xpath for selecting which elements get transformed
619
   *     into <a href> tags. 
620
   * @return HTML string
621
   */  
622 3
  public function asHTML($context = NULL, $options = array()) {
623
    $xslSimple = '
624
      <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
625
      <xsl:template match="*">
626
        <span class="{translate(name(.),\':\',\'-\')}">
627
          <xsl:for-each select="./@*">
628
            <xsl:attribute name="data-{translate(name(.),\':\',\'-\')}">
629
              <xsl:value-of select="." />
630
            </xsl:attribute>
631
          </xsl:for-each>
632
          <xsl:apply-templates/>
633
        </span>
634
      </xsl:template>
635 3
      </xsl:stylesheet>';
636
637
    $xslOptions = '
638
      <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xlink="http://www.w3.org/1999/xlink" ||namespaces||>
639
      <xsl:template match="*">
640
        <xsl:choose>
641
          <xsl:when test="||xlink||">
642
            <a class="{translate(name(.),\':\',\'-\')}">
643
              <xsl:for-each select="./@*">
644
                <xsl:attribute name="data-{translate(name(.),\':\',\'-\')}">
645
                  <xsl:value-of select="."/>
646
                </xsl:attribute>
647
              </xsl:for-each>
648
              <xsl:attribute name="href">
649
                <xsl:value-of select="@xlink:href"/>
650
              </xsl:attribute>
651
              <xsl:apply-templates/>
652
            </a>
653
          </xsl:when>
654
          <xsl:otherwise>
655
            <span class="{translate(name(.),\':\',\'-\')}">
656
              <xsl:for-each select="./@*">
657
                <xsl:attribute name="data-{translate(name(.),\':\',\'-\')}">
658
                  <xsl:value-of select="." />
659
                </xsl:attribute>
660
              </xsl:for-each>
661
              <xsl:apply-templates/>
662
            </span>
663
          </xsl:otherwise>
664
        </xsl:choose>
665
      </xsl:template>
666 3
      </xsl:stylesheet>';
667
668 3
    if (!empty($options)) {
669
      // Add in the namespaces
670 1
      foreach ($this->getNamespaces() as $prefix => $url) {
671 1
        $namespaces = '';
672 1
        if ($prefix != 'xsl' && $prefix != 'xlink') {
673 1
          $namespaces .= 'xmlns:' . $prefix . '="' . $url. '" ';
674
        }
675 1
        $xslOptions = str_replace("||namespaces||", $namespaces, $xslOptions);
676
      }
677
678
      // Add in xlink options
679 1
      if ($options['xlink'] === TRUE) {
680 1
        $options['xlink'] = "@xlink:type = 'simple'";
681
      }
682
      else if (empty($options['xlink'])) {
683
        $options['xlink'] = "false()";
684
      }
685 1
      $xslOptions = str_replace("||xlink||", $options['xlink'], $xslOptions);
686 1
      $transformed = $this->tranform($xslOptions, $context);
687
    }
688
    else {
689 2
      $transformed = $this->tranform($xslSimple, $context);
690
    }
691
    
692 3
    return $transformed->out();
693
  }
694
695
  /**
696
   * Output the DOMDoc as an XML string
697
   * 
698
   * @param mixed $context
699
   *   $context can either be an xpath string, or a DOMElement. Ommiting it
700
   *   results in outputting the entire document
701
   * 
702
   * @return XML string
703
   */  
704 12
  public function out($context = NULL) {
705 12
    $this->createContext($context, 'xpath');
706 12
    if (!$context) {
707 2
      return '';
708
    }
709
710
    // Copy namespace prefixes
711 10
    foreach ($this->ns as $prefix => $namespace) {
712
      if (!$context->hasAttribute('xmlns:' . $prefix)) {
713
        $context->setAttribute('xmlns:' . $prefix, $namespace);
714
      }
715
    }
716
    
717
    // Check to seee if it's HTML, if it is we need to fix broken html void elements.
718 10
    if ($this->documentElement->lookupNamespaceURI(NULL) == 'http://www.w3.org/1999/xhtml' || $this->documentElement->tagName == 'html') {
719 1
      $output = $this->saveXML($context, LIBXML_NOEMPTYTAG);
720
      // The types listed are html "void" elements. 
721
      // Find any of these elements that have no child nodes and are therefore candidates for self-closing, replace them with a self-closed version. 
722 1
      $pattern = '<(area|base|br|col|command|embed|hr|img|input|keygen|link|meta|param|source|track|wbr)(\b[^<]*)><\/\1>';
723 1
      return preg_replace('/' . $pattern . '/', '<$1$2/>', $output);
724
    }
725
    else {
726 9
      return $this->saveXML($context, LIBXML_NOEMPTYTAG);
727
    }
728
  }
729
730
  /**
731
   * Magic method for casting a DOMDoc as a string
732
   */ 
733 1
  public function __toString() {
734 1
    return $this->out();
735
  }
736
737 24
  public function setErrorChecking($error_checking) {
738
    // Check up error-checking
739 24
    if ($error_checking == FALSE) {
740
      $this->error_checking = 'none';
741
    }
742
    else {
743 24
      $this->error_checking = $error_checking;
744
    }
745 24
    if ($this->error_checking != 'strict') {
746 7
      $this->strictErrorChecking = FALSE;
747
    }
748 24
  }
749
750 14
  public static function loadFile($file_or_url, $auto_register_namespaces = TRUE) {
751 14
    $dom = @parent::load($file_or_url, LIBXML_COMPACT);
752 14
    if (empty($dom)) {
753
      return FALSE;
754
    }
755
756 14
    return new DOMDoc($dom, $auto_register_namespaces);
757
  }
758
759 1
  public function loadHTML($source, $options = NULL) {
760 1
    $success = parent::loadHTML($source, $options);
761 1
    $this->AutoRegisterNamespace(TRUE);
762
763 1
    return boolval($success);
764
  }
765
766 14
  public function loadXML($source, $options = NULL) {
767 14
    $success = parent::loadXML($source, $options);
768 14
    $this->AutoRegisterNamespace(TRUE);
769
    
770 14
    return boolval($success);
771
  }
772
773 24
  private function AutoRegisterNamespace($auto_register_namespaces) {
774 24
    $this->auto_ns = TRUE;
775
776
    // If it's an "XML" document, then get namespaces via xpath
777 24
    $xpath = new \DOMXPath($this);
778 24
    foreach($xpath->query('namespace::*') as $namespace) {
779 23
      if (!empty($namespace->prefix)) {
780 23
        if ($namespace->prefix != 'xml' && $namespace->nodeValue != 'http://www.w3.org/XML/1998/namespace') {
781 23
          $this->registerNamespace($namespace->prefix, $namespace->nodeValue);
782
        }
783
      }
784 View Code Duplication
      else {
785 3
        $this->default_ns = $namespace->nodeValue;
786 3
        if (is_string($auto_register_namespaces)) {
787
          $this->registerNamespace($auto_register_namespaces, $namespace->nodeValue);
788
        }
789
        // Otherwise, automatically set-up the root element tag name as the prefix for the default namespace
790
        else {
791 3
          $tagname = $this->documentElement->tagName;
792 3
          if (empty($this->ns[$tagname])) {
793 23
            $this->registerNamespace($tagname, $this->documentElement->getAttribute('xmlns'));
794
          }
795
        }
796
      }
797
    }
798
799
    // If it's an "HTML" document, we get namespaces via attributes
800 24
    if (empty($this->ns) && !empty($this->documentElement)) {
801 15
      foreach ($this->documentElement->attributes as $attr) {
802 4
        if ($attr->name == 'xmlns') {
803 1
          $this->default_ns = $attr->value;
804
          // If auto_register_namespaces is a prefix string, then we register the default namespace to that string
805 1 View Code Duplication
          if (is_string($auto_register_namespaces)) {
806
            $this->registerNamespace($auto_register_namespaces, $attr->value);
807
          }
808
          // Otherwise, automatically set-up the root element tag name as the prefix for the default namespace
809
          else {
810 1
            $tagname = $this->documentElement->tagName;
811 1
            if (empty($this->ns[$tagname])) {
812 1
              $this->registerNamespace($tagname, $attr->value);
813
            } 
814
          }
815
        }
816 3
        else if (substr($attr->name,0,6) == 'xmlns:') {
817
          $prefix = substr($attr->name,6);
818 4
          $this->registerNamespace($prefix, $attr->value); 
819
        }
820
      }
821
    }
822 24
  }
823
  
824 22
  private function createContext(&$context, $type = 'xpath', $createDocument = TRUE) {
825 22
    if (!$context && $createDocument) {
826 11
      $context = $this->documentElement;
827 11
      return;
828
    }
829
830 19
    if (!$context) {
831 19
      return FALSE;
832
    }
833
834 13
    if ($context && is_string($context)) {
835 12
      if ($type == 'xpath') {
836 12
        $context = $this->xpathSingle($context);
837 12
        return;
838
      }
839 5
      if ($type == 'xml') {
840 5
        $context = $this->createElementFromXML($context);
841 5
        return;
842
      }
843
    }
844
845 2
    if (is_object($context) && is_a($context, 'DOMNode')) {
846 2
      if ($context->ownerDocument === $this) {
847 2
        return;
848
      }
849 1
      if (is_a($context, 'BetterDOMDocument\DOMDoc')) {
850
        foreach ($context->ns as $prefix => $uri) {
851
          $this->registerNamespace($prefix, $uri);
852
        }
853
        $context = $this->importNode($context->documentElement, TRUE);
854
        return;
855
      }
856 1
      else if (is_a($context, 'DOMDocument')) {
857
        $context = $this->importNode($context->documentElement, TRUE);
858
        return;
859
      }
860
      else {
861 1
        $context = $this->importNode($context, TRUE);
862 1
        return;
863
      }
864
    }
865
866
    return FALSE;
867
  }
868
}
869
870
871
872