Passed
Push — master ( 6d7a51...05f3bf )
by Andreas
05:30 queued 30s
created

GeoJsonService   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Test Coverage

Coverage 86.67%

Importance

Changes 0
Metric Value
eloc 33
dl 0
loc 61
ccs 26
cts 30
cp 0.8667
rs 10
c 0
b 0
f 0
wmc 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getConfig() 0 10 3
B index() 0 43 7
1
<?php
2
3
namespace Smindel\GIS\Control;
4
5
use SilverStripe\Core\Injector\Injector;
6
use SilverStripe\Control\Controller;
7
use SilverStripe\Core\Config\Config;
8
use Smindel\GIS\GIS;
9
10
class GeoJsonService extends AbstractGISWebServiceController
11
{
12
    private static $url_handlers = array(
13
        '$Model' => 'handleAction',
14
    );
15
16 2
    public function getConfig($model)
17
    {
18 2
        $modelConfig = parent::getConfig($model);
19 2
        if (!$modelConfig) {
20
            return false;
21
        }
22
        $defaults = [
23 2
            'property_map' => singleton($model)->summaryFields(),
24
        ];
25 2
        return is_array($modelConfig) ? array_merge($defaults, $modelConfig) : $defaults;
26
    }
27
28 2
    public function index($request)
29
    {
30 2
        $model = $this->getModel($request);
31 2
        $config = $this->getConfig($model);
32 2
        $list = $this->getRecords($request);
33
34 2
        $propertyMap = $config['property_map'];
35
36
        // The HTTP kernel keeps a copy of the response body, which
37
        // can exhaust the memory limit for large data sets. So we
38
        // opt out and flush the buffer after processing each feature.
39 2
        if (!($is_test = headers_sent())) {
40
            header('Content-Type: application/geo+json');
41
        }
42 2
        echo '{"type":"FeatureCollection","features":[';
43
44 2
        foreach ($list as $item) {
45 2
            if (!$item->canView()) {
46
                continue;
47
            }
48
49 2
            echo isset($geo) ? ',' : '';
50
51 2
            $geo = GIS::create($item->{$config['geometry_field']})->reproject(4326);
52
53 2
            $properties = [];
54 2
            foreach ($propertyMap as $fieldName => $propertyName) {
55 2
                $properties[$propertyName] = $item->$fieldName;
56
            }
57
58 2
            echo json_encode([
59 2
                'type' => 'Feature',
60
                'geometry' => [
61 2
                    'type' => $geo->type,
62 2
                    'coordinates' => $geo->coordinates
63
                ],
64 2
                'properties' => $properties,
65
            ]);
66
        }
67
68 2
        echo ']}';
69 2
        if (!$is_test) {
70
            die;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
71
        }
72 2
    }
73
}
74