Completed
Pull Request — master (#18)
by Matthew
08:44
created

LocatorControllerExtension::setFormSchema()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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

80
        /** @scrutinizer ignore-deprecated */ Requirements::add_i18n_javascript('dynamic/silverstripe-locator-react: client/lang');
Loading history...
81
82
        // because we need another library when using autocomplete
83 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...
84
            // google maps api key
85 1
            $key = Config::inst()->get(GoogleGeocoder::class, 'map_api_key');
86 1
            Requirements::block("https://maps.google.com/maps/api/js?key={$key}");
87 1
            Requirements::javascript("https://maps.google.com/maps/api/js?key={$key}&libraries=places");
88
        }
89
90 1
        Requirements::customScript("
91
            window.ss = window.ss || {};
92 1
            window.ss.config = " . $this->owner->getClientConfig() . ";
93
        ");
94
95 1
        $this->owner->customScript();
96
    }
97
98
    /**
99
     * Generates the custom script for settings
100
     */
101 2
    public function customScript()
102
    {
103 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

103
        $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

103
        $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...
104 2
        $radiiString = json_encode($radii);
105
106 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

106
        /** @scrutinizer ignore-call */ 
107
        $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...
107 2
        $categoriesString = $this->owner->categoriesString($categories);
108
109 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...
110
        // otherwise this is 0 or 1
111 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...
112 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...
113
114 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

114
        $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...
115 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

115
        $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...
116
117
        // force to float
118 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...
119 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...
120
121 2
        Requirements::customScript("
122
            window.dynamic_locator = {
123 2
                'radii': {$radiiString},
124 2
                'categories': {$categoriesString},
125 2
                'unit': '{$unit}',
126 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

126
                '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...
127 2
                'clusters': {$clusters},
128 2
                'mapStylePath': '{$stylePath}',
129 2
                'markerImagePath': '{$markerIconPath}',
130
                'defaultCenter': {
131 2
                    'lat': {$defaultLat},
132 2
                    'lng': {$defaultLng}
133
                },
134 2
                'autocomplete': {$autocomplete}
135
            };
136 2
        ", 'react-locator');
137
    }
138
139
    /**
140
     * @param $categories
141
     *
142
     * @return string
143
     */
144 3
    public function categoriesString($categories)
145
    {
146 3
        $string = '[';
147 3
        for ($i = 0; $i < $categories->count(); $i++) {
148 1
            $cat = $categories[$i];
149 1
            $ID = $cat->ID;
150 1
            $Name = $cat->Name;
151
            $string .= "{
152 1
                'ID': {$ID},
153 1
                'Name': '{$Name}'
154
            }";
155
156 1
            if ($i !== $categories->count() - 1) {
157 1
                $string .= ',';
158
            }
159
        }
160 3
        $string .= ']';
161
162 3
        return $string;
163
    }
164
165
    /**
166
     * @return string
167
     */
168 1
    public function getClientConfig()
169
    {
170 1
        $token = SecurityToken::inst();
171
172
        $clientConfig = [
173 1
            'name' => get_class($this->owner),
174 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

174
            '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...
175 1
            'baseUrl' => Director::baseURL(),
176 1
            'absoluteBaseUrl' => Director::absoluteBaseURL(),
177 1
            $token->getName() => $token->getValue(),
178
            'sections' => [],
179 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

179
            '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...
180
        ];
181
182 1
        $clientConfig['sections'][] = Injector::inst()->get(LeftAndMain::class)->getClientConfig();
183
184 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

184
        $this->owner->/** @scrutinizer ignore-call */ 
185
                      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...
185
186 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

186
        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...
187
    }
188
189
    /**
190
     * Gets a JSON schema representing the search form.
191
     *
192
     * @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...
193
     * @return HTTPResponse
194
     */
195
    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

195
    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...
196
    {
197
        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

197
        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...
198
    }
199
200
    /**
201
     * Check if the current request has a X-Formschema-Request header set.
202
     * Used by conditional logic that responds to validation results
203
     *
204
     * @return bool
205
     */
206
    protected function getSchemaRequested()
207
    {
208
        $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

208
        $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...
209
        return !empty($parts);
210
    }
211
212
    /**
213
     * Generate schema for the given form based on the X-Formschema-Request header value
214
     *
215
     * @param string $schemaID ID for this schema. Required.
216
     * @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...
217
     * @param ValidationResult $errors Required for 'error' response
218
     * @param array $extraData Any extra data to be merged with the schema response
219
     * @return HTTPResponse
220
     */
221
    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...
222
    {
223
        $parts = $this->owner->getRequest()->getHeader(LeftAndMain::SCHEMA_HEADER);
224
        $data = $this
225
            ->getFormSchema()
226
            ->getMultipartSchema($parts, $schemaID, $form, $errors);
227
228
        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...
229
            $data = array_merge($data, $extraData);
230
        }
231
232
        $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

232
        $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...
233
        $response->addHeader('Content-Type', 'application/json');
234
        return $response;
235
    }
236
}
237