2025-06-29 20:29:52 +03:00

90 lines
3.0 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\JsonErrorCode;
use goodboyalex\php_components_pack\exceptions\JsonException;
use goodboyalex\php_components_pack\traits\JsonReWriter\JsonReWriterDeleteTrait;
use goodboyalex\php_components_pack\traits\JsonReWriter\JsonReWriterKeyTrait;
use goodboyalex\php_components_pack\traits\JsonReWriter\JsonReWriterLoadSaveTrait;
use goodboyalex\php_components_pack\traits\JsonReWriter\JsonReWriterReadTrait;
use goodboyalex\php_components_pack\traits\JsonReWriter\JsonReWriterWriteTrait;
/**
* Класс для работы с JSON-файлами.
*
* @author Александр Бабаев
* @package php_components_pack
* @version 1.0
* @since 1.1.0
*/
final class JsonReWriter
{
/**
* @var string $JsonString Строка JSON.
*/
public string $JsonString {
get {
// Проверка на пустоту
if (count($this->JsonData) === 0)
// - если массив пуст, возвращаем пустой JSON
return '{}';
// Преобразую данные в JSON
$json = json_encode($this->JsonData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
// Проверка на ошибки
if (json_last_error() !== JSON_ERROR_NONE)
// - если есть ошибки, выбрасываем исключение
throw new JsonException(null, JsonErrorCode::FromLastError(), json_last_error_msg());
// Возвращаем JSON
return $json;
}
set {
// Чтение содержимого файла и преобразование JSON в объект
$this->JsonData = json_decode($value, true);
// Проверка на ошибки
if ($this->JsonData === null && json_last_error() !== JSON_ERROR_NONE)
// - если есть ошибки, выбрасываем исключение
throw new JsonException($value, JsonErrorCode::FromLastError(), json_last_error_msg());
}
}
/**
* @var array $JsonData Массив данных.
*/
private array $JsonData;
/**
* Конструктор класса.
*/
public function __construct ()
{
$this->JsonData = [];
}
/**
* Деструктор класса.
*/
public function __destruct ()
{
unset($this->JsonData);
}
// Подключаем методы чтения JSON
use JsonReWriterReadTrait;
// Подключаем методы записи JSON
use JsonReWriterWriteTrait;
// Подключаем методы сохранения и загрузки JSON
use JsonReWriterLoadSaveTrait;
// Подключаем методы работы с ключами
use JsonReWriterKeyTrait;
// Подключаем методы удаления данных из JSON
use JsonReWriterDeleteTrait;
}