Completed
Push — master ( b23c0f...43ea5a )
by Arman
24s queued 18s
created

markdown_to_html()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 9
nc 4
nop 2
dl 0
loc 17
rs 9.9666
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Quantum PHP Framework
5
 *
6
 * An open source software development framework for PHP
7
 *
8
 * @package Quantum
9
 * @author Arman Ag. <[email protected]>
10
 * @copyright Copyright (c) 2018 Softberg LLC (https://softberg.org)
11
 * @link http://quantum.softberg.org/
12
 * @since 2.9.6
13
 */
14
15
use Symfony\Component\VarExporter\Exception\ExceptionInterface;
16
use Quantum\Libraries\Config\Exceptions\ConfigException;
17
use Quantum\Libraries\Database\Contracts\DbalInterface;
18
use Quantum\Renderer\Exceptions\RendererException;
19
use Quantum\Exceptions\StopExecutionException;
20
use Symfony\Component\VarExporter\VarExporter;
21
use League\CommonMark\CommonMarkConverter;
0 ignored issues
show
Bug introduced by
The type League\CommonMark\CommonMarkConverter 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...
22
use Quantum\Di\Exceptions\DiException;
23
use Quantum\Exceptions\BaseException;
24
use Quantum\Model\QtModel;
25
use Quantum\Http\Response;
26
27
/**
28
 * Compose a message
29
 * @param string $subject
30
 * @param string|array $params
31
 * @return string
32
 */
33
function _message(string $subject, $params): string
34
{
35
    if (is_array($params)) {
36
        return preg_replace_callback('/{%\d+}/', function () use (&$params) {
37
            return array_shift($params);
38
        }, $subject);
39
    } else {
40
        return preg_replace('/{%\d+}/', $params, $subject);
41
    }
42
}
43
44
/**
45
 * Validates base64 string
46
 * @param string $string
47
 * @return boolean
48
 */
49
function valid_base64(string $string): bool
50
{
51
    if (!preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $string)) {
52
        return false;
53
    }
54
55
    $decoded = base64_decode($string, true);
56
57
    return $decoded !== false && base64_encode($decoded) === $string;
58
}
59
60
/**
61
 * Generates random number sequence
62
 * @param int $length
63
 * @return int
64
 */
65
function random_number(int $length = 10): int
66
{
67
    $randomString = '';
68
    for ($i = 0; $i < $length; $i++) {
69
        $randomString .= rand(0, 9);
70
    }
71
    return (int)$randomString;
72
}
73
74
/**
75
 * Slugify the string
76
 * @param string $text
77
 * @return string
78
 */
79
function slugify(string $text): string
80
{
81
    $text = trim($text, ' ');
82
    $text = preg_replace('/[^\p{L}\p{N}]/u', ' ', $text);
83
    $text = preg_replace('/\s+/', '-', $text);
84
    $text = trim($text, '-');
85
    $text = mb_strtolower($text);
86
87
    if (empty($text)) {
88
        return 'n-a';
89
    }
90
91
    return $text;
92
}
93
94
/**
95
 * Stops the execution
96
 * @param Closure|null $closure
97
 * @param int|null $code
98
 * @return mixed
99
 * @throws StopExecutionException
100
 */
101
function stop(Closure $closure = null, ?int $code = 0)
102
{
103
    if ($closure) {
104
        $closure();
105
    }
106
107
    throw StopExecutionException::executionTerminated($code);
108
}
109
110
/**
111
 * Checks the app debug mode
112
 * @return bool
113
 */
114
function is_debug_mode(): bool
115
{
116
    return filter_var(config()->get('debug'), FILTER_VALIDATE_BOOLEAN);
117
}
118
119
/**
120
 * Handles page not found
121
 * @return void
122
 * @throws DiException
123
 * @throws ReflectionException
124
 * @throws BaseException
125
 * @throws ConfigException
126
 * @throws RendererException
127
 */
