21 Commits
0.1.0 ... 2.0.2

Author SHA1 Message Date
3e095e14f7 return values fix 2024-10-12 19:21:25 +03:00
577bc837d8 connection fix 2024-10-12 11:24:32 +03:00
9f7ce7e9b6 chmod 0664 2024-10-11 10:02:53 +03:00
4e04d09b32 TOTAL REBUILD 2024-10-11 10:01:40 +03:00
d0ce9e47af удалили компосер лок 2023-12-21 23:26:50 +07:00
b2088df8fb забыл что сделал 2023-12-21 23:20:32 +07:00
cb1388722c added to .gitignore 2023-07-10 06:47:42 +07:00
root
11be80b0ad remove composer.lock 2023-07-09 16:45:49 +00:00
root
48a8908afd PHP 8.2 2023-07-09 16:42:01 +00:00
root
8f5f5b44de just rules and license 2023-07-09 16:37:43 +00:00
root
8e7972d933 cool patch 2023-07-09 16:24:00 +00:00
e7da9978d0 english description 2022-11-06 10:03:56 +10:00
4daa93799e Update composer.json 2022-11-06 09:57:23 +10:00
0012a31e6b Механизм деления на данные и метаданные был порублен на мелкие кусочки 2022-10-26 06:16:30 +10:00
c5d83ceee5 Отключена проверка по умолчанию 2022-10-23 08:08:56 +10:00
d21e421b2e Доработка того же самого 2022-10-23 08:08:31 +10:00
0feecd605f Исправление записи в буфер вывода при проверке 2022-10-23 08:06:02 +10:00
2947dd694a ВАЖНОЕ ИСПРАВЛЕНИЕ СОЗДАНИЯ РЕБРА 2022-10-23 07:36:20 +10:00
b70d384053 Исправление генерации data и metadata 2022-10-23 05:25:59 +10:00
3efe35fd30 Доработка терминала 2022-10-21 23:01:47 +10:00
f6c1d756d2 Исправление инициализации и переход на PHP8.1 2022-10-09 04:12:30 +10:00
10 changed files with 698 additions and 2571 deletions

2
.gitignore vendored Normal file → Executable file
View File

@@ -1 +1,3 @@
vendor vendor
composer.lock
!.gitignore

11
LICENSE Normal file
View File

@@ -0,0 +1,11 @@
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>
Everyone is permitted to copy and distribute verbatim or modified copies of this license document, and changing it is allowed as long as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.

3
README.md Normal file
View File

@@ -0,0 +1,3 @@
# PHP 8.3 Framework for working with ArangoDB
🤟 Very simple and flexible, easy to scale and integrate

82
composer.json Normal file → Executable file
View File

@@ -1,35 +1,47 @@
{ {
"name": "mirzaev/arangodb", "name": "mirzaev/arangodb",
"description": "Реализация управления хранилищем данных ArangoDB", "description": "Simple PHP-framework for ArangoDB",
"keywords": [ "readme": "README.md",
"ArangoDB" "keywords": [
], "ArangoDB"
"type": "library", ],
"license": "WTFPL", "type": "framework",
"homepage": "https://git.hood.su/mirzaev/arangodb", "license": "WTFPL",
"authors": [ "homepage": "https://git.hood.su/mirzaev/arangodb",
{ "authors": [
"name": "Arsen Mirzaev Tatyano-Muradovich", {
"email": "arsen@mirzaev.sexy", "name": "Arsen Mirzaev Tatyano-Muradovich",
"homepage": "https://mirzaev.sexy", "email": "arsen@mirzaev.sexy",
"role": "Developer" "homepage": "https://mirzaev.sexy",
} "role": "Developer"
], }
"require": { ],
"php": "^8.0.0", "support": {
"triagens/arangodb": "~3.2" "email": "arsen@mirzaev.sexy",
}, "wiki": "https://git.mirzaev.sexy/mirzaev/arangodb/manual",
"require-dev": { "issues": "https://git.mirzaev.sexy/mirzaev/arangodb/issues"
"phpunit/phpunit": "^9.3.3" },
}, "funding": [
"autoload": { {
"psr-4": { "type": "funding",
"mirzaev\\arangodb\\": "mirzaev/arangodb/system" "url": "https://fund.mirzaev.sexy"
} }
}, ],
"autoload-dev": { "require": {
"psr-4": { "php": "^8.2",
"mirzaev\\arangodb\\tests\\": "mirzaev/arangodb/tests" "triagens/arangodb": "~3.8"
} },
} "require-dev": {
} "phpunit/phpunit": "^9.3.3"
},
"autoload": {
"psr-4": {
"mirzaev\\arangodb\\": "mirzaev/arangodb/system"
}
},
"autoload-dev": {
"psr-4": {
"mirzaev\\arangodb\\tests\\": "mirzaev/arangodb/tests"
}
}
}

