Completed
Push — master ( 4cc8d8...e56a52 )
by Arjay
04:43
created

Helper::replacePatternWithKeyword()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 13
rs 9.4286
cc 3
eloc 8
nc 3
nop 3
1
<?php
2
3
namespace Yajra\Datatables;
4
5
use DateTime;
6
use Illuminate\Contracts\Support\Arrayable;
7
use Illuminate\Filesystem\Filesystem;
8
use Illuminate\Support\Str;
9
use Illuminate\View\Compilers\BladeCompiler;
10
11
class Helper
12
{
13
    /**
14
     * Places item of extra columns into results by care of their order.
15
     *
16
     * @param  $item
17
     * @param  $array
18
     * @return array
19
     */
20
    public static function includeInArray($item, $array)
21
    {
22
        if ($item['order'] === false) {
23
            return array_merge($array, [$item['name'] => $item['content']]);
24
        } else {
25
            $count = 0;
26
            $last  = $array;
27
            $first = [];
28
            foreach ($array as $key => $value) {
29
                if ($count == $item['order']) {
30
                    return array_merge($first, [$item['name'] => $item['content']], $last);
31
                }
32
33
                unset($last[$key]);
34
                $first[$key] = $value;
35
36
                $count++;
37
            }
38
        }
39
    }
40
41
    /**
42
     * Determines if content is callable or blade string, processes and returns.
43
     *
44
     * @param string|callable $content Pre-processed content
45
     * @param array $data data to use with blade template
46
     * @param mixed $param parameter to call with callable
47
     * @return string Processed content
48
     */
49
    public static function compileContent($content, array $data, $param)
50
    {
51
        if (is_string($content)) {
52
            return static::compileBlade($content, static::getMixedValue($data, $param));
53
        } elseif (is_callable($content)) {
54
            return $content($param);
55
        }
56
57
        return $content;
58
    }
59
60
    /**
61
     * Parses and compiles strings by using Blade Template System.
62
     *
63
     * @param string $str
64
     * @param array $data
65
     * @return string
66
     * @throws \Exception
67
     */
68
    public static function compileBlade($str, $data = [])
69
    {
70
        if (view()->exists($str)) {
71
            return view($str, $data)->render();
72
        }
73
74
        $empty_filesystem_instance = new Filesystem();
75
        $blade                     = new BladeCompiler($empty_filesystem_instance, 'datatables');
76
        $parsed_string             = $blade->compileString($str);
77
78
        ob_start() && extract($data, EXTR_SKIP);
79
80
        try {
81
            eval('?>' . $parsed_string);
0 ignored issues
show
Coding Style introduced by
It is generally not recommended to use eval unless absolutely required.

On one hand, eval might be exploited by malicious users if they somehow manage to inject dynamic content. On the other hand, with the emergence of faster PHP runtimes like the HHVM, eval prevents some optimization that they perform.

Loading history...
82
        } catch (\Exception $e) {
0 ignored issues
show
Unused Code introduced by
catch (\Exception $e) { ...lean(); throw $e; } does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
83
            ob_end_clean();
84
            throw $e;
85
        }
86
87
        $str = ob_get_contents();
88
        ob_end_clean();
89
90
        return $str;
91
    }
92
93
    /**
94
     * @param  array $data
95
     * @param  mixed $param
96
     * @return array
97
     */
98
    public static function getMixedValue(array $data, $param)
99
    {
100
        $param = self::castToArray($param);
101
102
        foreach ($data as $key => $value) {
103
            if (isset($param[$key])) {
104
                $data[$key] = $param[$key];
105
            }
106
        }
107
108
        return $data;
109
    }
110
111
    /**
112
     * @param $param
113
     * @return array
114
     */
115
    public static function castToArray($param)
116
    {
117
        if ($param instanceof \stdClass) {
118
            $param = (array) $param;
119
120
            return $param;
121
        }
122
123
        return $param;
124
    }
125
126
    /**
127
     * Get equivalent or method of query builder.
128
     *
129
     * @param string $method
130
     * @return string
131
     */
132
    public static function getOrMethod($method)
133
    {
134
        if (! Str::contains(Str::lower($method), 'or')) {
135
            return 'or' . ucfirst($method);
136
        }
137
138
        return $method;
139
    }
140
141
    /**
142
     * Wrap value depending on database type.
143
     *
144
     * @param string $database
145
     * @param string $value
146
     * @return string
147
     */
148
    public static function wrapDatabaseValue($database, $value)
149
    {
150
        $parts  = explode('.', $value);
151
        $column = '';
152
        foreach ($parts as $key) {
153
            $column = static::wrapDatabaseColumn($database, $key, $column);
154
        }
155
156
        return substr($column, 0, strlen($column) - 1);
157
    }
158
159
    /**
160
     * Database column wrapper
161
     *
162
     * @param string $database
163
     * @param string $key
164
     * @param string $column
165
     * @return string
166
     */
167
    public static function wrapDatabaseColumn($database, $key, $column)
168
    {
169
        switch ($database) {
170
            case 'mysql':
171
                $column .= '`' . str_replace('`', '``', $key) . '`' . '.';
172
                break;
173
174
            case 'sqlsrv':
175
                $column .= '[' . str_replace(']', ']]', $key) . ']' . '.';
176
                break;
177
178
            case 'pgsql':
179
            case 'sqlite':
180
                $column .= '"' . str_replace('"', '""', $key) . '"' . '.';
181
                break;
182
183
            default:
184
                $column .= $key . '.';
185
        }
186
187
        return $column;
188
    }
189
190
    /**
191
     * Converts array object values to associative array.
192
     *
193
     * @param mixed $row
194
     * @return array
195
     */
196
    public static function convertToArray($row)
197
    {
198
        $data = $row instanceof Arrayable ? $row->toArray() : (array) $row;
199
        foreach (array_keys($data) as $key) {
200
            if (is_object($data[$key]) || is_array($data[$key])) {
201
                $data[$key] = self::convertToArray($data[$key]);
202
            }
203
        }
204
205
        return $data;
206
    }
207
208
    /**
209
     * @param array $data
210
     * @return array
211
     */
212
    public static function transform(array $data)
213
    {
214
        return array_map(function ($row) {
215
            return self::transformRow($row);
216
        }, $data);
217
    }
218
219
    /**
220
     * @param $row
221
     * @return mixed
222
     */
223
    protected static function transformRow($row)
224
    {
225
        foreach ($row as $key => $value) {
226
            if ($value instanceof DateTime) {
227
                $row[$key] = $value->format('Y-m-d H:i:s');
228
            } else {
229
                if (is_string($value)) {
230
                    $row[$key] = (string) $value;
231
                } else {
232
                    $row[$key] = $value;
233
                }
234
            }
235
        }
236
237
        return $row;
238
    }
239
240
    /**
241
     * Build parameters depending on # of arguments passed.
242
     *
243
     * @param array $args
244
     * @return array
245
     */
246
    public static function buildParameters(array $args)
247
    {
248
        $parameters = [];
249
250
        if (count($args) > 2) {
251
            $parameters[] = $args[0];
252
            foreach ($args[1] as $param) {
253
                $parameters[] = $param;
254
            }
255
        } else {
256
            foreach ($args[0] as $param) {
257
                $parameters[] = $param;
258
            }
259
        }
260
261
        return $parameters;
262
    }
263
264
    /**
265
     * Replace all pattern occurrences with keyword
266
     *
267
     * @param array $subject
268
     * @param string $keyword
269
     * @param string $pattern
270
     * @return array
271
     */
272
    public static function replacePatternWithKeyword(array $subject, $keyword, $pattern = '$1')
273
    {
274
        $parameters = [];
275
        foreach ($subject as $param) {
276
            if (is_array($param)) {
277
                $parameters[] = self::replacePatternWithKeyword($param, $keyword, $pattern);
278
            } else {
279
                $parameters[] = str_replace($pattern, $keyword, $param);
280
            }
281
        }
282
283
        return $parameters;
284
    }
285
}
286