KML   C
last analyzed

Complexity

Total Complexity 55

Size/Duplication

Total Lines 239
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 0
Metric Value
dl 0
loc 239
rs 6
c 0
b 0
f 0
wmc 55
lcom 1
cbo 6

15 Methods

Rating   Name   Duplication   Size   Complexity  
A read() 0 3 1
A write() 0 7 2
A geomFromText() 0 24 4
B geomFromXML() 0 26 8
A childElements() 0 11 4
A parsePoint() 0 4 1
A parseLineString() 0 8 2
A parsePolygon() 0 24 5
A parseGeometryCollection() 0 12 4
A _extractCoordinates() 0 18 5
B geometryToKML() 0 20 8
A pointToKML() 0 3 1
A linestringToKML() 0 23 5
A polygonToKML() 0 11 3
A collectionToKML() 0 10 2

How to fix   Complexity   

Complex Class

Complex classes like KML often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use KML, and based on these observations, apply Extract Interface, too.

1
<?php
2
/*
3
 * Copyright (c) Patrick Hayes
4
 * Copyright (c) 2010-2011, Arnaud Renevier
5
 *
6
 * This code is open-source and licenced under the Modified BSD License.
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
/**
12
 * PHP Geometry/KML encoder/decoder
13
 *
14
 * Mainly inspired/adapted from OpenLayers( http://www.openlayers.org )
15
 *   Openlayers/format/WKT.js
16
 *
17
 * @package    sfMapFishPlugin
18
 * @subpackage GeoJSON
19
 * @author     Camptocamp <[email protected]>
20
 */
