Passed
Push — master ( c562f3...3066ec )
by Thomas
02:12
created

RabbitFish   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 50
ccs 28
cts 28
cp 1
rs 10
c 0
b 0
f 0
wmc 10
lcom 1
cbo 2

2 Methods

Rating   Name   Duplication   Size   Complexity  
B getNodes() 0 16 5
B getNodesArray() 0 20 5
1
<?php
2
/**
3
 * Serialize a DOM to RabbitFish Json: http://www.bramstein.com/projects/xsltjson/
4
 *
5
 * @license http://www.opensource.org/licenses/mit-license.php The MIT License
6
 * @copyright Copyright (c) 2009-2017 FluentDOM Contributors
7
 */
8
9
namespace FluentDOM\Serializer\Json {
10
11
  use FluentDOM\DOM\Xpath;
12
13
  /**
14
   * Serialize a DOM to RabbitFish Json: http://www.bramstein.com/projects/xsltjson/
15
   *
16
   * @license http://www.opensource.org/licenses/mit-license.php The MIT License
17
   * @copyright Copyright (c) 2009-2017 FluentDOM Contributors
18
   */
19
  class RabbitFish extends BadgerFish {
20
21
    /**
22
     * @param \DOMElement $node
23
     * @return mixed
24
     */
25 9
    protected function getNodes(\DOMElement $node) {
26 9
      $xpath = new Xpath($node->ownerDocument);
27 9
      $hasText = $xpath->evaluate('count(text()[normalize-space(.) != ""]) > 0', $node);
28 9
      $hasElements = $xpath->evaluate('count(*) > 0', $node);
29 9
      $attributes = new \stdClass();
30 9
      $this->addAttributes($attributes, $node, $xpath);
31 9
      $this->addNamespaces($attributes, $node, $xpath);
32 9
      $attributes = (array)$attributes;
33 9
      if ($hasText && $hasElements) {
34 2
        return $this->getNodesArray($node, $attributes, $xpath);
35
      }
36 9
      if ($hasText && count($attributes) === 0) {
37 5
        return $node->nodeValue;
38
      }
39 6
      return parent::getNodes($node);
40
    }
41
42
    /**
43
     * @param \DOMElement $node
44
     * @param \stdClass|array $attributes
45
     * @param Xpath $xpath
46
     * @return array
47
     */
48 2
    private function getNodesArray(\DOMElement $node, $attributes, $xpath): array {
49 2
      $result = [];
50 2
      foreach ((array)$attributes as $name => $value) {
51 1
        $child = new \stdClass();
52 1
        $child->{$name} = $value;
53 1
        $result[] = $child;
54
      }
55 2
      $nodes = $xpath->evaluate('*|text()[normalize-space(.) != ""]', $node);
56 2
      foreach ($nodes as $childNode) {
57
        /** @var \DOMElement|\DOMText|\DOMCdataSection $childNode */
58 2
        if ($childNode instanceof \DOMElement) {
59 2
          $child = new \stdClass();
60 2
          $child->{$childNode->nodeName} = $this->getNodes($childNode);
61 2
          $result[] = $child;
62 2
        } elseif (!$childNode->isWhitespaceInElementContent()) {
63 2
          $result[] = $childNode->nodeValue;
64
        }
65
      }
66 2
      return $result;
67
    }
68
  }
69
}