Passed
Push — master ( 26a67b...aa1885 )
by Thomas
21:40 queued 19:19
created

BuildTaskTools::getRequest()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace LeKoala\Multilingual;
4
5
use SilverStripe\ORM\ArrayLib;
6
use SilverStripe\Core\ClassInfo;
7
use SilverStripe\ORM\DataObject;
8
use SilverStripe\Control\Director;
9
use SilverStripe\Core\Environment;
10
use SilverStripe\Control\HTTPRequest;
11
use SilverStripe\Core\Manifest\ClassLoader;
12
use SilverStripe\Core\Manifest\ModuleLoader;
13
14
/**
15
 * Makes your life easier with build tasks
16
 * TODO: make this into a separate module
17
 */
18
trait BuildTaskTools
19
{
20
    /**
21
     * @var \SilverStripe\Control\HTTPRequest
22
     */
23
    protected $request;
24
25
    /**
26
     * @var array<string,array<mixed>>
27
     */
28
    protected $options = [];
29
30
    /**
31
     * Increase time limit
32
     *
33
     * @return void
34
     */
35
    protected function increaseTimeLimitTo($timeLimit = null)
36
    {
37
        Environment::increaseTimeLimitTo($timeLimit);
38
        if (!$timeLimit) {
39
            $this->message("Time limit is disabled", "info");
40
        } else {
41
            $this->message("Time limit has been set to $timeLimit seconds", "info");
42
        }
43
    }
44
45
    /**
46
     * Rebuild the class manifest
47
     *
48
     * @return void
49
     */
50
    protected function regenerateClassManifest()
51
    {
52
        ClassLoader::inst()->getManifest()->regenerate(false);
53
        $this->message("The class manifest has been rebuilt", "created");
54
    }
55
56
    /**
57
     * All dataobjects
58
     *
59
     * @return array
60
     */
61
    protected function getValidDataObjects()
62
    {
63
        $list = ClassInfo::getValidSubClasses(DataObject::class);
64
        array_shift($list);
65
        return $list;
66
    }
67
68
    /**
69
     * All modules
70
     *
71
     * @return array
72
     */
73
    protected function getModules()
74
    {
75
        return ArrayLib::valuekey(array_keys(ModuleLoader::inst()->getManifest()->getModules()));
76
    }
77
78
    /**
79
     * Get the request (and keep your imports clean :-) )
80
     *
81
     * @return HTTPRequest
82
     */
83
    protected function getRequest()
84
    {
85
        if (!$this->request) {
86
            die('Make sure to call $this->request = $request in your own class');
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...
87
        }
88
        return $this->request;
89
    }
90
91
    /**
92
     * Add options (to be called later with askOptions)
93
     *
94
     * @param string $key
95
     * @param string $title
96
     * @param mixed $default Default value. Input type will be based on this (bool => checkbox, etc)
97
     * @param array|Map $list An array of value for a dropdown
0 ignored issues
show
Bug introduced by
The type LeKoala\Multilingual\Map 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...
98
     * @return void
99
     */
100
    protected function addOption($key, $title, $default = '', $list = null)
101
    {
102
        // Handle maps
103
        if (is_object($list) && method_exists($list, 'toArray')) {
104
            $list = $list->toArray();
105
        }
106
        $opt = [
107
            'key' => $key,
108
            'title' => $title,
109
            'default' => $default,
110
            'list' => $list,
111
        ];
112
        $this->options[] = $opt;
113
114
        return $opt;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $opt returns the type array<string,mixed|string> which is incompatible with the documented return type void.
Loading history...
115
    }
116
117
    /**
118
     * Display a form with options
119
     *
120
     * Options are added through addOption method
121
     *
122
     * @return array Array with key => value corresponding to options asked
123
     */
124
    protected function askOptions()
125
    {
126
        $values = [];
127
        $request = $this->getRequest();
128
        echo '<form action="" method="post"><fieldset>';
129
        foreach ($this->options as $opt) {
130
            $val = $request->requestVar($opt['key']);
131
            if ($val === null) {
132
                $val = $opt['default'];
133
            }
134
135
            $values[$opt['key']] = $val;
136
137
            if ($opt['list']) {
138
                $input = '<select name="' . $opt['key'] . '">';
139
                $input .= '<option></option>';
140
                foreach ($opt['list'] as $k => $v) {
141
                    $selected = '';
142
                    if ($k == $val) {
143
                        $selected = ' selected="selected"';
144
                    }
145
                    $input .= '<option value="' . $k . '"' . $selected . '>' . $v . '</option>';
146
                }
147
                $input .= '</select>';
148
            } else {
149
                $type = 'text';
150
                $input = null;
151
                if (isset($opt['default'])) {
152
                    if (is_bool($opt['default'])) {
153
                        $type = 'checkbox';
154
                        $checked = $val ? ' checked="checked"' : '';
155
                        $input = '<input type="hidden" name="' . $opt['key'] . '" value="0" />';
156
                        $input .= '<input type="' . $type . '" name="' . $opt['key'] . '" value="1"' . $checked . ' />';
157
                    } else {
158
                        if (is_int($opt['default'])) {
159
                            $type = 'numeric';
160
                        }
161
                    }
162
                }
163
                if (!$input) {
164
                    $input = '<input type="' . $type . '" name="' . $opt['key'] . '" value="' . $val . '" />';
165
                }
166
            }
167
            echo '<div class="field">';
168
            echo '<label> ' . $opt['title'] . ' ' . $input . '</label>';
169
            echo '</div>';
170
            echo '<br/>';
171
        }
172
        echo '</fieldset><br/><input type="submit" />';
173
        echo '</form>';
174
        echo '<hr/ >';
175
        return $values;
176
    }
177
178
    protected function message($message, $type = 'default')
179
    {
180
        if (Director::is_cli()) {
181
            $cli_map = [
182
                'repaired' => '>',
183
                'success' => '✓',
184
                'created' => '+',
185
                'changed' => '+',
186
                'bad' => '-',
187
                'obsolete' => '-',
188
                'deleted' => '-',
189
                'notice' => '!',
190
                'error' => '-',
191
            ];
192
193
            $message = strip_tags($message);
194
            if (isset($cli_map[$type])) {
195
                $message = $cli_map[$type] . ' ' . $message;
196
            }
197
            if (!is_string($message)) {
0 ignored issues
show
introduced by
The condition is_string($message) is always true.
Loading history...
198
                $message = json_encode($message);
199
            }
200
            echo "  $message\n";
201
        } else {
202
            $web_map = [
203
                'info' => 'blue',
204
                'repaired' => 'blue',
205
                'success' => 'green',
206
                'created' => 'green',
207
                'changed' => 'green',
208
                'obsolete' => 'red',
209
                'notice' => 'orange',
210
                'deleted' => 'red',
211
                'bad' => 'red',
212
                'error' => 'red',
213
            ];
214
            $color = '#000000';
215
            if (isset($web_map[$type])) {
216
                $color = $web_map[$type];
217
            }
218
            if (!is_string($message)) {
219
                $message = print_r($message, true);
220
                echo "<pre style=\"color:$color\">$message</pre>";
221
            } else {
222
                echo "<div style=\"color:$color\">$message</div>";
223
            }
224
        }
225
    }
226
227
    protected function isDev()
228
    {
229
        return Director::isDev();
230
    }
231
232
    protected function isLive()
233
    {
234
        return Director::isLive();
235
    }
236
}
237