128
function page_not_found()
129
{
130
    $acceptHeader = Response::getHeader('Accept');
131
132
    $isJson = $acceptHeader === 'application/json';
133
134
    if ($isJson) {
135
        Response::json(
136
            ['status' => 'error', 'message' => 'Page not found'],
137
            404
138
        );
139
    } else {
140
        Response::html(
141
            partial('errors' . DS . '404'),
142
            404
143
        );
144
    }
145
}
146
147
/**
148
 * Gets directory classes
149
 * @param string $path
150
 * @return array
151
 */
152
function get_directory_classes(string $path): array
153
{
154
    $class_names = [];
155
156
    if (is_dir($path)) {
157
        $allFiles = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
158
        $phpFiles = new RegexIterator($allFiles, '/\.php$/');
159
160
        foreach ($phpFiles as $file) {
161
            $class = pathinfo($file->getFilename());
162
            $class_names[] = $class['filename'];
163
        }
164
    }
165
166
    return $class_names;
167
}
168
169
/**
170
 * Gets the caller class
171
 * @param integer $index
172
 * @return string|null
173
 */
174
function get_caller_class(int $index = 2): ?string
175
{
176
    $caller = debug_backtrace();
177
    $caller = $caller[$index];
178
179
    return $caller['class'] ?? null;
180
}
181
182
/**
183
 * Gets the caller function
184
 * @param integer $index
185
 * @return string|null
186
 */
187
function get_caller_function(int $index = 2): ?string
188
{
189
    $caller = debug_backtrace();
190
    $caller = $caller[$index];
191
192
    return $caller['function'] ?? null;
193
}
194
195
/**
196
 * Exports the variable
197
 * @param $var
198
 * @return string
199
 * @throws ExceptionInterface
200
 */
201
function export($var): string
202
{
203
    return VarExporter::export($var);
204
}
205
206
/**
207
 * Checks if the entity is closure
208
 * @param mixed $entity
209
 * @return bool
210
 */
211
function is_closure($entity): bool
212
{
213
    return $entity instanceof Closure;
214
}
215
216
/**
217
 * @param DbalInterface $ormInstance
218
 * @param string $modelClass
219
 * @return QtModel
220
 */
221
function wrapToModel(DbalInterface $ormInstance, string $modelClass): QtModel
222
{
223
    if (!class_exists($modelClass)) {
224
        throw new InvalidArgumentException("Model class '$modelClass' does not exist.");
225
    }
226
227
    $model = new $modelClass();
228
229
    if (!$model instanceof QtModel) {
230
        throw new InvalidArgumentException("Model class '$modelClass' must extend QtModel.");
231
    }
232
233
    $model->setOrmInstance($ormInstance);
234
235
    return $model;
236
}
237
238
/**
239
 * Recursively deletes folder
240
 * @param string $dir
241
 * @return bool
242
 */
243
function deleteDirectoryWithFiles(string $dir): bool
244
{
245
    if (!is_dir($dir)) {
246
        return false;
247
    }
248
249
    $files = array_diff(scandir($dir), array('.', '..'));
250
251
    foreach ($files as $file) {
252
        $path = $dir . DS . $file;
253
        is_dir($path) ? deleteDirectoryWithFiles($path) : unlink($path);
254
    }
255
256
    return rmdir($dir);
257
}
258
259
/**
260
 * @param string $content
261
 * @param bool $sanitize
262
 * @return string
263
 */
264
function markdown_to_html(string $content, bool $sanitize = false): string
265
{
266
    $converter = new CommonMarkConverter();
267
    $purifier = null;
268
269
    if ($sanitize) {
270
        $config = HTMLPurifier_Config::createDefault();
0 ignored issues
show
Bug introduced by
The type HTMLPurifier_Config 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...
271
        $purifier = new HTMLPurifier($config);
0 ignored issues
show
Bug introduced by
The type HTMLPurifier 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...
272
    }
273
274
    $html = $converter->convertToHtml($content);
275
    
276
    if ($purifier) {
277
        return $purifier->purify($html);
278
    }
279
280
    return $html;
281
}