Skip to content

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

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
10 changes: 10 additions & 0 deletions configdb.php
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' => []
];
128 changes: 128 additions & 0 deletions functions/db.php
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

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'], ...

{
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");

Choose a reason for hiding this comment

The 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;
}
39 changes: 39 additions & 0 deletions functions/functions.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php
/**

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

перенести описание к той функции, для которой оно написано

* Подключает шаблон, передает туда данные и возвращает итоговый HTML контент
* @param string $name Путь к файлу шаблона относительно папки templates
* @param array $data Ассоциативный массив с данными для шаблона
* @return string Итоговый HTML
*/


/**
*Форматирует время лота

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

пробелы после *

*@param string $data
*@return array
*/
function remainingTime(string $date): array

Choose a reason for hiding this comment

The 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

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

перенести в functions/template.php

{
$price = number_format($price, 0, '.', ' ');
return $price . ' ₽';
}


102 changes: 102 additions & 0 deletions functions/template.php
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 . ' ₽';
}
24 changes: 24 additions & 0 deletions functions/validators.php
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;
}
22 changes: 13 additions & 9 deletions helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -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

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

создать файл
./funtions/validators.php
перенести туда функцию и подключить его через require

{
$formatToCheck = 'Y-m-d';
$dateTimeObj = date_create_from_format($formatToCheck, $date);

return $dateTimeObj !== false && array_sum(date_get_last_errors()) === 0;
}
Expand All @@ -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

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

пробел после :

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

перенести в fuctions/db.php

{
$stmt = mysqli_prepare($link, $sql);

if ($stmt === false) {
Expand All @@ -39,7 +41,7 @@ function db_get_prepare_stmt($link, $sql, $data = []) {

if ($data) {
$types = '';
$stmt_data = [];
$stmtData = [];

foreach ($data as $value) {
$type = 's';
Expand All @@ -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);
Expand Down Expand Up @@ -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

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

перенести в functions/template.php

{
$number = (int) $number;
$mod10 = $number % 10;
Expand Down Expand Up @@ -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 = [])

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

перенести в functions/template.php

{
$name = 'templates/' . $name;
$result = '';

Expand All @@ -144,3 +147,4 @@ function include_template($name, array $data = []) {
}



Loading