-
Notifications
You must be signed in to change notification settings - Fork 1
/
helpers.php
104 lines (87 loc) · 3.15 KB
/
helpers.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
<?php
/**
* Проверяет переданную дату на соответствие формату 'ГГГГ-ММ-ДД'
*
* Примеры использования:
* is_date_valid('2019-01-01'); // true
* is_date_valid('2016-02-29'); // true
* is_date_valid('2019-04-31'); // false
* is_date_valid('10.10.2010'); // false
* is_date_valid('10/10/2010'); // false
*
* @param string $date Дата в виде строки
*
* @return bool true при совпадении с форматом 'ГГГГ-ММ-ДД', иначе false
*/
function is_date_valid(string $date): bool
{
$format_to_check = 'Y-m-d';
$dateTimeObj = date_create_from_format($format_to_check, $date);
return $dateTimeObj !== false && array_sum(date_get_last_errors()) === 0;
}
/**
* Создает подготовленное выражение на основе готового SQL запроса и переданных данных
*
* @param $link mysqli Ресурс соединения
* @param $sql string SQL запрос с плейсхолдерами вместо значений
* @param array $data Данные для вставки на место плейсхолдеров
*
* @return mysqli_stmt Подготовленное выражение
*/
function db_get_prepare_stmt($link, $sql, $data = [])
{
$stmt = mysqli_prepare($link, $sql);
if ($stmt === false) {
$errorMsg = 'Не удалось инициализировать подготовленное выражение: ' . mysqli_error($link);
die($errorMsg);
}
if ($data) {
$types = '';
$stmt_data = [];
foreach ($data as $value) {
$type = 's';
if (is_int($value)) {
$type = 'i';
} else {
if (is_string($value)) {
$type = 's';
} else {
if (is_double($value)) {
$type = 'd';
}
}
}
if ($type) {
$types .= $type;
$stmt_data[] = $value;
}
}
$values = array_merge([$stmt, $types], $stmt_data);
$func = 'mysqli_stmt_bind_param';
$func(...$values);
if (mysqli_errno($link) > 0) {
$errorMsg = 'Не удалось связать подготовленное выражение с параметрами: ' . mysqli_error($link);
die($errorMsg);
}
}
return $stmt;
}
/**
* Подключает шаблон, передает туда данные и возвращает итоговый HTML контент
* @param string $name Путь к файлу шаблона относительно папки templates
* @param array $data Ассоциативный массив с данными для шаблона
* @return string Итоговый HTML
*/
function include_template($name, array $data = [])
{
$name = 'templates/' . $name;
$result = '';
if (!is_readable($name)) {
return $result;
}
ob_start();
extract($data);
require $name;
$result = ob_get_clean();
return $result;
}