2175
composer.lock generated

File diff suppressed because it is too large Load Diff

284
mirzaev/arangodb/system/collection.php Normal file → Executable file
View File

@@ -1,83 +1,201 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
namespace mirzaev\arangodb; namespace mirzaev\arangodb;
use mirzaev\arangodb\terminal; // Files of the project
use mirzaev\arangodb\connection,
use ArangoDBClient\Connection as _connection; mirzaev\arangodb\terminal,
use ArangoDBClient\Collection as _collection; mirzaev\arangodb\enumerations\collection\type;
use ArangoDBClient\CollectionHandler as _collection_handler;
// Library for ArangoDB
/** use ArangoDBClient\Statement as _statement,
* Коллекция ArangoDBClient\Document as _document,
* ArangoDBClient\CollectionHandler as _collection_handler;
* @package mirzaev\arangodb
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy> // Built-in libraries
*/ use exception;
class collection
{ /**
/** * Collection
* Инициализация *
* * @package mirzaev\arangodb
* @param _connection $connection Инстанция соединения *
* @param string $name Название * @license http://www.wtfpl.net/ Do What The Fuck You Want To Public License
* @param bool $edge Это ребро? (иначе: вершина) * @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
* */
* @return string|null Идентификатор class collection
*/ {
public static function init(_connection $connection, string $name, bool $edge = false): ?string /**
{ * Initialize a collection
// Инициализация *
$collections = new _collection_handler($connection); * @param string $collection Name of the collection
* @param type $type Type of the collection
if (!$collections->has($name)) { * @param ?terminal $terminal Инстанция терминала
// Коллекция не найдена * @param array &$errors Registry of errors
*
// Запись в вывод * @return string|null Identifier of the collection
terminal::write("Коллекция \"$name\" не найдена"); */
public static function initialize(string $name, type $type = type::document, ?terminal $terminal = null, array &$errors = []): ?string
// Инициализация {
$collection = new _collection(); try {
// Инициализация
// Настройка $collections = new _collection_handler(connection::$session);
$collection->setName($name);
$collection->setType($edge ? 'edge' : 'document'); if (!$collections->has($name)) {
// Не найдана коллекция
// Запись коллекции на сервер и его ответ в буфер возврата
$id = $collections->create($name); // Запись в вывод
if ($terminal instanceof terminal) $terminal::write("Not found $type collection: $name");
if ($collections->has($name)) {
// Коллекция найдена (записана) // Запись коллекции на сервер и его ответ в буфер возврата
$id = $collections->create($name, ['type' => $type->code()]);
// Запись в вывод
terminal::write("Создана коллекция \"$name\""); if ($collections->has($name)) {
// Коллекция найдена (записана)
// Возврат идентификатора коллекции
return $id; // Запись в вывод
} if ($terminal instanceof terminal) $terminal::write("Created $type collection: $name");
}
} // Возврат идентификатора коллекции
return $id;
/** }
* Поиск } else {
* // Найдена коллекция
* @param _connection $connection Соединение
* @param string $collection Название // Возврат идентификатора коллекции
* @param array $condition Условия return $name;
* }
* @return array|null Коллекция, если найдена } catch (exception $e) {
*/ // Writing to registry of errors
public static function search(_connection $connection, string $name, array $condition): ?array $errors[] = [
{ 'text' => $e->getMessage(),
// Инициализация 'file' => $e->getFile(),
$collections = new _collection_handler($connection); 'line' => $e->getLine(),
'stack' => $e->getTrace()
if ($collections->has($name)) { ];
// Коллекция найдена }
return $collections->byExample($name, $condition)->getAll(); return null;
} }
}
} /**
* Execute
*
* @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 Instance of the document
*/
public static function execute(string $query, array $parameters = [], array &$errors = []): _document|string|array|int|null
{
try {
// Statement instance initialization
$instance = new _statement(
connection::$session,
[
'query' => $query,
"batchSize" => 1000,
"sanitize" => true
]
);
// Binds application
$instance->bind($parameters);
// Sending the request
$response = $instance->execute();
// Инициализация буфера вывода
$buffer = [];
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()
];
}
// Exit (fail)
return null;
}
/**
* Truncate
*
* @param string $name Name of the collection
* @param array &$errors Registry of errors
*
* @return bool Статус выполнения
*/
public static function truncate(string $collection, array &$errors = []): bool
{
try {
// Initizlizing of the collection handler
$collections = new _collection_handler(connection::$session);
if ($collections->has($collection)) {
// Fount the collection
// 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;
}
}

337
mirzaev/arangodb/system/connection.php Normal file → Executable file
View File

@@ -4,198 +4,205 @@ declare(strict_types=1);
namespace mirzaev\arangodb; namespace mirzaev\arangodb;
use ArangoDBClient\Connection as _connection; // Library for ArangoDB
use ArangoDBClient\Exception as _exception; use ArangoDBClient\Connection as _connection,
use ArangoDBClient\UpdatePolicy as _update; ArangoDBClient\Exception as _exception,
use ArangoDBClient\ConnectionOptions as _options; ArangoDBClient\UpdatePolicy as _update,
ArangoDBClient\ConnectionOptions as _options;
// Built-in libraries
use exception; use exception;
/** /**
* Подключение * Connection
* *
* @package mirzaev\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> * @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
*/ */
final class connection 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 Настройки * @param array $settings Настройки
*/ *
public function __construct(array $settings = null) * @todo ПЕРЕДЕЛАТЬ ПОЛНОСТЬЮ
{ */
// Запись 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('adress', $settings['adress'] ?? $settings['endpoint']);
@$this->__set('name', $settings['name']); @$this->__set('storage', $settings['storage'] ?? $settings['database']);
@$this->__set('password', $settings['password']); @$this->__set('auth', $settings['auth']);
@$this->__set('connection', $settings['connection']); @$this->__set('name', $settings['name']);
@$this->__set('timeout_connect', $settings['timeout_connect']); @$this->__set('password', $settings['password']);
@$this->__set('timeout_request', $settings['timeout_request']); @$this->__set('connection', $settings['connection']);
@$this->__set('reconnect', $settings['reconnect']); @$this->__set('timeout_connect', $settings['timeout_connect']);
@$this->__set('create', $settings['create']); @$this->__set('timeout_request', $settings['timeout_request']);
@$this->__set('update', $settings['update'] ?? $settings['policy']); @$this->__set('reconnect', $settings['reconnect']);
@$this->__set('journal', $settings['journal']); @$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([ static::$session = new _connection([
_options::OPTION_ENDPOINT => $this->adress, _options::OPTION_ENDPOINT => $this->adress,
_options::OPTION_DATABASE => $this->storage, _options::OPTION_DATABASE => $this->storage,
_options::OPTION_AUTH_TYPE => $this->auth, _options::OPTION_AUTH_TYPE => $this->auth,
_options::OPTION_AUTH_USER => $this->name, _options::OPTION_AUTH_USER => $this->name,
_options::OPTION_AUTH_PASSWD => $this->password, _options::OPTION_AUTH_PASSWD => $this->password,
_options::OPTION_CONNECTION => $this->connection, _options::OPTION_CONNECTION => $this->connection,
_options::OPTION_CONNECT_TIMEOUT => $this->timeout_connect, _options::OPTION_CONNECT_TIMEOUT => $this->timeout_connect,
_options::OPTION_REQUEST_TIMEOUT => $this->timeout_request, _options::OPTION_REQUEST_TIMEOUT => $this->timeout_request,
_options::OPTION_RECONNECT => $this->reconnect, _options::OPTION_RECONNECT => $this->reconnect,
_options::OPTION_CREATE => $this->create, _options::OPTION_CREATE => $this->create,
_options::OPTION_UPDATE_POLICY => $this->update, _options::OPTION_UPDATE_POLICY => $this->update,
]); ]);
} }
/** /**
* Записать свойство * Записать свойство
* *
* @param mixed $name Название * @param mixed $name Название
* @param mixed $value Значение * @param mixed $value Значение
*/ */
public function __set(string $name, mixed $value): void public function __set(string $name, mixed $value): void
{ {
match ($name) { match ($name) {
'adress', 'endpoint' => $this->adress = $value ?? throw new exception("Свойство \"$name\" не может быть пустым", 500), 'adress', 'endpoint' => $this->adress = $value ?? throw new exception("Свойство \"$name\" не может быть пустым", 500),
'storage', 'database', 'db' => $this->storage = $value ?? throw new exception("Свойство \"$name\" не может быть пустым", 500), 'storage', 'database', 'db' => $this->storage = $value ?? throw new exception("Свойство \"$name\" не может быть пустым", 500),
'auth' => $this->auth = $value, 'auth' => !$value ?: $this->auth = $value,
'name' => $this->name = $value, 'name' => !$value ?: $this->name = $value,
'password' => $this->password = $value, 'password' => !$value ?: $this->password = $value,
'connection' => $this->connection = $value, 'connection' => !$value ?: $this->connection = $value,
'timeout_connect' => $this->timeout_connect = $value, 'timeout_connect' => !$value ?: $this->timeout_connect = $value,
'timeout_request' => $this->timeout_request = $value, 'timeout_request' => !$value ?: $this->timeout_request = $value,
'reconnect' => $this->reconnect = $value, 'reconnect' => !$value ?: $this->reconnect = $value,
'create' => $this->create = $value, 'create' => !$value ?: $this->create = $value,
'update', 'policy' => $this->update = $value, 'update', 'policy' => !$value ?: $this->update = $value,
default => throw new exception("Свойство \"$name\" не найдено", 404) 'journal' => !$value ?: $this->journal = $value,
}; default => throw new exception("Свойство \"$name\" не найдено", 404)
} };
}
/** /**
* Прочитать свойство * Прочитать свойство
* *
* @param mixed $name Название * @param mixed $name Название
*/ */
public function __get(string $name): mixed public function __get(string $name): mixed
{ {
return match ($name) { return match ($name) {
'adress', 'endpoint' => $this->adress, 'adress', 'endpoint' => $this->adress,
'storage', 'database', 'db' => $this->storage, 'storage', 'database', 'db' => $this->storage,
'auth' => $this->auth, 'auth' => $this->auth,
'name' => $this->name, 'name' => $this->name,
'password' => $this->password, 'password' => $this->password,
'connection' => $this->connection, 'connection' => $this->connection,
'timeout_connect' => $this->timeout_connect, 'timeout_connect' => $this->timeout_connect,
'timeout_request' => $this->timeout_request, 'timeout_request' => $this->timeout_request,
'reconnect' => $this->reconnect, 'reconnect' => $this->reconnect,
'create' => $this->create, 'create' => $this->create,
'update', 'policy' => $this->update, 'update', 'policy' => $this->update,
'session' => $this->session, 'journal' => $this->journal,
default => throw new exception("Свойство \"$name\" не найдено", 404) default => throw new exception("Свойство \"$name\" не найдено", 404)
}; };
} }
/** /**
* Проверить свойство на инициализированность * Проверить свойство на инициализированность
* *
* @param mixed $name Название * @param mixed $name Название
*/ */
public function __isset(string $name): bool public function __isset(string $name): bool
{ {
return match ($name) { return match ($name) {
'adress', 'endpoint' => isset($this->adress), 'adress', 'endpoint' => isset($this->adress),
'storage', 'database', 'db' => isset($this->storage), 'storage', 'database', 'db' => isset($this->storage),
'auth' => isset($this->auth), 'auth' => isset($this->auth),
'name' => isset($this->name), 'name' => isset($this->name),
'password' => isset($this->password), 'password' => isset($this->password),
'connection' => isset($this->connection), 'connection' => isset($this->connection),
'timeout_connect' => isset($this->timeout_connect), 'timeout_connect' => isset($this->timeout_connect),
'timeout_request' => isset($this->timeout_request), 'timeout_request' => isset($this->timeout_request),
'reconnect' => isset($this->reconnect), 'reconnect' => isset($this->reconnect),
'create' => isset($this->create), 'create' => isset($this->create),
'update', 'policy' => isset($this->update), 'update', 'policy' => isset($this->update),
'session' => isset($this->session), 'journal' => isset($this->journal),
default => throw new exception("Свойство \"$name\" не найдено", 404) default => throw new exception("Свойство \"$name\" не найдено", 404)
}; };
} }
} }

