babaev-an b6f9698e59 20250214
+ [TwoDimSize]: Класс, описывающий двумерный размер.

+ [HashGetType]: Перечисление типов получения хэша.

+ [FileHash]: Класс для работы с хэшем файла или строки.
2025-02-14 16:41:50 +03:00

79 lines
2.2 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
namespace goodboyalex\php_components_pack\classes;
use goodboyalex\php_components_pack\enums\HashGetType;
use goodboyalex\php_components_pack\extensions\StringExtension;
/**
* Класс для работы с хэшем файла или строки.
*
* @author Александр Бабаев
* @package php_components_pack
* @version 1.0
* @since 1.0.5
*/
final class FileHash
{
/**
* @var string $Hash Хэш файла.
*/
private(set) string $Hash;
/**
* @var HashGetType Тип получения хэша.
*/
public HashGetType $HashBy;
/**
* Конструктор.
*
* @param string $str Строка или имя файла.
* @param HashGetType $HashBy Тип получения хэша.
*/
public function __construct (string $str = "", HashGetType $HashBy = HashGetType::ByString)
{
$this->HashBy = $HashBy;
$this->Hash = match ($HashBy) {
HashGetType::ByString => $this->pGetHash($str),
HashGetType::ByFile => $this->pGetFileHash($str)
};
}
/**
* Получение хэша файла по строке.
*
* @param string $str Строка.
*
* @return string Хэш строки.
*/
private function pGetHash (string $str): string
{
return hash('sha256', $str);
}
/**
* Получение хэша файла по имени файла.
*
* @param string $fileName Имя файла.
*
* @return string Хэш файла.
*/
private function pGetFileHash (string $fileName): string
{
return hash_file('sha256', $fileName);
}
/**
* Сравнивает текущий хэш с хэшем <code>otherHash</code> и выдаёт <code>true</code>, если совпадают, и
* <code>false</code>, если не совпадают.
*
* @param FileHash $otherHash Другой хэш.
*
* @return bool <code>true</code>, если совпадают, и <code>false</code>, если не совпадают.
*/
public function IsEqual (FileHash $otherHash): bool
{
return StringExtension::Compare($this->Hash, $otherHash->Hash, true) === 0;
}
}