21
class KML extends GeoAdapter
22
{
23
  private $namespace = FALSE;
24
  private $nss = ''; // Name-space string. eg 'georss:'
25
26
  /**
27
   * Read KML string into geometry objects
28
   *
29
   * @param string $kml A KML string
30
   *
31
   * @return Geometry|GeometryCollection
32
   */
33
  public function read($kml) {
34
    return $this->geomFromText($kml);
35
  }
36
37
  /**
38
   * Serialize geometries into a KML string.
39
   *
40
   * @param Geometry $geometry
41
   *
42
   * @return string The KML string representation of the input geometries
43
   */
44
  public function write(Geometry $geometry, $namespace = FALSE) {
45
    if ($namespace) {
46
      $this->namespace = $namespace;
47
      $this->nss = $namespace.':';
48
    }
49
    return $this->geometryToKML($geometry);
50
  }
51
52
  public function geomFromText($text) {
53
54
    // Change to lower-case and strip all CDATA
55
    $text = mb_strtolower($text, mb_detect_encoding($text));
56
    $text = preg_replace('/<!\[cdata\[(.*?)\]\]>/s','',$text);
57
58
    // Load into DOMDOcument
59
    $xmlobj = new DOMDocument();
60
    @$xmlobj->loadXML($text);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
61
    if ($xmlobj === false) {
62
      throw new Exception("Invalid KML: ". $text);
63
    }
64
65
    $this->xmlobj = $xmlobj;
0 ignored issues
show
Bug introduced by
The property xmlobj does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
66
    try {
67
      $geom = $this->geomFromXML();
68
    } catch(InvalidText $e) {
0 ignored issues
show
Bug introduced by
The class InvalidText does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
69
        throw new Exception("Cannot Read Geometry From KML: ". $text);
70
    } catch(Exception $e) {
71
        throw $e;
72
    }
73
74
    return $geom;
75
  }
76
77
  protected function geomFromXML() {
78
    $geometries = array();
79
    $geom_types = geoPHP::geometryList();
80
    $placemark_elements = $this->xmlobj->getElementsByTagName('placemark');
81
    if ($placemark_elements->length) {
82
      foreach ($placemark_elements as $placemark) {
83
        foreach ($placemark->childNodes as $child) {
84
          // Node names are all the same, except for MultiGeometry, which maps to GeometryCollection
85
          $node_name = $child->nodeName == 'multigeometry' ? 'geometrycollection' : $child->nodeName;
86
          if (array_key_exists($node_name, $geom_types)) {
87
            $function = 'parse'.$geom_types[$node_name];
88
            $geometries[] = $this->$function($child);
89
          }
90
        }
91
      }
92
    }
93
    else {
94
      // The document does not have a placemark, try to create a valid geometry from the root element
95
      $node_name = $this->xmlobj->documentElement->nodeName == 'multigeometry' ? 'geometrycollection' : $this->xmlobj->documentElement->nodeName;
96
      if (array_key_exists($node_name, $geom_types)) {
97
        $function = 'parse'.$geom_types[$node_name];
98
        $geometries[] = $this->$function($this->xmlobj->documentElement);
99
      }
100
    }
101
    return geoPHP::geometryReduce($geometries);
102
  }
103
104
  protected function childElements($xml, $nodename = '') {
105
    $children = array();
106
    if ($xml->childNodes) {
107
      foreach ($xml->childNodes as $child) {
108
        if ($child->nodeName == $nodename) {
109
          $children[] = $child;
110
        }
111
      }
112
    }
113
    return $children;
114
  }
115
116
  protected function parsePoint($xml) {
117
    $coordinates = $this->_extractCoordinates($xml);
118
    return new Point($coordinates[0][0],$coordinates[0][1]);
119
  }
120
121
  protected function parseLineString($xml) {
122
    $coordinates = $this->_extractCoordinates($xml);
123
    $point_array = array();
124
    foreach ($coordinates as $set) {
125
      $point_array[] = new Point($set[0],$set[1]);
126
    }
127
    return new LineString($point_array);
128
  }
129
130
  protected function parsePolygon($xml) {
131
    $components = array();
132
133
    $outer_boundary_element_a = $this->childElements($xml, 'outerboundaryis');
134
    $outer_boundary_element = $outer_boundary_element_a[0];
135
    $outer_ring_element_a = $this->childElements($outer_boundary_element, 'linearring');
136
    $outer_ring_element = $outer_ring_element_a[0];
137
    $components[] = $this->parseLineString($outer_ring_element);
138
139
    if (count($components) != 1) {
140
      throw new Exception("Invalid KML");
141
    }
142
143
    $inner_boundary_element_a = $this->childElements($xml, 'innerboundaryis');
144
    if (count($inner_boundary_element_a)) {
145
      foreach ($inner_boundary_element_a as $inner_boundary_element) {
146
        foreach ($this->childElements($inner_boundary_element, 'linearring') as $inner_ring_element) {
147
          $components[] = $this->parseLineString($inner_ring_element);
148
        }
149
      }
150
    }
151
152
    return new Polygon($components);
153
  }
154
155
  protected function parseGeometryCollection($xml) {
156
    $components = array();
157
    $geom_types = geoPHP::geometryList();
158
    foreach ($xml->childNodes as $child) {
159
      $nodeName = ($child->nodeName == 'linearring') ? 'linestring' : $child->nodeName;
160
      if (array_key_exists($nodeName, $geom_types)) {
161
        $function = 'parse'.$geom_types[$nodeName];
162
        $components[] = $this->$function($child);
163
      }
164
    }
165
    return new GeometryCollection($components);
166
  }
167
168
  protected function _extractCoordinates($xml) {
169
    $coord_elements = $this->childElements($xml, 'coordinates');
170
    $coordinates = array();
171
    if (count($coord_elements)) {
172
      $coord_sets = explode(' ', preg_replace('/[\r\n]+/', ' ', $coord_elements[0]->nodeValue));
173
      foreach ($coord_sets as $set_string) {
174
        $set_string = trim($set_string);
175
        if ($set_string) {
176
          $set_array = explode(',',$set_string);
177
          if (count($set_array) >= 2) {
178
            $coordinates[] = $set_array;
179
          }
180
        }
181
      }
182
    }
183
184
    return $coordinates;
185
  }
186
187
  private function geometryToKML($geom) {
188
    $type = strtolower($geom->getGeomType());
189
    switch ($type) {
190
      case 'point':
191
        return $this->pointToKML($geom);
192
        break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
193
      case 'linestring':
194
        return $this->linestringToKML($geom);
195
        break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
196
      case 'polygon':
197
        return $this->polygonToKML($geom);
198
        break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
199
      case 'multipoint':
200
      case 'multilinestring':
201
      case 'multipolygon':
202
      case 'geometrycollection':
203
        return $this->collectionToKML($geom);
204
        break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
205
    }
206
  }
207
208
  private function pointToKML($geom) {
209
    return '<'.$this->nss.'Point><'.$this->nss.'coordinates>'.$geom->getX().",".$geom->getY().'</'.$this->nss.'coordinates></'.$this->nss.'Point>';
210
  }
211
212
  private function linestringToKML($geom, $type = FALSE) {
213
    if (!$type) {
214
      $type = $geom->getGeomType();
215
    }
216
217
    $str = '<'.$this->nss . $type .'>';
218
219
    if (!$geom->isEmpty()) {
220
      $str .= '<'.$this->nss.'coordinates>';
221
      $i=0;
222
      foreach ($geom->getComponents() as $comp) {
223
        if ($i != 0) $str .= ' ';
224
        $str .= $comp->getX() .','. $comp->getY();
225
        $i++;
226
      }
227
228
      $str .= '</'.$this->nss.'coordinates>';
229
    }
230
231
    $str .= '</'. $this->nss . $type .'>';
232
233
    return $str;
234
  }
235
236
  public function polygonToKML($geom) {
237
    $components = $geom->getComponents();
238
    if (!empty($components)) {
239
      $str = '<'.$this->nss.'outerBoundaryIs>' . $this->linestringToKML($components[0], 'LinearRing') . '</'.$this->nss.'outerBoundaryIs>';
0 ignored issues
show
Documentation introduced by
'LinearRing' is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
240
      foreach (array_slice($components, 1) as $comp) {
241
        $str .= '<'.$this->nss.'innerBoundaryIs>' . $this->linestringToKML($comp) . '</'.$this->nss.'innerBoundaryIs>';
242
      }
243
    }
244
245
    return '<'.$this->nss.'Polygon>'. $str .'</'.$this->nss.'Polygon>';
0 ignored issues
show
Bug introduced by
The variable $str does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
246
  }
247
248
  public function collectionToKML($geom) {
249
    $components = $geom->getComponents();
0 ignored issues
show
Unused Code introduced by
$components is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
250
    $str = '<'.$this->nss.'MultiGeometry>';
251
    foreach ($geom->getComponents() as $comp) {
252
      $sub_adapter = new KML();
253
      $str .= $sub_adapter->write($comp);
254
    }
255
256
    return $str .'</'.$this->nss.'MultiGeometry>';
257
  }
258
259
}
260