MapBlock   A
last analyzed

Complexity

Total Complexity 26

Size/Duplication

Total Lines 205
Duplicated Lines 2.44 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 0
Metric Value
wmc 26
lcom 1
cbo 7
dl 5
loc 205
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A singular_name() 0 3 1
A plural_name() 0 3 1
A getCoordinatesAsOption() 0 13 2
B getCMSFields() 0 36 1
A forTemplate() 0 7 2
D getMarkersAsJson() 0 28 9
D getOptionsAsJson() 5 41 10

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
/**
4
 * @author    Donatas Navidonskis <[email protected]>
5
 * @since     2017
6
 * @class     MapBlock
7
 *
8
 * @property int    GlobalMarkerID
9
 * @property string Coordinates
10
 * @property int    ZoomLevel
11
 *
12
 * @method Image GlobalMarker
13
 * @method DataList Markers
14
 */
15
class MapBlock extends BaseBlock {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
16
17
    /**
18
     * @var array
19
     * @config
20
     */
21
    private static $db = [
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $db is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
22
        'Coordinates' => 'Varchar(255)', // center coordinates
23
        'ZoomLevel'   => 'Int(3)', // zoom level of map
24
    ];
25
26
    /**
27
     * @var array
28
     * @config
29
     */
30
    private static $has_many = [
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
31
        'Markers' => 'Marker',
32
    ];
33
34
    /**
35
     * @var array
36
     * @config
37
     */
38
    private static $has_one = [
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
39
        'GlobalMarker' => 'Image',
40
    ];
41
42
    /**
43
     * Google Maps styles in string of JSON format. See
44
     * docs/GOOGLE_MAPS_BLOCK.md how to use it.
45
     *
46
     * @var string|null
47
     * @config
48
     */
49
    private static $map_styles = null;
0 ignored issues
show
Unused Code introduced by
The property $map_styles is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
50
51
    /**
52
     * This will load javascript dependency to initialize
53
     * user client map element.
54
     *
55
     * @var bool
56
     * @config
57
     */
58
    private static $load_javascript = true;
0 ignored issues
show
Unused Code introduced by
The property $load_javascript is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
59
60
    /**
61
     * @return string
62
     */
63
    public function singular_name() {
64
        return _t('MapBlock.SINGULARNAME', 'Map Block');
65
    }
66
67
    /**
68
     * @return string
69
     */
70
    public function plural_name() {
71
        return _t('MapBlock.PLURALNAME', 'Map Blocks');
72
    }
73
74
    /**
75
     * @return array
76
     */
77
    public function getCoordinatesAsOption() {
78
        $coordinates = [];
79
80
        if (! empty($this->Coordinates)) {
81
            list($lat, $lng) = explode(',', $this->Coordinates);
82
            $coordinates['center'] = [
83
                'lat' => (float) $lat,
84
                'lng' => (float) $lng,
85
            ];
86
        }
87
88
        return $coordinates;
89
    }
90
91
    /**
92
     * @return \FieldList
93
     */
94
    public function getCMSFields() {
95
        $fields = parent::getCMSFields();
96
        $fields->removeByName(['Coordinates', 'ZoomLevel']);
97
98
        $coordinates = $this->getCoordinatesAsOption();
99
100
        $fields->addFieldsToTab('Root.Main', [
101
            $marker = \UploadField::create('GlobalMarker', _t('MapBlock.Marker', 'Marker')),
102
            GoogleMapField::create(
103
                'GoogleMap',
104
                $this,
105
                $this->Markers(),
0 ignored issues
show
Bug introduced by
The method Markers() does not exist on MapBlock. Did you maybe mean getMarkersAsJson()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
106
                [
107
                    'api' => \SiteConfig::current_site_config()->GoogleMapsApiKey,
108
                    'map' => array_merge(
109
                        [
110
                            'zoom' => (int) $this->ZoomLevel,
111
                        ],
112
                        $coordinates
113
                    ),
114
                ]
115
            ),
116
        ], 'Content');
117
118
        $marker
119
            ->setRightTitle(_t('MapBlock.MARKER_RIGHT_TITLE', 'Set a global marker image'))
120
            ->setAllowedFileCategories('image')
121
            ->setAllowedMaxFileNumber(1)
122
            ->setFolderName('Uploads/Blocks/Markers');
123
124
        $fields->removeByName(['Content']);
125
126
        $this->extend('updateCMSFields', $fields);
127
128
        return $fields;
129
    }
130
131
    /**
132
     * @return \HTMLText
133
     */
134
    public function forTemplate() {
135
        if (static::config()->load_javascript) {
136
            \Requirements::javascript(CONTENT_BLOCKS_DIR.'/assets/javascript/maps-frontend.js');
137
        }
138
139
        return parent::forTemplate();
140
    }
141
142
    /**
143
     * @return bool|string
144
     */
145
    public function getMarkersAsJson() {
146
        if (count($markers = $this->Markers())) {
0 ignored issues
show
Bug introduced by
The method Markers() does not exist on MapBlock. Did you maybe mean getMarkersAsJson()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
147
            $list = [];
148
149
            /** @var Marker $marker */
150
            foreach ($markers as $marker) {
151
                $markerImage = [];
152
153
                if ($marker->Marker()->exists()) {
154
                    $markerImage = ['icon' => $marker->Marker()->getAbsoluteURL()];
155
                }
156
157
                $markerAsArray = $marker->toMap();
158
159
                $list[] = array_merge([
160
                    'instanceId'    => isset($markerAsArray['InstanceId']) ? $markerAsArray['InstanceId'] : '',
161
                    'address'       => isset($markerAsArray['Address']) ? $markerAsArray['Address'] : '',
162
                    'coordinates'   => isset($markerAsArray['Coordinates']) ? $markerAsArray['Coordinates'] : '',
163
                    'content'       => isset($markerAsArray['Content']) ? $markerAsArray['Content'] : '',
164
                    'displayWindow' => (bool) (isset($markerAsArray['DisplayWindow']) ? $markerAsArray['DisplayWindow'] : false),
165
                ], $markerImage);
166
            }
167
168
            return \Convert::raw2att(\Convert::array2json($list));
169
        }
170
171
        return false;
172
    }
173
174
    /**
175
     * @return bool|string
176
     */
177
    public function getOptionsAsJson() {
178
        $data = [];
179
180
        if (count($coordinates = $this->getCoordinatesAsOption())) {
181
            $data['map'] = $coordinates;
182
        }
183
184
        if (! empty($this->ZoomLevel)) {
185
            if (! isset($data['map'])) {
186
                $data['map'] = [];
187
            }
188
189
            $data['map']['zoom'] = (int) $this->ZoomLevel;
190
        }
191
192
        if ($this->GlobalMarker()->exists()) {
0 ignored issues
show
Documentation Bug introduced by
The method GlobalMarker does not exist on object<MapBlock>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
193
            $data['globalMarkerIcon'] = $this->GlobalMarker()->getAbsoluteURL();
0 ignored issues
show
Documentation Bug introduced by
The method GlobalMarker does not exist on object<MapBlock>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
194
        }
195
196
        $styles = static::config()->map_styles;
197
198
        if (! empty($styles)) {
199
            if (! isset($data['map'])) {
200
                $data['map'] = [];
201
            }
202
203
            $data['map']['styles'] = (string) $styles;
204
        }
205
206 View Code Duplication
        foreach ($data as $key => $value) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
207
            if (is_array($value)) {
208
                $data[$key] = json_decode(json_encode((object) $value), false);
209
            }
210
        }
211
212
        if (count($data)) {
213
            return \Convert::raw2att(\Convert::array2json($data));
214
        }
215
216
        return false;
217
    }
218
219
}