-
Notifications
You must be signed in to change notification settings - Fork 1
Module5 task1 #13
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Module5 task1 #13
Changes from all commits
10b9eb2
e995a20
f132aab
1d4f563
4593227
5c880df
1b691d3
15c35d6
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
<?php | ||
return [ | ||
'db' => [ | ||
'host' => 'MySQL-8.2', | ||
'user' => 'root', | ||
'password' => '', | ||
'database' => 'yeticave', | ||
], | ||
'sender' => [] | ||
]; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,128 @@ | ||
<?php | ||
/** | ||
* Подключение к базе данных | ||
* @param array $config Настройки подключения | ||
* @return mysqli|bool Возваращемый тип данных | ||
*/ | ||
function dbConnect(array $config):mysqli|bool | ||
{ | ||
if (!isset($config['db']['host'], $config['db']['user'], $config['db']['password'], $config['db']['database'])) { | ||
exit; | ||
} | ||
|
||
$dbConfig = $config['db']; | ||
|
||
$con = mysqli_connect($dbConfig['host'], $dbConfig['user'], $dbConfig['password'], $dbConfig['database']); | ||
|
||
|
||
if (!$con) { | ||
echo "Подключения к базе данных не установлено"; | ||
exit("Connection error: " . mysqli_connect_error()); | ||
} | ||
|
||
mysqli_set_charset($con, "utf8"); | ||
|
||
return $con; | ||
} | ||
|
||
/** | ||
* Функция формирующая запрос на получение массива самых новых актуальных лотов из базы данных | ||
* @param mysqli $con | ||
* @return array | ||
*/ | ||
function getNewLotsFromDb(mysqli $con):array | ||
{ | ||
$sql = "SELECT l.id, l.title, l.start_price, l.image_url, c.name AS category_name, r.amount AS current_price, l.created_at | ||
FROM lots l | ||
JOIN categories c ON c.id = l.category_id | ||
LEFT JOIN rates r ON r.lot_id = l.id | ||
WHERE l.ended_at > NOW() | ||
GROUP BY l.id, l.title, l.start_price, l.image_url, c.name, current_price | ||
ORDER BY l.created_at DESC | ||
LIMIT 3;"; | ||
|
||
$result = mysqli_query($con, $sql); | ||
|
||
if (!$result) { | ||
$error = mysqli_error($con); | ||
print("SQL Error: $error"); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. exit(); |
||
exit(); | ||
} | ||
|
||
return mysqli_fetch_all($result, MYSQLI_ASSOC); | ||
} | ||
|
||
/** | ||
* Функция формирующая запрос на получение массива всех категорий из базы данных | ||
* @param mysqli $con | ||
* @return array | ||
*/ | ||
function getAllCategoriesFromDb(mysqli $con):array | ||
{ | ||
$sql = "SELECT * FROM categories;"; | ||
$result = mysqli_query($con, $sql); | ||
|
||
if (!$result) { | ||
$error = mysqli_error($con); | ||
print("SQL Error: $error"); | ||
exit(); | ||
} | ||
|
||
return mysqli_fetch_all($result, MYSQLI_ASSOC); | ||
} | ||
|
||
/** | ||
* Создает подготовленное выражение на основе готового SQL запроса и переданных данных | ||
* | ||
* @param $link mysqli Ресурс соединения | ||
* @param $sql string SQL запрос с плейсхолдерами вместо значений | ||
* @param array $data Данные для вставки на место плейсхолдеров | ||
* | ||
* @return mysqli_stmt Подготовленное выражение | ||
*/ | ||
|
||
function dbGetPrepareStmt(mysqli $link, $sql, $data = []) : mysqli_stmt | ||
{ | ||
$stmt = mysqli_prepare($link, $sql); | ||
|
||
if ($stmt === false) { | ||
$errorMsg = 'Не удалось инициализировать подготовленное выражение: ' . mysqli_error($link); | ||
die($errorMsg); | ||
} | ||
|
||
if ($data) { | ||
$types = ''; | ||
$stmtData = []; | ||
|
||
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; | ||
$stmtData[] = $value; | ||
} | ||
} | ||
|
||
$values = array_merge([$stmt, $types], $stmtData); | ||
|
||
$func = 'mysqli_stmt_bind_param'; | ||
$func(...$values); | ||
|
||
if (mysqli_errno($link) > 0) { | ||
$errorMsg = 'Не удалось связать подготовленное выражение с параметрами: ' . mysqli_error($link); | ||
die($errorMsg); | ||
} | ||
} | ||
|
||
return $stmt; | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
<?php | ||
/** | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. перенести описание к той функции, для которой оно написано |
||
* Подключает шаблон, передает туда данные и возвращает итоговый HTML контент | ||
* @param string $name Путь к файлу шаблона относительно папки templates | ||
* @param array $data Ассоциативный массив с данными для шаблона | ||
* @return string Итоговый HTML | ||
*/ | ||
|
||
|
||
/** | ||
*Форматирует время лота | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. пробелы после * |
||
*@param string $data | ||
*@return array | ||
*/ | ||
function remainingTime(string $date): array | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. можно тоже в перенести в functions/template.php |
||
{ | ||
$timeDifference = strtotime($date) - time(); | ||
if ($timeDifference<=0){ | ||
return [0,0]; | ||
|
||
} | ||
$hours = floor($timeDifference / 3600); | ||
$minutes = floor(($timeDifference / 3600) % 60); | ||
|
||
return [$hours, $minutes]; | ||
} | ||
|
||
/** | ||
* Форматирует cумму лота и добавляет знак рубля | ||
* @param int|float $price | ||
* @return string | ||
*/ | ||
function formatAmount(int|float $price): string | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. перенести в functions/template.php |
||
{ | ||
$price = number_format($price, 0, '.', ' '); | ||
return $price . ' ₽'; | ||
} | ||
|
||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,102 @@ | ||
<?php | ||
|
||
/** | ||
* Возвращает корректную форму множественного числа | ||
* Ограничения: только для целых чисел | ||
* | ||
* Пример использования: | ||
* $remaining_minutes = 5; | ||
* echo "Я поставил таймер на {$remaining_minutes} " . | ||
* get_noun_plural_form( | ||
* $remaining_minutes, | ||
* 'минута', | ||
* 'минуты', | ||
* 'минут' | ||
* ); | ||
* Результат: "Я поставил таймер на 5 минут" | ||
* | ||
* @param int $number Число, по которому вычисляем форму множественного числа | ||
* @param string $one Форма единственного числа: яблоко, час, минута | ||
* @param string $two Форма множественного числа для 2, 3, 4: яблока, часа, минуты | ||
* @param string $many Форма множественного числа для остальных чисел | ||
* | ||
* @return string Рассчитанная форма множественнго числа | ||
*/ | ||
|
||
function getNounPluralForm (int $number, string $one, string $two, string $many): string | ||
{ | ||
$number = (int) $number; | ||
$mod10 = $number % 10; | ||
$mod100 = $number % 100; | ||
|
||
switch (true) { | ||
case ($mod100 >= 11 && $mod100 <= 20): | ||
return $many; | ||
|
||
case ($mod10 > 5): | ||
return $many; | ||
|
||
case ($mod10 === 1): | ||
return $one; | ||
|
||
case ($mod10 >= 2 && $mod10 <= 4): | ||
return $two; | ||
|
||
default: | ||
return $many; | ||
} | ||
} | ||
|
||
/** | ||
* Подключает шаблон, передает туда данные и возвращает итоговый HTML контент | ||
* @param string $name Путь к файлу шаблона относительно папки templates | ||
* @param array $data Ассоциативный массив с данными для шаблона | ||
* @return string Итоговый HTML | ||
*/ | ||
|
||
function includeTemplate($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; | ||
} | ||
|
||
/** | ||
*Форматирует время лота | ||
*@param string $data | ||
*@return array | ||
*/ | ||
function remainingTime(string $date): array | ||
{ | ||
$timeDifference = strtotime($date) - time(); | ||
if ($timeDifference<=0){ | ||
return [0,0]; | ||
|
||
} | ||
$hours = floor($timeDifference / 3600); | ||
$minutes = floor(($timeDifference / 3600) % 60); | ||
|
||
return [$hours, $minutes]; | ||
} | ||
|
||
/** | ||
* Форматирует cумму лота и добавляет знак рубля | ||
* @param int|float $price | ||
* @return string | ||
*/ | ||
function formatAmount(int|float $price): string | ||
{ | ||
$price = number_format($price, 0, '.', ' '); | ||
return $price . ' ₽'; | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
<?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 isDateValid(string $date) : bool | ||
{ | ||
$formatToCheck = 'Y-m-d'; | ||
$dateTimeObj = date_create_from_format($formatToCheck, $date); | ||
|
||
return $dateTimeObj !== false && array_sum(date_get_last_errors()) === 0; | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -13,9 +13,10 @@ | |
* | ||
* @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); | ||
function isDateValid(string $date) : bool | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. создать файл |
||
{ | ||
$formatToCheck = 'Y-m-d'; | ||
$dateTimeObj = date_create_from_format($formatToCheck, $date); | ||
|
||
return $dateTimeObj !== false && array_sum(date_get_last_errors()) === 0; | ||
} | ||
|
@@ -29,7 +30,8 @@ function is_date_valid(string $date) : bool { | |
* | ||
* @return mysqli_stmt Подготовленное выражение | ||
*/ | ||
function db_get_prepare_stmt($link, $sql, $data = []) { | ||
function dbGetPrepareStmt(mysqli $link, $sql, $data = []):mysqli_stmt | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. пробел после : There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. перенести в fuctions/db.php |
||
{ | ||
$stmt = mysqli_prepare($link, $sql); | ||
|
||
if ($stmt === false) { | ||
|
@@ -39,7 +41,7 @@ function db_get_prepare_stmt($link, $sql, $data = []) { | |
|
||
if ($data) { | ||
$types = ''; | ||
$stmt_data = []; | ||
$stmtData = []; | ||
|
||
foreach ($data as $value) { | ||
$type = 's'; | ||
|
@@ -56,11 +58,11 @@ function db_get_prepare_stmt($link, $sql, $data = []) { | |
|
||
if ($type) { | ||
$types .= $type; | ||
$stmt_data[] = $value; | ||
$stmtData[] = $value; | ||
} | ||
} | ||
|
||
$values = array_merge([$stmt, $types], $stmt_data); | ||
$values = array_merge([$stmt, $types], $stmtData); | ||
|
||
$func = 'mysqli_stmt_bind_param'; | ||
$func(...$values); | ||
|
@@ -96,7 +98,7 @@ function db_get_prepare_stmt($link, $sql, $data = []) { | |
* | ||
* @return string Рассчитанная форма множественнго числа | ||
*/ | ||
function get_noun_plural_form (int $number, string $one, string $two, string $many): string | ||
function getNounPluralForm (int $number, string $one, string $two, string $many): string | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. перенести в functions/template.php |
||
{ | ||
$number = (int) $number; | ||
$mod10 = $number % 10; | ||
|
@@ -126,7 +128,8 @@ function get_noun_plural_form (int $number, string $one, string $two, string $ma | |
* @param array $data Ассоциативный массив с данными для шаблона | ||
* @return string Итоговый HTML | ||
*/ | ||
function include_template($name, array $data = []) { | ||
function includeTemplate($name, array $data = []) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. перенести в functions/template.php |
||
{ | ||
$name = 'templates/' . $name; | ||
$result = ''; | ||
|
||
|
@@ -144,3 +147,4 @@ function include_template($name, array $data = []) { | |
} | ||
|
||
|
||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Передать в нее $config['db']
и тогда внутри можно будет использовать ключи
$config['host'], $config['user'], ...