Completed
Pull Request — master (#18)
by Matthew
10:25
created

LocatorControllerExtension::getSchemaResponse()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 2
eloc 9
c 2
b 0
f 0
nc 2
nop 4
dl 0
loc 14
ccs 0
cts 9
cp 0
crap 6
rs 9.9666
1
<?php
2
3
namespace Dynamic\Locator\React\Extensions;
4
5
use Dynamic\SilverStripeGeocoder\GoogleGeocoder;
6
use SilverStripe\Admin\LeftAndMain;
7
use SilverStripe\Control\Director;
8
use SilverStripe\Control\HTTPResponse;
9
use SilverStripe\Core\Config\Config;
10
use SilverStripe\Core\Convert;
11
use SilverStripe\Core\Extension;
12
use SilverStripe\Core\Manifest\ModuleResourceLoader;
13
use SilverStripe\Forms\Schema\FormSchema;
14
use SilverStripe\Security\SecurityToken;
15
use SilverStripe\View\Requirements;
16
17
/**
18
 * Class LocatorControllerExtension
19
 * @package Dynamic\Locator\React\Extensions
20
 *
21
 * @property \Dynamic\Locator\LocatorController|\Dynamic\Locator\React\Extensions\LocatorControllerExtension $owner
22
 */
23
class LocatorControllerExtension extends Extension
24
{
25
26
    /**
27
     * @var array
28
     */
29
    private static $allowed_actions = [
0 ignored issues
show
introduced by
The private property $allowed_actions is not used, and could be removed.
Loading history...
30
        'schema',
31
    ];
32
33
    /**
34
     * @var array
35
     */
36
    private static $dependencies = [
0 ignored issues
show
introduced by
The private property $dependencies is not used, and could be removed.
Loading history...
37
        'FormSchema' => '%$' . FormSchema::class,
38
    ];
39
40
    /**
41
     * Current form schema helper
42
     *
43
     * @var FormSchema
44
     */
45
    protected $schema = null;
46
47
    /**
48
     * Get form schema helper
49
     *
50
     * @return FormSchema
51
     */
52 3
    public function getFormSchema()
53
    {
54 3
        return $this->schema;
55
    }
56
57
    /**
58
     * Set form schema helper for this controller
59
     *
60
     * @param FormSchema $schema
61
     * @return $this
62
     */
63 3
    public function setFormSchema(FormSchema $schema)
64
    {
65 3
        $this->schema = $schema;
66 3
        return $this;
67
    }
68
69
    /**
70
     *
71
     */
72 1
    public function onBeforeInit()
73
    {
74
        // stops script from loading
75 1
        Requirements::block('jquery-locator');
76
77
        // require i18n translation stuff
78 1
        Requirements::javascript('silverstripe/admin: client/dist/js/i18n.js');
79 1
        Requirements::add_i18n_javascript('dynamic/silverstripe-locator-react: client/lang');
0 ignored issues
show
Deprecated Code introduced by
The function SilverStripe\View\Requir...::add_i18n_javascript() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

79
        /** @scrutinizer ignore-deprecated */ Requirements::add_i18n_javascript('dynamic/silverstripe-locator-react: client/lang');
Loading history...
80
81
        // because we need another library when using autocomplete
82 1
        if ($this->owner->Autocomplete) {
0 ignored issues
show
Bug Best Practice introduced by
The property Autocomplete does not exist on Dynamic\Locator\React\Ex...atorControllerExtension. Did you maybe forget to declare it?
Loading history...
83
            // google maps api key
84 1
            $key = Config::inst()->get(GoogleGeocoder::class, 'map_api_key');
85 1
            Requirements::block("https://maps.google.com/maps/api/js?key={$key}");
86 1
            Requirements::javascript("https://maps.google.com/maps/api/js?key={$key}&libraries=places");
87
        }
88
89 1
        Requirements::customScript("
90
            window.ss = window.ss || {};
91 1
            window.ss.config = " . $this->owner->getClientConfig() . ";
92
        ");
93
94 1
        $this->owner->customScript();
95
    }
96
97
    /**
98
     * Generates the custom script for settings
99
     */
100 2
    public function customScript()
101
    {
102 2
        $radii = $this->owner->getShowRadius() ? $this->owner->getRadii() : [];
0 ignored issues
show
Bug introduced by
The method getRadii() does not exist on Dynamic\Locator\React\Ex...atorControllerExtension. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

102
        $radii = $this->owner->getShowRadius() ? $this->owner->/** @scrutinizer ignore-call */ getRadii() : [];

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
Bug introduced by
The method getShowRadius() does not exist on Dynamic\Locator\React\Ex...atorControllerExtension. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

102
        $radii = $this->owner->/** @scrutinizer ignore-call */ getShowRadius() ? $this->owner->getRadii() : [];

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
103 2
        $radiiString = json_encode($radii);
104
105 2
        $categories = $this->owner->getUsedCategories();
0 ignored issues
show
Bug introduced by
The method getUsedCategories() does not exist on Dynamic\Locator\React\Ex...atorControllerExtension. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

105
        /** @scrutinizer ignore-call */ 
106
        $categories = $this->owner->getUsedCategories();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
106 2
        $categoriesString = $this->owner->categoriesString($categories);
107
108 2
        $unit = $this->owner->Unit ? $this->owner->Unit : 'm';
0 ignored issues
show
Bug Best Practice introduced by
The property Unit does not exist on Dynamic\Locator\React\Ex...atorControllerExtension. Did you maybe forget to declare it?
Loading history...
109
        // otherwise this is 0 or 1
110 2
        $clusters = $this->owner->Clusters ? 'true' : 'false';
0 ignored issues
show
Bug Best Practice introduced by
The property Clusters does not exist on Dynamic\Locator\React\Ex...atorControllerExtension. Did you maybe forget to declare it?
Loading history...
111 2
        $autocomplete = $this->owner->Autocomplete ? 'true' : 'false';
0 ignored issues
show
Bug Best Practice introduced by
The property Autocomplete does not exist on Dynamic\Locator\React\Ex...atorControllerExtension. Did you maybe forget to declare it?
Loading history...
112
113 2
        $stylePath = ModuleResourceLoader::singleton()->resolveURL($this->owner->getMapStyle());
0 ignored issues
show
Bug introduced by
The method getMapStyle() does not exist on Dynamic\Locator\React\Ex...atorControllerExtension. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

113
        $stylePath = ModuleResourceLoader::singleton()->resolveURL($this->owner->/** @scrutinizer ignore-call */ getMapStyle());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
114 2
        $markerIconPath = ModuleResourceLoader::singleton()->resolveURL($this->owner->getMarkerIcon());
0 ignored issues
show
Bug introduced by
The method getMarkerIcon() does not exist on Dynamic\Locator\React\Ex...atorControllerExtension. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

114
        $markerIconPath = ModuleResourceLoader::singleton()->resolveURL($this->owner->/** @scrutinizer ignore-call */ getMarkerIcon());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
115
116
        // force to float
117 2
        $defaultLat = (float) $this->owner->DefaultLat;
0 ignored issues
show
Bug Best Practice introduced by
The property DefaultLat does not exist on Dynamic\Locator\React\Ex...atorControllerExtension. Did you maybe forget to declare it?
Loading history...
118 2
        $defaultLng = (float) $this->owner->DefaultLng;
0 ignored issues
show
Bug Best Practice introduced by
The property DefaultLng does not exist on Dynamic\Locator\React\Ex...atorControllerExtension. Did you maybe forget to declare it?
Loading history...
119
120 2
        Requirements::customScript("
121
            window.dynamic_locator = {
122 2
                'radii': {$radiiString},
123 2
                'categories': {$categoriesString},
124 2
                'unit': '{$unit}',
125 2
                'limit': {$this->owner->getLimit()},
0 ignored issues
show
Bug introduced by
The method getLimit() does not exist on Dynamic\Locator\React\Ex...atorControllerExtension. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

125
                'limit': {$this->owner->/** @scrutinizer ignore-call */ getLimit()},

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
126 2
                'clusters': {$clusters},
127 2
                'mapStylePath': '{$stylePath}',
128 2
                'markerImagePath': '{$markerIconPath}',
129
                'defaultCenter': {
130 2
                    'lat': {$defaultLat},
131 2
                    'lng': {$defaultLng}
132
                },
133 2
                'autocomplete': {$autocomplete}
134
            };
135 2
        ", 'react-locator');
136
    }
137
138
    /**
139
     * @param $categories
140
     *
141
     * @return string
142
     */
143 3
    public function categoriesString($categories)
144
    {
145 3
        $string = '[';
146 3
        for ($i = 0; $i < $categories->count(); $i++) {
147 1
            $cat = $categories[$i];
148 1
            $ID = $cat->ID;
149 1
            $Name = $cat->Name;
150
            $string .= "{
151 1
                'ID': {$ID},
152 1
                'Name': '{$Name}'
153
            }";
154
155 1
            if ($i !== $categories->count() - 1) {
156 1
                $string .= ',';
157
            }
158
        }
159 3
        $string .= ']';
160
161 3
        return $string;
162
    }
163
164
    /**
165
     * @return string
166
     */
167 1
    public function getClientConfig()
168
    {
169 1
        $token = SecurityToken::inst();
170
171
        $clientConfig = [
172 1
            'name' => get_class($this->owner),
173 1
            'url' => trim($this->owner->Link(), '/'),
0 ignored issues
show
Bug introduced by
The method Link() does not exist on Dynamic\Locator\React\Ex...atorControllerExtension. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

173
            'url' => trim($this->owner->/** @scrutinizer ignore-call */ Link(), '/'),

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
174 1
            'baseUrl' => Director::baseURL(),
175 1
            'absoluteBaseUrl' => Director::absoluteBaseURL(),
176 1
            $token->getName() => $token->getValue(),
177
            'sections' => [
178
                [
179
                    'name'=> '',
180
                    'url' => '',
181
                ],
182
            ],
183 1
            'debugging' => $this->owner->config()->get('debugging'),
0 ignored issues
show
Bug introduced by
The method config() does not exist on Dynamic\Locator\React\Ex...atorControllerExtension. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

183
            'debugging' => $this->owner->/** @scrutinizer ignore-call */ config()->get('debugging'),

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
184
        ];
185 1
        $this->owner->extend('updateClientConfig', $clientConfig);
0 ignored issues
show
Bug introduced by
The method extend() does not exist on Dynamic\Locator\React\Ex...atorControllerExtension. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

185
        $this->owner->/** @scrutinizer ignore-call */ 
186
                      extend('updateClientConfig', $clientConfig);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
186
187 1
        return Convert::raw2json($clientConfig);
0 ignored issues
show
Deprecated Code introduced by
The function SilverStripe\Core\Convert::raw2json() has been deprecated: 4.4.0:5.0.0 Use json_encode() instead ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

187
        return /** @scrutinizer ignore-deprecated */ Convert::raw2json($clientConfig);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
188
    }
189
190
    /**
191
     * Gets a JSON schema representing the search form.
192
     *
193
     * @param HTTPRequest $request
0 ignored issues
show
Bug introduced by
The type Dynamic\Locator\React\Extensions\HTTPRequest was not found. Did you mean HTTPRequest? If so, make sure to prefix the type with \.
Loading history...
194
     * @return HTTPResponse
195
     */
196
    public function schema($request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

196
    public function schema(/** @scrutinizer ignore-unused */ $request)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
197
    {
198
        return $this->getSchemaResponse("Locator.SearchForm", $this->owner->LocationSearch());
0 ignored issues
show
Bug introduced by
The method LocationSearch() does not exist on Dynamic\Locator\React\Ex...atorControllerExtension. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

198
        return $this->getSchemaResponse("Locator.SearchForm", $this->owner->/** @scrutinizer ignore-call */ LocationSearch());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
199
    }
200
201
    /**
202
     * Check if the current request has a X-Formschema-Request header set.
203
     * Used by conditional logic that responds to validation results
204
     *
205
     * @return bool
206
     */
207
    protected function getSchemaRequested()
208
    {
209
        $parts = $this->owner->getRequest()->getHeader(LeftAndMain::SCHEMA_HEADER);
0 ignored issues
show
Bug introduced by
The method getRequest() does not exist on Dynamic\Locator\React\Ex...atorControllerExtension. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

209
        $parts = $this->owner->/** @scrutinizer ignore-call */ getRequest()->getHeader(LeftAndMain::SCHEMA_HEADER);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
210
        return !empty($parts);
211
    }
212
213
    /**
214
     * Generate schema for the given form based on the X-Formschema-Request header value
215
     *
216
     * @param string $schemaID ID for this schema. Required.
217
     * @param Form $form Required for 'state' or 'schema' response
0 ignored issues
show
Bug introduced by
The type Dynamic\Locator\React\Extensions\Form was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
218
     * @param ValidationResult $errors Required for 'error' response
219
     * @param array $extraData Any extra data to be merged with the schema response
220
     * @return HTTPResponse
221
     */
222
    protected function getSchemaResponse($schemaID, $form = null, ValidationResult $errors = null, $extraData = [])
0 ignored issues
show
Bug introduced by
The type Dynamic\Locator\React\Extensions\ValidationResult was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
223
    {
224
        $parts = $this->owner->getRequest()->getHeader(LeftAndMain::SCHEMA_HEADER);
225
        $data = $this
226
            ->getFormSchema()
227
            ->getMultipartSchema($parts, $schemaID, $form, $errors);
228
229
        if ($extraData) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $extraData of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
230
            $data = array_merge($data, $extraData);
231
        }
232
233
        $response = new HTTPResponse(Convert::raw2json($data));
0 ignored issues
show
Deprecated Code introduced by
The function SilverStripe\Core\Convert::raw2json() has been deprecated: 4.4.0:5.0.0 Use json_encode() instead ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

233
        $response = new HTTPResponse(/** @scrutinizer ignore-deprecated */ Convert::raw2json($data));

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
234
        $response->addHeader('Content-Type', 'application/json');
235
        return $response;
236
    }
237
}
238