site-tordv-calculator/mirzaev/calculator/system/models/metals_model.php

233 lines
7.9 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
declare(strict_types=1);
namespace mirzaev\calculator\models;
use mirzaev\calculator\models\settings_model as settings;
use mirzaev\calculator\models\accounts_model as accounts;
use pdo;
use exception;
/**
* Модель металла
*
* @package mirzaev\calculator\models
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
*/
final class metals_model extends core
{
/**
* Расчёт скорость реза металла
*
* @param string $metal Металл
* @param string $gas Газ
* @param float $lenght Толщина
* @param array &$errors Журнал ошибок
*
* @return float|int Скорость реза (мм/с)
*/
public static function cut(string $metal, string $gas, float $lenght, array &$errors = []): float|int
{
try {
return (float) settings::read("cut_speed_${metal}_${gas}_$lenght", $errors) ?? throw new exception('Не удалось определить скорость реза металла');
} catch (exception $e) {
// Запись в журнал ошибок
$errors[] = [
'text' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine(),
'stack' => $e->getTrace()
];
}
return 0;
}
/**
* Определение веса
*
* @param string $type Тип
* @param array &$errors Журнал ошибок
*
* @return float|null Вес (кг)
*/
public static function kg(string $type = 'stainless_steel', array &$errors = []): ?float
{
try {
return (float) match ($type) {
'steel' => 8,
'galvanized_steel' => 8,
'stainless_steel' => 8.7,
'brass' => 8.7,
'copper' => 9,
'aluminum' => 3,
default => throw new exception('Не удалось определить тип металла')
};
} catch (exception $e) {
// Запись в журнал ошибок
$errors[] = [
'text' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine(),
'stack' => $e->getTrace()
];
}
return null;
}
/**
* Запись в базу данных
*
* @param int $supply Идентификатор записи поставки в базе данных
* @param string $type Тип
* @param string $mark Марка
* @param float $width Ширина (мм)
* @param float $height Высота (мм)
* @param float $length Толщина (мм)
* @param int $piece Цена за лист (руб)
* @param int $ton Цена за тонну (руб)
* @param array &$errors Журнал ошибок
*
* @return bool Статус записи
*/
public static function write(int $supply, string $type, string $mark, float $width, float $height, float $length, int $piece, int $ton, array &$errors = []): bool
{
try {
if ($account = accounts::account($errors)) {
// Инициализирован аккаунт
// Инициализация запроса
$request = static::$db->prepare("INSERT INTO `metals` (`supply`, `type`, `mark`, `width`, `height`, `length`, `piece`, `ton`, `account`) VALUES (:supply, :type, :mark, :width, :height, :length, :piece, :ton, :account)");
// Инициализация параметров
$params = [
':supply' => $supply,
':type' => $type,
':mark' => $mark,
':width' => $width,
':height' => $height,
':length' => $length,
':piece' => $piece,
':ton' => $ton,
':account' => $account['id'],
];
// Отправка запроса
$request->execute($params);
// Получение ответа
return $request->fetch(pdo::FETCH_ASSOC) !== false;
}
} catch (exception $e) {
// Запись в журнал ошибок
$errors[] = [
'text' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine(),
'stack' => $e->getTrace()
];
}
return false;
}
/**
* Чтение из базы данных
*
* Очищает от дубликатов
*
* @param string $type Тип
* @param string $mark Марка
* @param float $length Толщина
* @param array &$errors Журнал ошибок
*
* @return float|null Цена за 1 килограмм (руб)
*/
public static function read(string $type, string $mark, float $length, array &$errors = []): ?array
{
try {
// Инициализация запроса
$request = static::$db->prepare("SELECT `width`, `height`, `piece`, `ton` FROM `metals` WHERE `type` = :type && `mark` = :mark && `length` = :length LIMIT 30");
// Отправка запроса
$request->execute([
':type' => $type,
':mark' => $mark,
':length' => $length
]);
// Генерация ответа
$response = $request->fetchAll(pdo::FETCH_ASSOC);
// Проверка на полученные значения
if (!is_array($response)) return false;
if (count($response) === 1) return $response[0];
else if (count($response) > 1) {
// Найдено более чем одно значение
// Инициализация буфера вывода
$buffer = $response[0];
foreach ($response as $metal) {
// Перебор полученных значений металлов
// Запись в буфер металла с самой большей площадью листа
if (($metal['width'] * $metal['height']) > ($buffer['width'] * $buffer['height'])) $buffer = $metal;
}
return $metal;
}
} catch (exception $e) {
// Запись в журнал ошибок
$errors[] = [
'text' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine(),
'stack' => $e->getTrace()
];
}
return null;
}
/**
* Поиск и чтение марок металла
*
* Очищает от дубликатов
*
* @param string $type Тип
* @param array &$errors Журнал ошибок
*
* @return float|null Цена за 1 килограмм (руб)
*/
public static function marks(string $type = '*', array &$errors = []): ?array
{
try {
// Инициализация запроса
$request = static::$db->prepare("SELECT DISTINCT `mark` FROM `metals` WHERE `type` = :type");
// Отправка запроса
$request->execute([':type' => $type]);
// Генерация ответа
$response = $request->fetchAll(pdo::FETCH_COLUMN);
return $response === false ? null : (array) $response;
} catch (exception $e) {
// Запись в журнал ошибок
$errors[] = [
'text' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine(),
'stack' => $e->getTrace()
];
}
return null;
}
}