Compare commits
2 Commits
d0ce9e47af
...
9f7ce7e9b6
Author | SHA1 | Date | |
---|---|---|---|
Arsen Mirzaev Tatyano-Muradovich | 9f7ce7e9b6 | ||
Arsen Mirzaev Tatyano-Muradovich | 4e04d09b32 |
|
@ -1,3 +1,3 @@
|
|||
# PHP 8.2 Framework for working with ArangoDB
|
||||
# PHP 8.3 Framework for working with ArangoDB
|
||||
|
||||
🤟 Very simple and flexible, easy to scale and integrate
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
"keywords": [
|
||||
"ArangoDB"
|
||||
],
|
||||
"type": "library",
|
||||
"type": "framework",
|
||||
"license": "WTFPL",
|
||||
"homepage": "https://git.hood.su/mirzaev/arangodb",
|
||||
"authors": [
|
||||
|
|
|
@ -4,122 +4,198 @@ declare(strict_types=1);
|
|||
|
||||
namespace mirzaev\arangodb;
|
||||
|
||||
use mirzaev\arangodb\terminal;
|
||||
// Files of the project
|
||||
use mirzaev\arangodb\connection,
|
||||
mirzaev\arangodb\terminal,
|
||||
mirzaev\arangodb\enumerations\collection\type;
|
||||
|
||||
use ArangoDBClient\Connection as _connection;
|
||||
use ArangoDBClient\Collection as _collection;
|
||||
use ArangoDBClient\Statement as _statement;
|
||||
use ArangoDBClient\Document as _document;
|
||||
use ArangoDBClient\CollectionHandler as _collection_handler;
|
||||
// Library for ArangoDB
|
||||
use ArangoDBClient\Statement as _statement,
|
||||
ArangoDBClient\Document as _document,
|
||||
ArangoDBClient\CollectionHandler as _collection_handler;
|
||||
|
||||
// Built-in libraries
|
||||
use exception;
|
||||
|
||||
/**
|
||||
* Коллекция
|
||||
* Collection
|
||||
*
|
||||
* @package mirzaev\arangodb
|
||||
*
|
||||
* @license http://www.wtfpl.net/ Do What The Fuck You Want To Public License
|
||||
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
|
||||
*/
|
||||
class collection
|
||||
{
|
||||
/**
|
||||
* Инициализация
|
||||
* Initialize a collection
|
||||
*
|
||||
* @param _connection $session Сессия соединения с базой данных
|
||||
* @param string $name Название
|
||||
* @param bool $edge Обрабатывать как ребро? (иначе: вершина)
|
||||
* @param string $collection Name of the collection
|
||||
* @param type $type Type of the collection
|
||||
* @param ?terminal $terminal Инстанция терминала
|
||||
* @param array &$errors Registry of errors
|
||||
*
|
||||
* @return string|null Идентификатор коллекции
|
||||
* @return string|null Identifier of the collection
|
||||
*/
|
||||
public static function init(_connection $session, string $name, bool $edge = false, ?terminal $terminal = null): ?string
|
||||
public static function initialize(string $name, type $type = type::document, ?terminal $terminal = null, array &$errors = []): ?string
|
||||
{
|
||||
// Инициализация
|
||||
$collections = new _collection_handler($session);
|
||||
try {
|
||||
// Инициализация
|
||||
$collections = new _collection_handler(connection::$session);
|
||||
|
||||
if (!$collections->has($name)) {
|
||||
// Не найдана коллекция
|
||||
|
||||
// Запись в вывод
|
||||
if ($terminal instanceof terminal) $terminal::write("Коллекция \"$name\" не найдена");
|
||||
|
||||
// Запись коллекции на сервер и его ответ в буфер возврата
|
||||
$id = $collections->create($name, ['type' => $edge ? _collection::TYPE_EDGE : _collection::TYPE_DOCUMENT]);
|
||||
|
||||
if ($collections->has($name)) {
|
||||
// Коллекция найдена (записана)
|
||||
if (!$collections->has($name)) {
|
||||
// Не найдана коллекция
|
||||
|
||||
// Запись в вывод
|
||||
if ($terminal instanceof terminal) $terminal::write("Создана коллекция \"$name\" с типом " . ($edge ? 'ребро' : 'документ'));
|
||||
if ($terminal instanceof terminal) $terminal::write("Not found $type collection: $name");
|
||||
|
||||
// Запись коллекции на сервер и его ответ в буфер возврата
|
||||
$id = $collections->create($name, ['type' => $type->code()]);
|
||||
|
||||
if ($collections->has($name)) {
|
||||
// Коллекция найдена (записана)
|
||||
|
||||
// Запись в вывод
|
||||
if ($terminal instanceof terminal) $terminal::write("Created $type collection: $name");
|
||||
|
||||
// Возврат идентификатора коллекции
|
||||
return $id;
|
||||
}
|
||||
} else {
|
||||
// Найдена коллекция
|
||||
|
||||
// Возврат идентификатора коллекции
|
||||
return $id;
|
||||
return $name;
|
||||
}
|
||||
} else {
|
||||
// Найдена коллекция
|
||||
|
||||
// Возврат идентификатора коллекции
|
||||
return $name;
|
||||
} catch (exception $e) {
|
||||
// Writing to registry of errors
|
||||
$errors[] = [
|
||||
'text' => $e->getMessage(),
|
||||
'file' => $e->getFile(),
|
||||
'line' => $e->getLine(),
|
||||
'stack' => $e->getTrace()
|
||||
];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Поиск
|
||||
* Execute
|
||||
*
|
||||
* @param _connection $session Сессия соединения с базой данных
|
||||
* @param string $query AQL-запрос
|
||||
* @param array $binds Binds for query [bind => value]
|
||||
* @param string $query Query (AQL)
|
||||
* @param array $parameters Binded parameters for placeholders [placholder => parameter]
|
||||
* @param array &$errors Registry of errors
|
||||
*
|
||||
* @return _document|array|string|int|null Инстанция документа
|
||||
* @return _document|array|string|int|null Instance of the document
|
||||
*/
|
||||
public static function search(_connection $session, string $query, array $binds = []): _document|string|array|int|null
|
||||
public static function execute(string $query, array $parameters = [], array &$errors = []): _document|string|array|int|null
|
||||
{
|
||||
// Statement instance initialization
|
||||
$instance = new _statement(
|
||||
$session,
|
||||
[
|
||||
'query' => $query,
|
||||
"batchSize" => 1000,
|
||||
"sanitize" => true
|
||||
]
|
||||
);
|
||||
try {
|
||||
// Statement instance initialization
|
||||
$instance = new _statement(
|
||||
connection::$session,
|
||||
[
|
||||
'query' => $query,
|
||||
"batchSize" => 1000,
|
||||
"sanitize" => true
|
||||
]
|
||||
);
|
||||
|
||||
// Binds application
|
||||
$instance->bind($binds);
|
||||
// Binds application
|
||||
$instance->bind($parameters);
|
||||
|
||||
// Sending the request
|
||||
$response = $instance->execute();
|
||||
// Sending the request
|
||||
$response = $instance->execute();
|
||||
|
||||
// Инициализация буфера вывода
|
||||
$buffer = [];
|
||||
// Инициализация буфера вывода
|
||||
$buffer = [];
|
||||
|
||||
foreach ($response->getAll() as $key => $value) {
|
||||
$buffer[$key] = $value;
|
||||
foreach ($response->getAll() as $key => $value) {
|
||||
$buffer[$key] = $value;
|
||||
}
|
||||
|
||||
// Exit (success)
|
||||
return is_array($buffer) && count($buffer) > 1 ? $buffer : $buffer[0] ?? null;
|
||||
} catch (exception $e) {
|
||||
// Writing to registry of errors
|
||||
$errors[] = [
|
||||
'text' => $e->getMessage(),
|
||||
'file' => $e->getFile(),
|
||||
'line' => $e->getLine(),
|
||||
'stack' => $e->getTrace()
|
||||
];
|
||||
}
|
||||
|
||||
return is_array($buffer) && count($buffer) > 1 ? $buffer : $buffer[0] ?? null;
|
||||
// Exit (fail)
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Очистка
|
||||
* Truncate
|
||||
*
|
||||
* @param _connection $session Сессия соединения с базой данных
|
||||
* @param string $name Название
|
||||
* @param string $name Name of the collection
|
||||
* @param array &$errors Registry of errors
|
||||
*
|
||||
* @return bool Статус выполнения
|
||||
*/
|
||||
public static function truncate(_connection $session, string $name): bool
|
||||
public static function truncate(string $collection, array &$errors = []): bool
|
||||
{
|
||||
// Инициализация
|
||||
$collections = new _collection_handler($session);
|
||||
try {
|
||||
// Initizlizing of the collection handler
|
||||
$collections = new _collection_handler(connection::$session);
|
||||
|
||||
if ($collections->has($name)) {
|
||||
// Найдена коллекция
|
||||
if ($collections->has($collection)) {
|
||||
// Fount the collection
|
||||
|
||||
// Очистка
|
||||
return $collections->truncate($name);
|
||||
// Truncate and exit (success)
|
||||
return $collections->truncate($collection);
|
||||
}
|
||||
} catch (exception $e) {
|
||||
// Writing to registry of errors
|
||||
$errors[] = [
|
||||
'text' => $e->getMessage(),
|
||||
'file' => $e->getFile(),
|
||||
'line' => $e->getLine(),
|
||||
'stack' => $e->getTrace()
|
||||
];
|
||||
}
|
||||
|
||||
// Exit (fail)
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Count documents in ArangoDB
|
||||
*
|
||||
* @param string $collection Name of the collection
|
||||
* @param array &$errors Registry of errors
|
||||
*
|
||||
* @return int|null Amount of documents in ArangoDB
|
||||
*/
|
||||
public static function count(string $collection, array &$errors = []): ?int
|
||||
{
|
||||
try {
|
||||
// Count and exit (success)
|
||||
return static::execute(
|
||||
<<<'AQL'
|
||||
RETURN LENGTH(@collection)
|
||||
AQL,
|
||||
[
|
||||
'collection' => $collection
|
||||
]
|
||||
);
|
||||
} catch (exception $e) {
|
||||
// Writing to registry of errors
|
||||
$errors[] = [
|
||||
'text' => $e->getMessage(),
|
||||
'file' => $e->getFile(),
|
||||
'line' => $e->getLine(),
|
||||
'stack' => $e->getTrace()
|
||||
];
|
||||
}
|
||||
|
||||
// Exit (fail)
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -4,201 +4,203 @@ declare(strict_types=1);
|
|||
|
||||
namespace mirzaev\arangodb;
|
||||
|
||||
use ArangoDBClient\Connection as _connection;
|
||||
use ArangoDBClient\Exception as _exception;
|
||||
use ArangoDBClient\UpdatePolicy as _update;
|
||||
use ArangoDBClient\ConnectionOptions as _options;
|
||||
// Library for ArangoDB
|
||||
use ArangoDBClient\Connection as _connection,
|
||||
ArangoDBClient\Exception as _exception,
|
||||
ArangoDBClient\UpdatePolicy as _update,
|
||||
ArangoDBClient\ConnectionOptions as _options;
|
||||
|
||||
// Built-in libraries
|
||||
use exception;
|
||||
|
||||
/**
|
||||
* Подключение
|
||||
* Connection
|
||||
*
|
||||
* @package mirzaev\arangodb
|
||||
*
|
||||
* @license http://www.wtfpl.net/ Do What The Fuck You Want To Public License
|
||||
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
|
||||
*/
|
||||
final class connection
|
||||
{
|
||||
/**
|
||||
* Адрес
|
||||
*/
|
||||
protected string $adress = 'tcp://127.0.0.1:8529';
|
||||
/**
|
||||
* Адрес
|
||||
*/
|
||||
protected string $adress = 'tcp://127.0.0.1:8529';
|
||||
|
||||
/**
|
||||
* Хранилище (название)
|
||||
*/
|
||||
protected string $storage = 'root';
|
||||
/**
|
||||
* Хранилище (название)
|
||||
*/
|
||||
protected string $storage = 'root';
|
||||
|
||||
/**
|
||||
* Тип аутентификации
|
||||
*/
|
||||
protected string $auth = 'Basic';
|
||||
/**
|
||||
* Тип аутентификации
|
||||
*/
|
||||
protected string $auth = 'Basic';
|
||||
|
||||
/**
|
||||
* Псевдоним пользователя
|
||||
*/
|
||||
protected string $name = 'root';
|
||||
/**
|
||||
* Псевдоним пользователя
|
||||
*/
|
||||
protected string $name = 'root';
|
||||
|
||||
/**
|
||||
* Пароль пользователя
|
||||
*/
|
||||
protected string $password = '';
|
||||
/**
|
||||
* Пароль пользователя
|
||||
*/
|
||||
protected string $password = '';
|
||||
|
||||
/**
|
||||
* Тип соединения
|
||||
*/
|
||||
protected string $connection = 'Keep-Alive';
|
||||
/**
|
||||
* Тип соединения
|
||||
*/
|
||||
protected string $connection = 'Keep-Alive';
|
||||
|
||||
/**
|
||||
* Время ожидания соединения
|
||||
*/
|
||||
protected int $timeout_connect = 3;
|
||||
/**
|
||||
* Время ожидания соединения
|
||||
*/
|
||||
protected int $timeout_connect = 3;
|
||||
|
||||
/**
|
||||
* Время ожидания запроса
|
||||
*/
|
||||
protected int $timeout_request = 3;
|
||||
/**
|
||||
* Время ожидания запроса
|
||||
*/
|
||||
protected int $timeout_request = 3;
|
||||
|
||||
/**
|
||||
* Переподключиться ли при разрыве соединения
|
||||
*/
|
||||
protected bool $reconnect = true;
|
||||
/**
|
||||
* Переподключиться ли при разрыве соединения
|
||||
*/
|
||||
protected bool $reconnect = true;
|
||||
|
||||
/**
|
||||
* Создавать ли коллекцию, если она не существует
|
||||
*/
|
||||
protected bool $create = true;
|
||||
/**
|
||||
* Создавать ли коллекцию, если она не существует
|
||||
*/
|
||||
protected bool $create = true;
|
||||
|
||||
/**
|
||||
* Действия при обновлении коллекции
|
||||
*/
|
||||
protected string $update = _update::LAST;
|
||||
/**
|
||||
* Действия при обновлении коллекции
|
||||
*/
|
||||
protected string $update = _update::LAST;
|
||||
|
||||
/**
|
||||
* Активация журналирования
|
||||
*/
|
||||
protected bool $journal = false;
|
||||
/**
|
||||
* Активация журналирования
|
||||
*/
|
||||
protected bool $journal = false;
|
||||
|
||||
/**
|
||||
* Сессия соединения
|
||||
*/
|
||||
protected _connection $session;
|
||||
/**
|
||||
* Сессия соединения
|
||||
*/
|
||||
public static _connection $session;
|
||||
|
||||
/**
|
||||
* Конструктор
|
||||
*
|
||||
* @param array $settings Настройки
|
||||
*/
|
||||
public function __construct(array $settings = null)
|
||||
{
|
||||
// Запись
|
||||
@$this->__set('adress', $settings['adress'] ?? $settings['endpoint']);
|
||||
@$this->__set('storage', $settings['storage'] ?? $settings['database']);
|
||||
@$this->__set('auth', $settings['auth']);
|
||||
@$this->__set('name', $settings['name']);
|
||||
@$this->__set('password', $settings['password']);
|
||||
@$this->__set('connection', $settings['connection']);
|
||||
@$this->__set('timeout_connect', $settings['timeout_connect']);
|
||||
@$this->__set('timeout_request', $settings['timeout_request']);
|
||||
@$this->__set('reconnect', $settings['reconnect']);
|
||||
@$this->__set('create', $settings['create']);
|
||||
@$this->__set('update', $settings['update'] ?? $settings['policy']);
|
||||
@$this->__set('journal', $settings['journal']);
|
||||
/**
|
||||
* Конструктор
|
||||
*
|
||||
* @param array $settings Настройки
|
||||
*/
|
||||
public function __construct(array $settings = null)
|
||||
{
|
||||
// Запись
|
||||
@$this->__set('adress', $settings['adress'] ?? $settings['endpoint']);
|
||||
@$this->__set('storage', $settings['storage'] ?? $settings['database']);
|
||||
@$this->__set('auth', $settings['auth']);
|
||||
@$this->__set('name', $settings['name']);
|
||||
@$this->__set('password', $settings['password']);
|
||||
@$this->__set('connection', $settings['connection']);
|
||||
@$this->__set('timeout_connect', $settings['timeout_connect']);
|
||||
@$this->__set('timeout_request', $settings['timeout_request']);
|
||||
@$this->__set('reconnect', $settings['reconnect']);
|
||||
@$this->__set('create', $settings['create']);
|
||||
@$this->__set('update', $settings['update'] ?? $settings['policy']);
|
||||
@$this->__set('journal', $settings['journal']);
|
||||
|
||||
if ($this->journal) {
|
||||
// Запрос на активацию журналирования
|
||||
if ($this->journal) {
|
||||
// Запрос на активацию журналирования
|
||||
|
||||
_exception::enableLogging();
|
||||
}
|
||||
_exception::enableLogging();
|
||||
}
|
||||
|
||||
// Подключение
|
||||
$this->session = new _connection([
|
||||
_options::OPTION_ENDPOINT => $this->adress,
|
||||
_options::OPTION_DATABASE => $this->storage,
|
||||
_options::OPTION_AUTH_TYPE => $this->auth,
|
||||
_options::OPTION_AUTH_USER => $this->name,
|
||||
_options::OPTION_AUTH_PASSWD => $this->password,
|
||||
_options::OPTION_CONNECTION => $this->connection,
|
||||
_options::OPTION_CONNECT_TIMEOUT => $this->timeout_connect,
|
||||
_options::OPTION_REQUEST_TIMEOUT => $this->timeout_request,
|
||||
_options::OPTION_RECONNECT => $this->reconnect,
|
||||
_options::OPTION_CREATE => $this->create,
|
||||
_options::OPTION_UPDATE_POLICY => $this->update,
|
||||
]);
|
||||
}
|
||||
// Подключение
|
||||
static::$session = new _connection([
|
||||
_options::OPTION_ENDPOINT => $this->adress,
|
||||
_options::OPTION_DATABASE => $this->storage,
|
||||
_options::OPTION_AUTH_TYPE => $this->auth,
|
||||
_options::OPTION_AUTH_USER => $this->name,
|
||||
_options::OPTION_AUTH_PASSWD => $this->password,
|
||||
_options::OPTION_CONNECTION => $this->connection,
|
||||
_options::OPTION_CONNECT_TIMEOUT => $this->timeout_connect,
|
||||
_options::OPTION_REQUEST_TIMEOUT => $this->timeout_request,
|
||||
_options::OPTION_RECONNECT => $this->reconnect,
|
||||
_options::OPTION_CREATE => $this->create,
|
||||
_options::OPTION_UPDATE_POLICY => $this->update,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Записать свойство
|
||||
*
|
||||
* @param mixed $name Название
|
||||
* @param mixed $value Значение
|
||||
*/
|
||||
public function __set(string $name, mixed $value): void
|
||||
{
|
||||
match ($name) {
|
||||
'adress', 'endpoint' => $this->adress = $value ?? throw new exception("Свойство \"$name\" не может быть пустым", 500),
|
||||
'storage', 'database', 'db' => $this->storage = $value ?? throw new exception("Свойство \"$name\" не может быть пустым", 500),
|
||||
'auth' => !$value ?: $this->auth = $value,
|
||||
'name' => !$value ?: $this->name = $value,
|
||||
'password' => !$value ?: $this->password = $value,
|
||||
'connection' => !$value ?: $this->connection = $value,
|
||||
'timeout_connect' => !$value ?: $this->timeout_connect = $value,
|
||||
'timeout_request' => !$value ?: $this->timeout_request = $value,
|
||||
'reconnect' => !$value ?: $this->reconnect = $value,
|
||||
'create' => !$value ?: $this->create = $value,
|
||||
'update', 'policy' => !$value ?: $this->update = $value,
|
||||
'journal' => !$value ?: $this->journal = $value,
|
||||
default => throw new exception("Свойство \"$name\" не найдено", 404)
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Записать свойство
|
||||
*
|
||||
* @param mixed $name Название
|
||||
* @param mixed $value Значение
|
||||
*/
|
||||
public function __set(string $name, mixed $value): void
|
||||
{
|
||||
match ($name) {
|
||||
'adress', 'endpoint' => $this->adress = $value ?? throw new exception("Свойство \"$name\" не может быть пустым", 500),
|
||||
'storage', 'database', 'db' => $this->storage = $value ?? throw new exception("Свойство \"$name\" не может быть пустым", 500),
|
||||
'auth' => !$value ?: $this->auth = $value,
|
||||
'name' => !$value ?: $this->name = $value,
|
||||
'password' => !$value ?: $this->password = $value,
|
||||
'connection' => !$value ?: $this->connection = $value,
|
||||
'timeout_connect' => !$value ?: $this->timeout_connect = $value,
|
||||
'timeout_request' => !$value ?: $this->timeout_request = $value,
|
||||
'reconnect' => !$value ?: $this->reconnect = $value,
|
||||
'create' => !$value ?: $this->create = $value,
|
||||
'update', 'policy' => !$value ?: $this->update = $value,
|
||||
'journal' => !$value ?: $this->journal = $value,
|
||||
default => throw new exception("Свойство \"$name\" не найдено", 404)
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Прочитать свойство
|
||||
*
|
||||
* @param mixed $name Название
|
||||
*/
|
||||
public function __get(string $name): mixed
|
||||
{
|
||||
return match ($name) {
|
||||
'adress', 'endpoint' => $this->adress,
|
||||
'storage', 'database', 'db' => $this->storage,
|
||||
'auth' => $this->auth,
|
||||
'name' => $this->name,
|
||||
'password' => $this->password,
|
||||
'connection' => $this->connection,
|
||||
'timeout_connect' => $this->timeout_connect,
|
||||
'timeout_request' => $this->timeout_request,
|
||||
'reconnect' => $this->reconnect,
|
||||
'create' => $this->create,
|
||||
'update', 'policy' => $this->update,
|
||||
'session' => $this->session,
|
||||
'journal' => $this->journal,
|
||||
default => throw new exception("Свойство \"$name\" не найдено", 404)
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Прочитать свойство
|
||||
*
|
||||
* @param mixed $name Название
|
||||
*/
|
||||
public function __get(string $name): mixed
|
||||
{
|
||||
return match ($name) {
|
||||
'adress', 'endpoint' => $this->adress,
|
||||
'storage', 'database', 'db' => $this->storage,
|
||||
'auth' => $this->auth,
|
||||
'name' => $this->name,
|
||||
'password' => $this->password,
|
||||
'connection' => $this->connection,
|
||||
'timeout_connect' => $this->timeout_connect,
|
||||
'timeout_request' => $this->timeout_request,
|
||||
'reconnect' => $this->reconnect,
|
||||
'create' => $this->create,
|
||||
'update', 'policy' => $this->update,
|
||||
'journal' => $this->journal,
|
||||
default => throw new exception("Свойство \"$name\" не найдено", 404)
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверить свойство на инициализированность
|
||||
*
|
||||
* @param mixed $name Название
|
||||
*/
|
||||
public function __isset(string $name): bool
|
||||
{
|
||||
return match ($name) {
|
||||
'adress', 'endpoint' => isset($this->adress),
|
||||
'storage', 'database', 'db' => isset($this->storage),
|
||||
'auth' => isset($this->auth),
|
||||
'name' => isset($this->name),
|
||||
'password' => isset($this->password),
|
||||
'connection' => isset($this->connection),
|
||||
'timeout_connect' => isset($this->timeout_connect),
|
||||
'timeout_request' => isset($this->timeout_request),
|
||||
'reconnect' => isset($this->reconnect),
|
||||
'create' => isset($this->create),
|
||||
'update', 'policy' => isset($this->update),
|
||||
'session' => isset($this->session),
|
||||
'journal' => isset($this->journal),
|
||||
default => throw new exception("Свойство \"$name\" не найдено", 404)
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Проверить свойство на инициализированность
|
||||
*
|
||||
* @param mixed $name Название
|
||||
*/
|
||||
public function __isset(string $name): bool
|
||||
{
|
||||
return match ($name) {
|
||||
'adress', 'endpoint' => isset($this->adress),
|
||||
'storage', 'database', 'db' => isset($this->storage),
|
||||
'auth' => isset($this->auth),
|
||||
'name' => isset($this->name),
|
||||
'password' => isset($this->password),
|
||||
'connection' => isset($this->connection),
|
||||
'timeout_connect' => isset($this->timeout_connect),
|
||||
'timeout_request' => isset($this->timeout_request),
|
||||
'reconnect' => isset($this->reconnect),
|
||||
'create' => isset($this->create),
|
||||
'update', 'policy' => isset($this->update),
|
||||
'journal' => isset($this->journal),
|
||||
default => throw new exception("Свойство \"$name\" не найдено", 404)
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
@ -4,111 +4,186 @@ declare(strict_types=1);
|
|||
|
||||
namespace mirzaev\arangodb;
|
||||
|
||||
use mirzaev\arangodb\terminal;
|
||||
// Files of the project
|
||||
use mirzaev\arangodb\terminal,
|
||||
mirzaev\arangodb\connection,
|
||||
mirzaev\arangodb\enumerations\collection\type;
|
||||
|
||||
use ArangoDBClient\Connection as _connection;
|
||||
use ArangoDBClient\Document as _document;
|
||||
use ArangoDBClient\Edge as _edge;
|
||||
use ArangoDBClient\DocumentHandler as _document_handler;
|
||||
use ArangoDBClient\EdgeHandler as _edge_handler;
|
||||
// Librsry for ArangoDB
|
||||
use ArangoDBClient\Connection as _connection,
|
||||
ArangoDBClient\Document as _document,
|
||||
ArangoDBClient\Edge as _edge,
|
||||
ArangoDBClient\DocumentHandler as _document_handler,
|
||||
ArangoDBClient\EdgeHandler as _edge_handler;
|
||||
|
||||
// Built-in libraries
|
||||
use exception;
|
||||
|
||||
/**
|
||||
* Документ
|
||||
* Document
|
||||
*
|
||||
* Handlers of document in ArangoDB
|
||||
*
|
||||
* @package mirzaev\arangodb
|
||||
*
|
||||
* @license http://www.wtfpl.net/ Do What The Fuck You Want To Public License
|
||||
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
|
||||
*/
|
||||
class document
|
||||
{
|
||||
/**
|
||||
* Записать
|
||||
* Write
|
||||
*
|
||||
* @param _connection $session Сессия соединения с базой данных
|
||||
* @param string $collection Коллекция
|
||||
* @param ?array $data Данные
|
||||
* @param bool $check Проверка на запись в базу данных
|
||||
* @param ?terminal $terminal Инстанция терминала
|
||||
* @param ?terminal $terminal Instance of the terminal
|
||||
* @param array &$errors Registry of errors
|
||||
*
|
||||
* @return string|null Идентификатор
|
||||
*
|
||||
* @todo
|
||||
* 1. Bind parameters
|
||||
*/
|
||||
public static function write(_connection $session, string $collection, ?array $data = [], bool $check = false, ?terminal $terminal = null): ?string
|
||||
{
|
||||
// Инициализация коллекции
|
||||
collection::init($session, $collection, isset($data['_from'], $data['_to']));
|
||||
public static function write(
|
||||
string $collection,
|
||||
?array $data = [],
|
||||
bool $check = false,
|
||||
?terminal $terminal = null,
|
||||
array &$errors = []
|
||||
): ?string {
|
||||
try {
|
||||
// Инициализация коллекции
|
||||
collection::initialize($collection, isset($data['_from'], $data['_to']) ? type::edge : type::document);
|
||||
|
||||
if (isset($data['_from'], $data['_to'])) {
|
||||
// Ребро
|
||||
if (isset($data['_from'], $data['_to'])) {
|
||||
// Ребро
|
||||
|
||||
// Инициализация обработчика рёбер
|
||||
$documents = new _edge_handler($session);
|
||||
// Инициализация обработчика рёбер
|
||||
$documents = new _edge_handler(connection::$session);
|
||||
|
||||
// Инициализация ребра
|
||||
$document = new _edge();
|
||||
// Инициализация ребра
|
||||
$document = new _edge();
|
||||
|
||||
// Инициализация вершин
|
||||
$_from = $data['_from'];
|
||||
$_to = $data['_to'];
|
||||
// Инициализация вершин
|
||||
$_from = $data['_from'];
|
||||
$_to = $data['_to'];
|
||||
|
||||
// Деинициализация из входных данных
|
||||
unset($data['_from'], $data['_to']);
|
||||
} else {
|
||||
// Вершина
|
||||
// Деинициализация из входных данных
|
||||
unset($data['_from'], $data['_to']);
|
||||
} else {
|
||||
// Вершина
|
||||
|
||||
// Инициализация обработчика вершин
|
||||
$documents = new _document_handler($session);
|
||||
// Инициализация обработчика вершин
|
||||
$documents = new _document_handler(connection::$session);
|
||||
|
||||
// Инициализация вершины
|
||||
$document = new _document();
|
||||
// Инициализация вершины
|
||||
$document = new _document();
|
||||
}
|
||||
|
||||
// Инициализация даты создания
|
||||
$created = time();
|
||||
|
||||
foreach (['created' => $created, 'updated' => $created] + $data as $key => $value) {
|
||||
// Перебор параметров
|
||||
|
||||
// Запись в инстанцию документа
|
||||
$document->set($key, $value);
|
||||
}
|
||||
|
||||
// Запись на сервер и его ответ в буфер возврата
|
||||
$id = isset($_from, $_to) ? $documents->saveEdge($collection, $_from, $_to, $document) : $documents->insert($collection, $document);
|
||||
|
||||
if ($check && $documents->has($collection, $id)) {
|
||||
// Найден записанный документ
|
||||
|
||||
// Запись в вывод
|
||||
if ($terminal instanceof terminal) $terminal::write("В коллекции \"$collection\" создан документ \"$id\"");
|
||||
} else if ($check) {
|
||||
// Не найден записанный документ
|
||||
|
||||
// Запись в вывод
|
||||
if ($terminal instanceof terminal) $terminal::write("В коллекции \"$collection\" не удалось найти созданный или создать документ");
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// Возврат идентификатора коллекции
|
||||
return $id;
|
||||
} catch (exception $e) {
|
||||
// Writing to registry of errors
|
||||
$errors[] = [
|
||||
'text' => $e->getMessage(),
|
||||
'file' => $e->getFile(),
|
||||
'line' => $e->getLine(),
|
||||
'stack' => $e->getTrace()
|
||||
];
|
||||
}
|
||||
|
||||
// Инициализация даты создания
|
||||
$created = time();
|
||||
|
||||
foreach (['created' => $created, 'updated' => $created] + $data as $key => $value) {
|
||||
// Перебор параметров
|
||||
|
||||
// Запись в инстанцию документа
|
||||
$document->set($key, $value);
|
||||
}
|
||||
|
||||
// Запись на сервер и его ответ в буфер возврата
|
||||
$id = isset($_from, $_to) ? $documents->saveEdge($collection, $_from, $_to, $document) : $documents->insert($collection, $document);
|
||||
|
||||
if ($check && $documents->has($collection, $id)) {
|
||||
// Найден записанный документ
|
||||
|
||||
// Запись в вывод
|
||||
if ($terminal instanceof terminal) $terminal::write("В коллекции \"$collection\" создан документ \"$id\"");
|
||||
} else if ($check) {
|
||||
// Не найден записанный документ
|
||||
|
||||
// Запись в вывод
|
||||
if ($terminal instanceof terminal) $terminal::write("В коллекции \"$collection\" не удалось найти созданный или создать документ");
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// Возврат идентификатора коллекции
|
||||
return $id;
|
||||
// Exit (fail)
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Обновить
|
||||
* Update
|
||||
*
|
||||
* @param _connection $session Сессия соединения с базой данных
|
||||
* @param _document $document Инстанция документа вершины
|
||||
* @param array &$errors Registry of errors
|
||||
* @param _document $document Instance of the document
|
||||
*
|
||||
* @return bool Статус обработки
|
||||
* @return bool Has the document been updated?
|
||||
*/
|
||||
public static function update(_connection $session, _document $document): bool
|
||||
public static function update(_document $document, array &$errors = []): bool
|
||||
{
|
||||
// Инициализация обработчика вершин
|
||||
$documents = new _document_handler($session);
|
||||
try {
|
||||
// Initialize the handler of documents
|
||||
$documents = new _document_handler(connection::$session);
|
||||
|
||||
// Запись даты обновления в инстанцию документа
|
||||
$document->set('updated', time());
|
||||
// Writing date of the updating to the updating document
|
||||
$document->set('updated', time());
|
||||
|
||||
// Запись в базу данных
|
||||
return $documents->update($document);
|
||||
// Writing and exit (success)
|
||||
return $documents->update($document);
|
||||
} catch (exception $e) {
|
||||
// Writing to registry of errors
|
||||
$errors[] = [
|
||||
'text' => $e->getMessage(),
|
||||
'file' => $e->getFile(),
|
||||
'line' => $e->getLine(),
|
||||
'stack' => $e->getTrace()
|
||||
];
|
||||
}
|
||||
|
||||
// Exit (fail)
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete
|
||||
*
|
||||
* @param _document $document Instance of the document
|
||||
* @param array &$errors Registry of errors
|
||||
*
|
||||
* @return bool Has the document been deleted?
|
||||
*/
|
||||
public static function delete(_document $document, array &$errors = []): bool
|
||||
{
|
||||
try {
|
||||
// Initialize the handler of documents
|
||||
$documents = new _document_handler(connection::$session);
|
||||
|
||||
// Delete abd exit (success)
|
||||
return $documents->remove($document);
|
||||
} catch (exception $e) {
|
||||
// Writing to registry of errors
|
||||
$errors[] = [
|
||||
'text' => $e->getMessage(),
|
||||
'file' => $e->getFile(),
|
||||
'line' => $e->getLine(),
|
||||
'stack' => $e->getTrace()
|
||||
];
|
||||
}
|
||||
|
||||
// Exit (fail)
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,36 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace mirzaev\arangodb\enumerations\collection;
|
||||
|
||||
// Library for ArangoDB
|
||||
use ArangoDBClient\Collection as _collection;
|
||||
|
||||
/**
|
||||
* Types of collections
|
||||
*
|
||||
* @package mirzaev\arangodb\enumerations\collection
|
||||
*
|
||||
* @license http://www.wtfpl.net/ Do What The Fuck You Want To Public License
|
||||
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
|
||||
*/
|
||||
enum type
|
||||
{
|
||||
case document;
|
||||
case edge;
|
||||
|
||||
/**
|
||||
* Read code of the type from library for ArangoDB
|
||||
*
|
||||
* @return int Code of the type
|
||||
*/
|
||||
public function code(): int
|
||||
{
|
||||
// Exit (success)
|
||||
return match ($this) {
|
||||
type::document => _collection::TYPE_DOCUMENT,
|
||||
type::edge => _collection::TYPE_EDGE
|
||||
};
|
||||
}
|
||||
}
|
|
@ -4,12 +4,26 @@ declare(strict_types=1);
|
|||
|
||||
namespace mirzaev\arangodb;
|
||||
|
||||
// Built-in libraries
|
||||
use exception;
|
||||
|
||||
/**
|
||||
* Terminal
|
||||
*
|
||||
* lol sorry
|
||||
* i did not want to do this
|
||||
*
|
||||
* @package mirzaev\arangodb
|
||||
*
|
||||
* @license http://www.wtfpl.net/ Do What The Fuck You Want To Public License
|
||||
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
|
||||
*/
|
||||
class terminal
|
||||
{
|
||||
/**
|
||||
* Префикс
|
||||
*/
|
||||
protected const PREFIX = 'arangodb';
|
||||
protected const string PREFIX = 'arangodb';
|
||||
|
||||
/**
|
||||
* Запись в вывод
|
||||
|
|
Loading…
Reference in New Issue