271
mirzaev/arangodb/system/document.php Normal file → Executable file
View File

@@ -1,82 +1,189 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
namespace mirzaev\arangodb; namespace mirzaev\arangodb;
use mirzaev\arangodb\terminal; // Files of the project
use mirzaev\arangodb\terminal,
use ArangoDBClient\Connection as _connection; mirzaev\arangodb\connection,
use ArangoDBClient\Document as _document; mirzaev\arangodb\enumerations\collection\type;
use ArangoDBClient\Edge as _edge;
use ArangoDBClient\CollectionHandler as _collection_handler; // Librsry for ArangoDB
use ArangoDBClient\EdgeHandler as _edge_handler; use ArangoDBClient\Connection as _connection,
ArangoDBClient\Document as _document,
/** ArangoDBClient\Edge as _edge,
* Документ ArangoDBClient\DocumentHandler as _document_handler,
* ArangoDBClient\EdgeHandler as _edge_handler;
* @package mirzaev\arangodb
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy> // Built-in libraries
*/ use exception;
class document
{ /**
/** * Document
* Записать *
* * Handlers of document in ArangoDB
* @param _connection $connection Инстанция соединения *
* @param string $collection Коллекция * @package mirzaev\arangodb
* @param array $data Данные *
* * @license http://www.wtfpl.net/ Do What The Fuck You Want To Public License
* @return string|null Идентификатор * @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
*/ */
public static function write(_connection $connection, string $collection, array $data): ?string class document
{ {
// Инициализация коллекции /**
collection::init($connection, $collection, isset($data['_from'], $data['_to'])); * Write
*
if (isset($data['_from'], $data['_to'])) { * @param string $collection Коллекция
// Ребро * @param ?array $data Данные
* @param bool $check Проверка на запись в базу данных
// Инициализация обработчика рёбер * @param ?terminal $terminal Instance of the terminal
$documents = new _edge_handler($connection); * @param array &$errors Registry of errors
*
// Инициализация ребра * @return string|null Идентификатор
$document = new _edge(); *
* @todo
// Инициализация вершин * 1. Bind parameters
$_from = $data['_from']; */
$_to = $data['_to']; public static function write(
string $collection,
// Деинициализация из входных данных ?array $data = [],
unset($data['_from'], $data['_to']); bool $check = false,
} else { ?terminal $terminal = null,
// Вершина array &$errors = []
): string|null|false {
// Инициализация обработчика вершин try {
$documents = new _collection_handler($connection); // Инициализация коллекции
collection::initialize($collection, isset($data['_from'], $data['_to']) ? type::edge : type::document);
// Инициализация вершины
$document = new _document(); if (isset($data['_from'], $data['_to'])) {
} // Ребро
// Настройка // Инициализация обработчика рёбер
foreach ($data as $key => $value) { $documents = new _edge_handler(connection::$session);
// Перебор параметров
// Инициализация ребра
$document->set($key, $value); $document = new _edge();
}
// Инициализация вершин
// Запись на сервер и его ответ в буфер возврата $_from = $data['_from'];
$id = isset($_from, $_to) ? $documents->saveEdge($collection, $_from, $_to, $document) : $documents->save($collection, $document); $_to = $data['_to'];
if ($documents->has($collection, $id)) { // Деинициализация из входных данных
// Документ записан unset($data['_from'], $data['_to']);
} else {
// Запись в вывод // Вершина
terminal::write("В коллекции \"$collection\" создан документ \"$id\"");
// Инициализация обработчика вершин
// Возврат идентификатора коллекции $documents = new _document_handler(connection::$session);
return $id;
} // Инициализация вершины
} $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()
];
}
// Exit (fail)
return false;
}
/**
* Update
*
* @param array &$errors Registry of errors
* @param _document $document Instance of the document
*
* @return bool Has the document been updated?
*/
public static function update(_document $document, array &$errors = []): bool
{
try {
// Initialize the handler of documents
$documents = new _document_handler(connection::$session);
// Writing date of the updating to the updating document
$document->set('updated', time());
// 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;
}
}

View File

@@ -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
};
}
}

68
mirzaev/arangodb/system/terminal.php Normal file → Executable file
View File

@@ -1,31 +1,37 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
namespace mirzaev\arangodb; namespace mirzaev\arangodb;
class terminal // Built-in libraries
{ use exception;
/**
* Префикс /**
*/ * Terminal
protected const PREFIX = 'arangodb'; *
* lol sorry
/** * i did not want to do this
* Запись в вывод *
* * @package mirzaev\arangodb
* @param string $text Текст сообщения *
*/ * @license http://www.wtfpl.net/ Do What The Fuck You Want To Public License
public static function write(string $text): void * @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
{ */
echo self::generate_prefix() . ' ' . $text . PHP_EOL; class terminal
} {
/**
/** * Префикс
* Генерация префикса */
*/ protected const string PREFIX = 'arangodb';
public static function generate_prefix(): string
{ /**
return '[' . self::PREFIX . ']'; * Запись в вывод
} *
} * @param string $text Текст сообщения
*/
public static function write(string $text): void
{
echo sprintf("[%s] $text\n", self::PREFIX);
}
}