Passed
Pull Request — master (#241)
by Arman
03:20
created

wrapToModel()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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